正如其他人所指出的那样,克隆ArrayList
并不克隆它的元素。如果你想做一个内容的深层副本,有一个巧妙的技巧:序列化和反序列化数组。 (这是可行的,因为ArrayList
和Integer
都执行Serializable
。)但是,这并没有摆脱禁止未经检查的转换警告的需要。
// Write the object out to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(this.items);
byte[] bytes = bos.toByteArray();
// Retrieve an input stream from the byte array and read
// a copy of the object back in.
ObjectInputStream in = new ObjectInputStream(
new ByteArrayInputStream(bytes));
ArrayList<Integer> items = (ArrayList<Integer>) in.readObject();
如果您的整个对象可以被声明为Serializable,那么可以使用它来代替克隆操作来进行深度复制。此外,请参阅this article,以避免从ByteArrayOutputStream
复制字节的开销。
当然,没有必要对Integer对象进行深层复制。 – 2012-01-18 04:29:54