I'm using Oracle JDK 7u79. I don't know why the code below produces compilation error:
package generics;
import java.util.Collection;
import java.util.Collections;
class SomeClass {
public Collection<String> getStringCollection() {
return Collections.singleton("hello");
}
}
class SomeTypedClass<T> {
public Collection<String> getStringCollection() {
return Collections.singleton("hello");
}
}
public class SomeTest {
public static void main(String[] args) {
final int length1 = new SomeClass() .getStringCollection().iterator().next().length();
final int length2 = new SomeTypedClass().getStringCollection().iterator().next().length(); // compilation error
}
}
Error:
Error:(21, 89) java: cannot find symbol
symbol: method length()
location: class java.lang.Object
I've specified constant generics type Collection<String>
as method parameter for getStringCollection()
so I think both SomeClass
and SomeTypedClass
should be compiled without error.
Why this happen? And what is the proper solution which is getting constantly typed Collection
without casting?