gpt4 book ai didi

java - 如何使用通配符在 Java 中复制通用集合

转载 作者:搜寻专家 更新时间:2023-10-31 20:01:29 26 4
gpt4 key购买 nike

考虑这个 java 类:

import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;


public class NumberSet {

private Collection<? extends Number> numbers;

public NumberSet(Collection<? extends Number> numbers) {
this.numbers = numbers;
}

public NumberSet(NumberSet other) {

//copy other.numbers to this.numbers
numbers = new LinkedList<>();
for (Iterator<? extends Number> it = other.numbers.iterator(); it.hasNext();) {
numbers.add(it.next()); // Here's Syntax Error near `it.next()`
}

}
}

for 循环中存在语法错误:

actual argument Number cannot be converted to CAP#1 by method invocation conversion
where E is a type-variable:
E extends Object declared in interface Collection
where CAP#1 is a fresh type-variable:
CAP#1 extends Number from capture of ? extends Number

我理解 PECS 的含义,但是我想为这个类实现一个复制构造函数。复制的实例将用作 other 的快照。有什么想法吗?

最佳答案

改变:

 Collection<? extends Number> dst 

收件人:

 Collection<? super Number> dst

不允许使用 添加?延伸。有一种称为 GetPut 的原则。引用自 Generics and CollectionsPhilip Wadler 预订:

The Get and Put Principle: use an extends wildcard when you only get values out of a structure, use a super wildcard when you only put values into a structure, and don’t use a wildcard when you both get and put

另请查看 PECS对于这种现象的更普遍的解释。 (不过,我更喜欢 GETPUT 原则,而不是 ProducerConsumer 原则,因为它不那么困惑)

关于java - 如何使用通配符在 Java 中复制通用集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30872922/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com