java - 使用对泛型对象的非类型化引用时,遍历成员类型化集合失败

标签 java generics

<分区>

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

最佳答案

当您使用原始类型(例如 Test 而不是 Test<T> 时,编译器将其 ( JLS 4.8 ) 视为该类型 ( JLS 4.6 ) 的删除 - 即删除完全泛型,无论它们是否使用类型参数:

The type parameters of a constructor or method (§8.4.4), and the return type (§8.4.5) of a method, also undergo erasure if the constructor or method's signature is erased.

基本上,原始类型的使用被编译器视为您根本不希望该代码知道泛型的指示 - 因此方法签名被删除为:

public Collection getCollection()

... 因此编译时错误,因为推断的元素类型是 Object , 根据 JLS 14.14.2 .

关于java - 使用对泛型对象的非类型化引用时,遍历成员类型化集合失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12693535/

相关文章:

java - 在 DispatcherServlet 中未找到名称为 'dispatcher' 的 URI 的 HTTP 请求映射”

java - 字符串:如何在所有出现的字符周围插入双引号

java - Android SwipeTabs 之后 ImageView 发生变化

java - 用于指定泛型的子类显示绑定(bind)不匹配

使用反射的 Java 通用枚举类

Java 泛型,无法从 E 转换为 E

java - 我没有数据库选项(Intellij IDEA)

java - 当两个字符串具有相同的文字时执行字符串池(java)

Java泛型方法结构解释

java - 泛型和比较器