考虑这个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()`
}
}
}
循环内部存在此语法错误:
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的含义,但我想为这个类实现一个copy-constructor.复制的实例将被用作其他的快照.任何的想法?
解决方法:
变化:
Collection extends Number> dst
至 :
Collection super Number> dst
添加是不允许使用?延伸.有一些被称为Get and Put原则的东西.引自Philip Wadler的Generics and Collections书:
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以获得有关此现象的更常见解释. (但是,我更喜欢GET和PUT原则而不是生产者和消费者原则,因为它不那么令人困惑)
标签:java,generics
来源: https://codeday.me/bug/20190519/1137312.html
本文探讨了Java中一个特定的泛型使用问题,通过解析一个实际的编译错误,介绍了如何正确地使用泛型来实现类的拷贝构造函数。文章强调了GET和PUT原则的应用,并对比了PECS原则。
8436

被折叠的 条评论
为什么被折叠?



