Possible Duplicate:
Generics in for each loop problem if instance does not have generic type assigned
Could someone clarify why iterate1()
is not accepted by compiler (Java 1.6)? I do not see why iterate2()
and iterate3()
are much better.
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