有时候当我们需要复制ArrayList时,最快的方法是新建一个实例,其实每个Collection类都有一个对应的通过自己复制的构造方法。clone()方法本身是有缺陷的,不推荐使用。推荐的做法如下:
List<Double> original = // some list
List<Double> copy = new ArrayList<Double>(original);
这个问题是在做HBase项目时发现的,当Scanner获得下一个结果时,如果直接将结果add进结果集并重用ArrayList的话,最后结果集里面的内容将会是最后一个结果的重复。
修改后的代码:
List<Cell> curVals = new ArrayList<Cell>();
List<List<Cell>> results = new ArrayList<List<Cell>>();
boolean finish = false;
do {
curVals.clear();
finish = scanner.next(curVals);
List<Cell> tmp = new ArrayList<Cell>(curVals); // 复制中间结果
results.add(tmp);
} while (finish);
文章原文链接:http://stackoverflow.com/questions/715650/how-to-clone-arraylist-and-also-clone-its-contents
更新:以上例子只是浅复制(shallow clone),如果想要深复制(deep clone),需要迭代复制里面所有引用。
具体请查看http://www.itzhai.com/java-based-notebook-the-object-of-deep-and-shallow-copy-copy-copy-implement-the-cloneable-interface-serializing-deep-deep-copy.html