Where is the difference between test1 and test2?
Why compilation error in test1?
import java.util.ArrayList;
import java.util.Collection;
class MyType {
}
class MyClass<T> {
private Collection<MyType> myTypes = new ArrayList<MyType>();
private Collection<T> myTs = new ArrayList<T>();
public Collection<MyType> getMyTypes() {
return myTypes;
}
public Collection<T> getMyTs() {
return myTs;
}
}
public class TestSimple {
public void test1() {
MyClass myClass = new MyClass();
for (MyType myType : myClass.getMyTypes()) {
}
}
public void test2() {
MyClass myClass = new MyClass();
Collection<MyType> myTypes = myClass.getMyTypes();
for (MyType myType : myTypes) {
}
}
public void test3() {
MyClass<Long> myClass = new MyClass<Long>();
for (Long myType : myClass.getMyTs()) {
}
}
}
If you define a generic constraint on a class, and then instantiate the class without providing any generic constraint (that is, you leave off the
<>completely), then you’ve just stepped into the realm of Raw Types, where nothing is the same anymore.According to the Java Language Spec:
According to Angelika Langer’s excellent Java Generics FAQ,
So by constructing
MyClassas a raw type (that is, asMyClassand notMyClass<?>), you have opted out of generics entirely, and the return type ofgetMyTypes()is now the raw typeCollection, and notCollection<MyType>. As a result, you can’t use the enhancedforsyntax with typeMyType, you’d have to useObjectinstead.Of course, the better solution is just to use
MyClass<?>(rather than justMyClass) when you mean aMyClassof an unknown parameterized type.