<分区>
Possible Duplicate:
Generics in for each loop problem if instance does not have generic type assigned
有人能解释一下为什么编译器 (Java 1.6) 不接受 iterate1()
吗?我不明白为什么 iterate2()
和 iterate3()
更好。
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()) {
// ...
}
}
}
编译器输出:
$ 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