我在阅读泛型时遇到了PECS(制片extends人和消费者的super简称).
能否给我一个人解释如何使用佩奇之间解决困惑extends和super?
我有一个声明如下的泛型方法
public static <E extends Number> List<E> myListOfElements(List<E> list) {
return new ArrayList<Integer>();
}
Run Code Online (Sandbox Code Playgroud)
我从中理解的是它期望一个类型的List Number作为输入扩展,List类型Number作为输出扩展.当我尝试返回一个ArrayList<Integer>r时,它会产生编译错误
Type mismatch: cannot convert from ArrayList<Integer> to List<E>
Run Code Online (Sandbox Code Playgroud)
我不明白这里有什么问题.为什么我不能回到ArrayList<Integer>这里?
我想知道为什么以下演员阵容未经检查:
==更新1 ==
我知道我们在运行时有类型擦除.介意输入参数是一个ArrayList而不是一些随机列表.ArrayList实施List和RandomAccess.我知道这个演员不适用于LinkedList或MySpecialArrayList.但是这个方法的参数禁止这样做.我知道(直到人们移除List或RandomAccess从ArrayList演员阵容不会在运行时失败,但为什么演员阵容未经检查?
==结束更新1 ==
private static <L extends List<GenericTokenType<?>> & RandomAccess> L castArrayList(ArrayList<GenericTokenType<?>> instance) {
return (L) instance;
}
Run Code Online (Sandbox Code Playgroud)
我简化为[仍然警告]
private static <L extends List> L castArrayList(ArrayList instance) {
return (L) instance;
}
Run Code Online (Sandbox Code Playgroud)
和[没有警告]
private static List castArrayList(ArrayList instance) {
return (List) instance;
}
Run Code Online (Sandbox Code Playgroud)
为什么这不起作用.L是一个List(不是运行时类型,但编译器应该得到它.
重新解释一下这个问题:为什么它不适用于泛型参数返回类型?谢谢