I have found a strange behavior when working with generics.
In this class Foo<T>
, the strings
member doesn't have anything to do with T
:
package test;
import java.util.ArrayList;
public class Foo<T> {
ArrayList<String> strings;
T getSome() {
return null;
}
}
The class is used in main:
package test;
public class Main {
public static void main() {
Foo<Integer> intFoo = new Foo<>();
Integer i = intFoo.getSome();
String s1 = intFoo.strings.get(0);
Foo rawFoo = new Foo();
Object o = rawFoo.getSome();
String s2 = rawFoo.strings.get(0); // Compilation error on this line
}
}
The compilation error is "incompatible types. required: String found: Object".
It appears that Java forgets the String
type argument to ArrayList
when raw type of Foo
is used.
My java version is 1.7.0_21
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…