java - 泛型编译错误

标签 java generics

test1和test2的区别在哪里? 为什么test1编译出错?

import java.util.ArrayList;
import java.util.Collection;

class MyType {

}

class MyClass<T> {
    private Collection<MyType> myTypes = new ArrayList<MyType>();
    private Collection<T> myTs = new ArrayList<T>();

    public Collection<MyType> getMyTypes() {
        return myTypes;
    }

    public Collection<T> getMyTs() {
        return myTs;
    }
}



public class TestSimple {

    public void test1() {    

        MyClass myClass = new MyClass();

        for (MyType myType : myClass.getMyTypes())  {

        }
    }

    public void test2() {            
        MyClass myClass = new MyClass();

        Collection<MyType> myTypes = myClass.getMyTypes();
        for (MyType myType : myTypes)  {

        }
    }

    public void test3() {
         MyClass<Long> myClass = new MyClass<Long>();

          for (Long myType : myClass.getMyTs())  {

          }        
     }

}

最佳答案

如果您在一个类上定义了一个通用约束,然后在不提供任何通用约束的情况下实例化该类(也就是说,您完全离开了 <>),那么您就进入了 Raw Types 的领域。 ,一切都不再一样了。

根据Java Language Spec :

The use of raw types is allowed only as a concession to compatibility of legacy code. The use of raw types in code written after the introduction of genericity into the Java programming language is strongly discouraged. It is possible that future versions of the Java programming language will disallow the use of raw types.

根据 Angelika Langer 的优秀 Java Generics FAQ ,

Methods or constructors of a raw type have the signature that they would have after type erasure. A method or constructor call to a raw type generates an unchecked warning if the erasure changes the argument types.

所以通过构建MyClass作为原始类型(即 MyClass 而不是 MyClass<?> ),您已完全选择退出泛型,返回类型为 getMyTypes()现在是原始类型 Collection ,而不是 Collection<MyType> .因此,您无法使用增强的 for类型为 MyType 的语法, 你必须使用 Object相反。

当然,更好的解决方案就是使用MyClass<?> (而不仅仅是 MyClass )当你的意思是 MyClass未知参数化类型。

关于java - 泛型编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7423150/

相关文章:

java - 为什么我的 GregorianCalendar 对象返回错误的星期几?

java - 在数据库中查找特定表时,为什么“显示表”比 DatabaseMetaData.getTables() 更好?

generics - 有没有办法为智能指针中的对象通用地实现一个特征?

swift - 如何在协议(protocol)中定义仅在协议(protocol)的关联类型为特定类型时才需要实现的函数

c# - 通用类型约束检查

java - 为什么Spring Security需要对权限集合进行排序?

java - Netbeans Ant 构建任务在一个输入对话框中获取多个值

java - 如何线程池一个 Spring JMS 监听器

c# - 在泛型方法中仅设置第二个参数类型

VB.NET:如何在 xml 文档中引用通用类和方法