有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java泛型编译问题:不兼容类型

考虑到这个简单的类:

    import java.util.Collection;

    public class GenericTest<T> {
      public Collection<String> getKeys() {
        return null;
      }
      public void copy(GenericTest a_from) {
        for (String x : a_from.getKeys()) {

        }
      }
    }

我得到以下编译错误,但不明白为什么

    error: incompatible types
    for (String x : a_from.getKeys()) {
      required: String
      found:    Object

如果我将copy()方法的参数改为GenericTest<;T>;,但这不是我想要的。copy()方法对任何类型的GenericTest都有效,而不仅仅是GenericTest<;T>


共 (1) 个答案

  1. # 1 楼答案

    这不是创建泛型类的方式。如果使用泛型类的原始类型,那么类中使用的所有参数化类型都会丢失其类型信息。因此,对于GenericTestraw类型,getKeys()方法签名更改为:

    public Collection getKeys() {
        return null;
    }
    

    所以,如果你在GenericTestraw类型的getKeys()方法上迭代,你会得到Object,而不是String,我不明白你为什么期望这样

    JLS Section 4.8 - Raw Types

    The type of a constructor (§8.8), instance method (§8.4, §9.4), or non-static field (§8.3) M of a raw type C that is not inherited from its superclasses or superinterfaces is the raw type that corresponds to the erasure of its type in the generic declaration corresponding to C.


    您应该在方法中使用GenericTest<T>作为参数类型,而不是原始类型。并将getKeys的返回类型更改为Collection<T>

    将课程改为:

    public class GenericTest<T> {
        public Collection<T> getKeys() {
          return null;
        }
        public void copy(GenericTest<T> a_from) {
          for (T x : a_from.getKeys()) {
    
          }
       }
    }
    

    类型T是从您为此泛型类创建的参数化类型推断出来的。对于GenericTest<String>T将在您的类中被推断为String


    参考: