Cloning multidimensional arrays in Java

In Java, calling the clone() method on an array returns a copy of the array, that is a new array containing references to the same objects as the source array. In particular, the objects themselves are not copied. As multidimensional arrays are just arrays of arrays, cloning a multidimensional array result in only the first dimension being copied, the array of the second and following dimensions are the same in the source and the destination array.

Below I present a static method to get a real clone of a multidimensional array, meaning one where all dimensions are copied, but not the objects. I use it for example, if I have a private multidimensional array in a class, and want to provide an accessor for it. To assure that the array which is returned by the accessor is totally independant of the one inside the class, all dimensions must be copied correctly (defensive copy).

Note that this implementation does not support arrays containing themselves. This will result in an infinite recursion and eventually a stack overflow.

So without further discussion, here’s the code (compatible JRE 1.3)

[sourcecode language=’java’]
/**
* Makes a copy of all dimensions of a multidimensional
* array. This function does not copy the actual objects, but
* only the references. The behavior is the same as {@link #clone()}
* but extends to all dimensions of an array.

* Note that this implementation does not handle arrays which
* contain themselves correctly. It results in a infinite recursion
* ending in a {@link StackOverflowError}.
*
* @param src a multidimensional array, either of {@link Object}s
* or of a primitive type
* @return a copy of src, so that each dimension is copied, but
* the objects are not cloned
* @author Philipp Buluschek bulu@romandie.com
*/
public static Object[] deepClone(Object[] src){
if(src == null){
return null;
}
Object[] dest = (Object[])src.clone();
for (int i = 0; i < dest.length; i++) { Object e = dest[i]; if (e != null &amp;&amp; e.getClass().isArray()) { // if it is null or not an array, it was taken care of by the clone() if (e instanceof Object[]) { // using recursion to reach all dimensions dest[i] = deepClone((Object[])e); } else { // primitive arr if(e instanceof byte[]) dest[i] = ((byte[]) e).clone(); else if(e instanceof short[]) dest[i] = ((short[]) e).clone(); else if(e instanceof int[]) dest[i] = ((int[]) e).clone(); else if(e instanceof long[]) dest[i] = ((long[]) e).clone(); else if(e instanceof float[]) dest[i] = ((float[]) e).clone(); else if(e instanceof double[]) dest[i] = ((double[]) e).clone(); else if(e instanceof boolean[])dest[i] = ((boolean[]) e).clone(); } } } return dest; } [/sourcecode] The same code using generics for JRE >= 1.5 [sourcecode language='java'] /** * Makes a copy of all dimensions of a multidimensional * array. This function does not copy the actual objects, but * only the references. The behavior is the same as {@link #clone()} * but extends to all dimensions of an array.

* Note that this implementation does not handle arrays which
* contain themselves correctly. It results in a infinite recursion
* ending in a {@link StackOverflowError}.
*
* @param src a multidimensional array, either of {@link Object}s
* or of a primitive type
* @return a copy of src, so that each dimension is copied, but
* the objects are not cloned
* @author Philipp Buluschek bulu@romandie.com
*/

@SuppressWarnings(“unchecked”)
public static T[] deepClone(T[] src){
if(src == null){
return null;
}
T[] dest = src.clone();
for (int i = 0; i < dest.length; i++) { Object e = dest[i]; if (e != null &amp;&amp; e.getClass().isArray()) { // if it is null or not an array, it was taken care of by the clone() if (e instanceof Object[]) { // using recursion to reach all dimensions dest[i] = (T)(deepClone((Object[])e)); } else { // primitive arr if(e instanceof byte[]) dest[i] = (T)((byte[]) e).clone(); else if(e instanceof short[]) dest[i] = (T)((short[]) e).clone(); else if(e instanceof int[]) dest[i] = (T)((int[]) e).clone(); else if(e instanceof long[]) dest[i] = (T)((long[]) e).clone(); else if(e instanceof float[]) dest[i] = (T)((float[]) e).clone(); else if(e instanceof double[]) dest[i] = (T)((double[]) e).clone(); else if(e instanceof boolean[])dest[i] = (T)((boolean[]) e).clone(); } } } return dest; } [/sourcecode]


Posted

in

by