List集合的复制方式小结

方式一:

List<String> l = new ArrayList<String>();
l.add("a");
l.add("b");
l.add("c");
List<String> l2 = new ArrayList<String>(l);
l2.add("d");
System.out.println(l2);
System.out.println(l);

 跑的结果:

[a, b, c, d]

[a, b, c]

说明:通过new ArrayList<T>(List<T> srcList)的方式复制一个集合,是单独开辟了一个内存空间,并且内容跟源集合的内容一样。对新集合的修改并不影响源集合。

方式二:

List<String> l = new ArrayList<String>();
l.add("a");
l.add("b");
l.add("c");
List<String> l2 = new ArrayList<String>();
l2.addAll(l);
l2.add("d");
System.out.println(l2);
System.out.println(l);

打印结果:

[a, b, c, d]

[a, b, c] 

说明:通过addAll的方法复制一个集合,新的集合也是单独开辟了一个内存空间。当然新集合的操作不影响源集合。

方式三:

List<String> l = new ArrayList<String>();
l.add("a");
l.add("b");
l.add("c");
List<Object> l2 = new ArrayList<Object>(Arrays.asList(new Object[l.size()]));
Collections.copy(l2, l);
l2.add("d");
System.out.println(l2);
System.out.println(l);

 打印结果:

[a, b, c, d]

[a, b, c]

说明:使用集合的工具类的静态方法Collections.copy(List desList, List srcList)的方式复制集合,得到的也是一个位于内存中不同空间的副本。

注意这种方式,如果你直接这样写:

List<String> l2 = new ArrayList<String>();
Collections.copy(l2, l);

 会报错:java.lang.IndexOutOfBoundsException: Source does not fit in dest

原因是你使用该方法时,会先比较目标集合和源集合的size,而你直接new ArrayList<String>();还没来得及复制,目标集合的size为0,和源集合的size不一样,就会报错。注:new ArrayList(int size)定义的是该集合的的容纳能力为size,并不是说目标集合中就有了size个元素。所以要这样写:new ArrayList<Object>(Arrays.asList(new Object[l.size()]));

方式四:

List<String> l = new ArrayList<String>();
l.add("a");
l.add("b");
l.add("c");
List<String> l2 = l;
l2.add("d");
System.out.println(l2);
System.out.println(l);

这次的打印结果为:

[a, b, c, d]

[a, b, c, d]

说明:这种方式只是定义了另一个引用,但是指向的内容还是源集合指向的内容。所以对其修改当然会影响源集合了。 

方式五:流式拷贝(适用于集合类型为非一般类型的情形)

public static <T> List<T> deepCopy(List<T> src) throws IOException, ClassNotFoundException {  
    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();  
    ObjectOutputStream out = new ObjectOutputStream(byteOut);  
    out.writeObject(src);  

    ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());  
    ObjectInputStream in = new ObjectInputStream(byteIn);  
    @SuppressWarnings("unchecked")  
    List<T> dest = (List<T>) in.readObject();  
    return dest;  
}

对Map, Set的复制拷贝方式研究同理,这里不再赘述。

猜你喜欢

转载自raising.iteye.com/blog/2246134