Iterating over member typed collection fails when using untyped reference to generic object
- by Alexander Pavlov
Could someone clarify why iterate1() is not accepted by compiler (Java 1.6)? I do not see why iterate2() and iterate3() are much better.
This paragraph is added to avoid silly "Your post does not have much context to explain the code sections; please explain your scenario more clearly." protection.
import java.util.Collection;
import java.util.HashSet;
public class Test<T> {
public Collection<String> getCollection() {
return new HashSet<String>();
}
public void iterate1(Test test) {
for (String s : test.getCollection()) {
// ...
}
}
public void iterate2(Test test) {
Collection<String> c = test.getCollection();
for (String s : c) {
// ...
}
}
public void iterate3(Test<?> test) {
for (String s : test.getCollection()) {
// ...
}
}
}
Compiler output:
$ javac Test.java
Test.java:11: incompatible types
found : java.lang.Object
required: java.lang.String
for (String s : test.getCollection()) {
^
Note: Test.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
1 error