Same as @Barak's solution (serialize and deserialize) with examples (as some people could not understand and vote for it)
public static <T extends Serializable> T deepCopy(T obj) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { ObjectOutputStream oos = new ObjectOutputStream(baos);
Using:
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]]]
Venkata Raju Aug 07 '14 at 17:47 2014-08-07 17:47
source share