有 Java 编程相关的问题?

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

java奇数编译泛型类和列表错误

因此,当使用一个具有列表(或映射或集合等)属性的泛型类时,我遇到了一个奇怪的编译错误

尝试迭代(使用foreach)列表时发生编译错误:

Sample.java:11: error: incompatible types
        for (String string : s.getStringList()) {
  required: String
  found:    Object

我只想说清楚,我知道这个问题有一个简单的解决方法,但我想了解代码的错误所在

以下是我创建的示例:

import java.util.List;

public class Sample<T> {

    public List<String> stringList;

    public static void main(String[] args) {
        Sample s = new Sample();

        // Why this doesn't work?
        for (String string : s.getStringList()) {

        }

        // Why does both of the following work?
        List<String> newList = s.getStringList();

        Sample<Object> s2 = new Sample<>();
        for (String string : s2.getStringList()) {

        }

    }

    public List<String> getStringList() {
        return stringList;
    }

}

共 (1) 个答案

  1. # 1 楼答案

    这些线

    Sample s = new Sample();
    
    // Why this doesn't work?
    for (String string : s.getStringList()) {
    
    }
    

    不要工作,因为您正在使用Sample类的raw形式。当使用类的原始形式时,类中的所有泛型,甚至不相关的泛型,都会执行类型擦除。这意味着getStringList现在只返回ListObject,而不是List<String>String

    Java的这一部分是在Java1.5中引入泛型的,因此现在使用泛型的类的旧版本将是向后兼容的。这样一来,在List上迭代的东西(之前必须使用Object)仍然可以通过使用List的原始形式使用Object

    {a1}处理原始类型:

    More precisely, a raw type is defined to be one of:

    • The reference type that is formed by taking the name of a generic type declaration without an accompanying type argument list.

    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.

    (我的)

    理由是:

    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 generics 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.