与带有示例的@Barak 解决方案(序列化和反序列化)相同(因为有些人无法理解并投反对票)
public static <T extends Serializable> T deepCopy(T obj)
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try
{
ObjectOutputStream oos = new ObjectOutputStream(baos);
// Beware, this can throw java.io.NotSerializableException
// if any object inside obj is not Serializable
oos.writeObject(obj);
ObjectInputStream ois = new ObjectInputStream(
new ByteArrayInputStream(baos.toByteArray()));
return (T) ois.readObject();
}
catch ( ClassNotFoundException /* Not sure */
| IOException /* Never happens as we are not writing to disc */ e)
{
throw new RuntimeException(e); // Your own custom exception
}
}
用法:
int[][] intArr = { { 1 } };
System.out.println(Arrays.deepToString(intArr)); // prints: [[1]]
int[][] intDc = deepCopy(intArr);
intDc[0][0] = 2;
System.out.println(Arrays.deepToString(intArr)); // prints: [[1]]
System.out.println(Arrays.deepToString(intDc)); // prints: [[2]]
int[][] intClone = intArr.clone();
intClone[0][0] = 4;
// original array modified because builtin cloning is shallow
System.out.println(Arrays.deepToString(intArr)); // prints: [[4]]
System.out.println(Arrays.deepToString(intClone)); // prints: [[4]]
short[][][] shortArr = { { { 2 } } };
System.out.println(Arrays.deepToString(shortArr)); // prints: [[[2]]]
// deepCopy() works for any type of array of any dimension
short[][][] shortDc = deepCopy(shortArr);
shortDc[0][0][0] = 4;
System.out.println(Arrays.deepToString(shortArr)); // prints: [[[2]]]
System.out.println(Arrays.deepToString(shortDc)); // prints: [[[4]]]