不兼容的类型:List <a> cannot be converted to List<u>

时间:2019-04-25 12:59:50

标签: java generics

Could someone explain to me why this piece of code does not compile? When I replace U with ? it works. Why it is not inferred to be Object?

class Scratch {
    static <U> List<U> method(int x) {
        if (x < 50) {
            return new ArrayList<String>();
        } else {
            return new ArrayList<Number>();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

因为ArrayList<Object>ArrayList<String>不是相关类型,所以ArrayList<String>不能从ArrayList<Object>继承并且不能转换为它。

如果有一秒钟我们认为可以做到这一点,那么该代码将不是安全类型:


ArrayList<String> stringList = ...;

ArrayList<Object> objectList = stringList; // this is what is not allowed in reality

objectList.add(new Integer());

现在stringList中有一个整数,这绝对是您不希望在类型安全程序中拥有的整数。