-
遍历-克隆-构造
遍历集合中的元素(所有元素重载了clone()方法),手动克隆每个元素,然后构造新的集合。
效率低,请尽量避免重载clone,为什么呢,看
accessing-clone-from-java-lang-object这个
-
遍历-new-构造
这个和上面那个差不多,也是遍历集合的元素,但是在将元素加入到新的集合中前,先使用new的方式,产生一个新的对象,再加入集合中。
-
下面这个是摘自stackoverflow上
class Dog { public Dog() { ... } // Regular constructor public Dog(Dog dog) { // Copy all the fields of Dog. } }
然后进行拷贝
public static List<Dog> cloneList(List<Dog> dogList) { List<Dog> clonedList = new ArrayList<Dog>(dogList.size()); for (Dog dog : dogList) { clonedList.add(new Dog(dog)); } return clonedList; }
-
下面的这种是利用标准的集合构造函数,我常用,我常用,我常用
List<Double> original = // some list List<Double> copy = new ArrayList<Double>(original);
-
下面这种通用性比较强,但是效率也比较低(使用序列化的方式,Java Object Serialization (JOS)),对于算法要求不高的情况下,很好使的。
@SuppressWarnings("unchecked") 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); List<T> dest = (List<T>) in.readObject(); return dest; }
引申一下就成了下面这种
public static Object copy(Object orig) {
Object obj = null;
try {
// Write the object out to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(orig);
out.flush();
out.close();
// Make an input stream from the byte array and read
// a copy of the object back in.
ObjectInputStream in = new ObjectInputStream(
new ByteArrayInputStream(bos.toByteArray()));
obj = in.readObject();
}
catch(IOException e) {
e.printStackTrace();
}
catch(ClassNotFoundException cnfe) {
cnfe.printStackTrace();
}
return obj;
}
-
这种是也是在stackoverflow上看到有人说
google-code
上有个library
,好吧,以后就用它了,求鉴别。Cloner cloner=new Cloner(); MyClass clone=cloner.deepClone(o); // clone is a deep-clone of o
check it out at here,如果不好下载,换个地址
-
还有人说用commons-lang-2.3.jar也可以。
List<YourObject> newList = new ArrayList<YourObject>(); foreach(YourObject obj : oldList){ newList.add((YourObject)SerializationUtils.clone(obj)); }
完了就有人评论说,要注意为什么commons-lang的版本这么低?
See the release history here -
还有个,不清楚,没试过。
import org.apache.commons.lang.SerializationUtils clonedObj = SerializationUtils.clone(oldObj);
我是来打酱油的。