Java中Collection类型变量复制注意事项
2015-09-21 11:22
169 查看
Java中Collection类型的构造器允许传入一个Collection类型变量作为参数,即可以复制旧有的Collection变量生成一个新的Collection变量。
在这个复制过程中,需要注意的是:复制的是引用,旧Collection变量中元素和新Collection变量中元素指向相同的对象。
现在有如下一段代码:
要使得复制后,对应的Set集合对象不是同一个,可以通过以下代码实现:
在这个复制过程中,需要注意的是:复制的是引用,旧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]
相关文章推荐
- java类加载器总结
- java SortedMap 升序、降序操作
- 用Jersey构建RESTful服务2--JAVA对象转成XML输出
- 请谨慎使用Java基本类型的对象类
- Spring MVC hello world annotation example
- Spring mvc 绑定Date日期
- java SE复习笔记32
- 一道经典的Java多线程编程题
- java SE复习笔记31
- 无法debug断点跟踪JDK源代码
- 帮助文档的制作javadoc
- Java注释规范
- OAuth 2.0系列教程(十一) 客户端证书请求和响应
- JAVA语言DES算法
- OAuth 2.0系列教程(九) 契约请求和响应
- OAuth 2.0系列教程(八) 授权码授权
- 【JAVA】---String 类
- Java学习之路:不走弯路,就是捷径
- OAuth 2.0系列教程(七) 请求和响应
- OAuth 2.0系列教程(六) 端点