java 类变量复制_Java中Collection类型变量复制注意事项

Java中Collection类型的构造器允许传入一个Collection类型变量作为参数,即可以复制旧有的Collection变量生成一个新的Collection变量。

在这个复制过程中,需要注意的是:复制的是引用,旧Collection变量中元素和新Collection变量中元素指向相同的对象。

现在有如下一段代码:

public class Main {

public static void main(String[] args) throws UnsupportedEncodingException, ParseException {

Map> map = new HashMap>();

Set set = new HashSet();

set.add("a");

set.add("b");

set.add("c");

map.put("hello", set);

Map> copied = new HashMap>(map);

System.out.println("before delete");

System.out.println(copied.get("hello"));

map.get("hello").removeAll(Arrays.asList("a", "b"));

System.out.println("after delete");

System.out.println(copied.get("hello"));

}

}运行结果如下:

before delete

[b, c, a]

after delete

[c]从中可以知道,map.get("hello")和copied.get("hello")对应的是同一个Set集合对象,因此,执行“map.get("hello").removeAll(Arrays.asList("a", "b"));”指令后,该Set集合对象中的"a"和"b"元素被去除掉,此时,执行"System.out.println(copied.get("hello"));"指令,会打印该Set集合对象中仅剩的"c"元素。

要使得复制后,对应的Set集合对象不是同一个,可以通过以下代码实现:

public class Main {

public static void main(String[] args) throws UnsupportedEncodingException, ParseException {

Map> map = new HashMap>();

Set set = new HashSet();

set.add("a");

set.add("b");

set.add("c");

map.put("hello", set);

Map> copied = new HashMap>();

Set value;

Set newValue;

for (String key : map.keySet()) {

value = map.get(key);

newValue = new HashSet(value);

copied.put(key, newValue);

}

System.out.println("before delete");

System.out.println(copied.get("hello"));

map.get("hello").removeAll(Arrays.asList("a", "b"));

System.out.println("after delete");

System.out.println(copied.get("hello"));

}

}运行后结果如下:

before delete

[b, c, a]

after delete

[b, c, a]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值