我最近开始学习 Java,并且在使用泛型时遇到了问题。我使用参数和参数上限 NumberBox<T extends Number>
仅存储 Number
的类对象并进行比较。每当我尝试创建未知数列表 List<NumberBox<?>>
存储任何 NumberBox<T extends Number>
对象我无法添加 List<NumberBox<Short>>
使用非参数方法得到这个未知数列表static addList(List<NumberBox<?>> destinationList, List<NumberBox<?>> sourceList)
。但是,我可以使用参数方法 <T extends Number> static addListInference(List<NumberBox<?>> destinationList, List<NumberBox<T>> sourceList)
将此参数列表添加到未知数列表中。 。任何帮助表示赞赏。谢谢。
import java.util.*;
import java.lang.*;
import java.io.*;
interface Box<T> {
public T get();
public void set(T t);
public int compareTo(Box<T> other);
}
class NumberBox<T extends Number> implements Box<T> {
T t;
public NumberBox(T t) {
set(t);
}
@Override
public T get() {
return t;
}
@Override
public void set(T t) {
this.t = t;
}
@Override
public int compareTo(Box<T> other) {
int result = 0;
if (t.doubleValue() < other.get().doubleValue()) {
result = -1;
} else if (t.doubleValue() > other.get().doubleValue()) {
result = 1;
} else if (t.doubleValue() == other.get().doubleValue()) {
result = 0;
}
return result;
}
}
class MainClass {
public static <T extends Number>
void addListInference(List<NumberBox<?>> destinationList, List<NumberBox<T>> sourceList) {
destinationList.addAll(sourceList);
}
public static void addList(List<NumberBox<?>> destinationList,
List<NumberBox<?>> sourceList) {
destinationList.addAll(sourceList);
}
public static void main (String[] args) throws java.lang.Exception {
// your code goes here
List<NumberBox<?>> list = new ArrayList<>();
List<NumberBox<Short>> shortList = new ArrayList<>();
shortList.add(new NumberBox<Short>((short) 1));
// this one fails
MainClass.addList(list, shortList);
// this one works
MainClass.addListInference(list, shortList);
}
}
最佳答案
问题在于
List<NumberBox<?>>
不是 的父类(super class)
List<NumberBox<Short>>
因为List<Superclass>
List<Subclass>
的父类(super class).
无需类型变量 T
即可使其工作使用:
List<? extends NumberBox<?>>
关于java - 无法将 List<SomeClass<SomeClass 的边界类型的子级>> 添加到 List<SomeClass<?>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37377399/