java泛型如何深复制,如何使用通配符在Java中复制泛型集合

本文探讨了Java中一个特定的泛型使用问题,通过解析一个实际的编译错误,介绍了如何正确地使用泛型来实现类的拷贝构造函数。文章强调了GET和PUT原则的应用,并对比了PECS原则。

考虑这个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

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值