您的位置:首页 > 编程语言 > Java开发

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

2015-09-21 11:22 169 查看
Java中Collection类型的构造器允许传入一个Collection类型变量作为参数,即可以复制旧有的Collection变量生成一个新的Collection变量。

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

现在有如下一段代码:

public class Main {
public static void main(String[] args) throws UnsupportedEncodingException, ParseException {
Map<String, Set<String>> map = new HashMap<String, Set<String>>();
Set<String> set = new HashSet<String>();
set.add("a");
set.add("b");
set.add("c");
map.put("hello", set);

Map<String, Set<String>> copied = new HashMap<String, Set<String>>(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<String, Set<String>> map = new HashMap<String, Set<String>>();
Set<String> set = new HashSet<String>();
set.add("a");
set.add("b");
set.add("c");
map.put("hello", set);

Map<String, Set<String>> copied = new HashMap<String, Set<String>>();
Set<String> value;
Set<String> newValue;
for (String key : map.keySet()) {
value = map.get(key);
newValue = new HashSet<String>(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]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: