且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

与通用编译错误

更新时间:2023-09-15 22:42:22

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:

The use of raw types is allowed only as a concession to compatibility of legacy code. The use of raw types in code written after the introduction of genericity into the Java programming language is strongly discouraged. It is possible that future versions of the Java programming language will disallow the use of raw types.

According to Angelika Langer's excellent Java Generics FAQ,

Methods or constructors of a raw type have the signature that they would have after type erasure. A method or constructor call to a raw type generates an unchecked warning if the erasure changes the argument types.

So by constructing MyClass as a raw type (that is, as MyClass and not MyClass<?>), you have opted out of generics entirely, and the return type of getMyTypes() is now the raw type Collection, and not Collection<MyType>. As a result, you can't use the enhanced for syntax with type MyType, you'd have to use Object instead.

Of course, the better solution is just to use MyClass<?> (rather than just MyClass) when you mean a MyClass of an unknown parameterized type.