出现这个错误的原因是因为Java中的泛型不支持协变性。但是可以通过将参数类型声明为 extends T>来避免这个问题。所以可以通过将参数类型声明为 extends Long>来解决这个问题。
示例代码:
public static void main(String[] args) {
List integers = Arrays.asList(1, 2, 3);
Set longs = new HashSet<>();
addElements(integers, longs);
}
public static void addElements(Collection extends T> collection, Set super T> set) {
for (T t : collection) {
set.add(t);
}
}