有没有可能指定未知的泛型类型是自我引用的?
一个失败的尝试:
import java.util.*;
class Generics {
public enum A { A1, A2 }
public enum B { B1, B2 }
public static List<? extends Enum<?>> listFactory(String[] args) {
if (args.length == 0) {
return new ArrayList<A>(Arrays.asList(A.A1, A.A2));
} else {
return new ArrayList<B>(Arrays.asList(B.B1, B.B2));
}
}
public static void main(String[] args) {
List<? extends Enum<?>> lst = listFactory(args);
dblList(lst);
System.out.println(lst);
}
public static <EType extends Enum<EType>> void dblList(List<EType> lst) {
int size = lst.size();
for (int i = 0; i < size; i++) {
lst.add(lst.get(i));
}
}
}
这会导致编译错误:
Generics.java:17: error: method dblList in class Generics cannot be applied to given types;
dblList(lst);
^
required: List<EType>
found: List<CAP#1>
reason: inferred type does not conform to declared bound(s)
inferred: CAP#1
bound(s): Enum<CAP#1>
where EType is a type-variable:
EType extends Enum<EType> declared in method <EType>dblList(List<EType>)
where CAP#1 is a fresh type-variable:
CAP#1 extends Enum<?> from capture of ? extends Enum<?>
1 error
理想情况下,
listFactory()
的返回类型应该表示列表包含自引用泛型类型(其确切类型未知)。这个是否可能?如果是,
listFactory()
和 lst
的类型应该是什么?
List<? super EType>
作为dblist
参数类型吗? - Danail AlexievdblList((List)lst)
。 - ZhongYuEnumSet.allOf
可以有一个更宽松的签名<E extends Enum<?>
,它应该可以正常工作。 - ZhongYu