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]