rekowski.info David Rekowski's random stuff

Shallow array cloning according to Java Language Specification 7 section 10.7

2012-09-13

Example for shallow array cloning in java.

The Java Language Specification 7 states in section 10.7:

A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared.
The following example code demonstrates this behaviour.

package com.example.test; public class ArrayClone { public static void main(String[] args) { System.out.println("Demonstrating 2-n-level references of cloned arrays "); System.out.println("See Java Language Specification 7 section 10.7"); System.out.println("Initializing 'a' with 1, 2, 3, 4"); int[][] a = {{1, 2}, {3, 4}}; System.out.println("Initializing 'b' to be a clone of 'a'"); int[][] b = a.clone(); System.out.println("Content of 'a':"); for (int[] ae : a) { for (int e: ae) { System.out.println(e); } } System.out.println("Setting b[0][1] to 5."); b[0][1] = 5; System.out.println("Content of 'a':"); for (int[] ae : a) { for (int e: ae) { System.out.println(e); } } } }

Which produces the following output

Demonstrating 2-n-level references of cloned arrays See Java Language Specification 7 section 10.7 Initializing 'a' with 1, 2, 3, 4 Initializing 'b' to be a clone of 'a' Content of 'a': 1 2 3 4 Setting b[0][1] to 5. Content of 'a': 1 5 3 4