Home > Tricks & Tips > Common array clone mistake in Java

Common array clone mistake in Java


While working on my application, I’ve found one bug whereas the cause is very common in practice.

Assuming, you have an two dimensional array storing data, and you want to copy or clone it to another storage variable, this is what somebody often does:

boolean data[][] = ... // original data

// common use of clone()
boolean copied[][] = data.clone();

The problem is that, it’s not gonna working as a new fresh copy data but a reference to the original data.
The fix for this is pretty much straight forward.

public static boolean[][] cloneData(boolean[][] from) {
	boolean[][] to = new boolean[from.length][];
	for (int i = 0; i < from.length; i++) {
		to[i] = from[i].clone();
	}
	return to;
}

Cheers,
Pete Houston

Categories: Tricks & Tips Tags: ,
  1. Saofai.xoan
    May 29, 2012 at 8:48 pm

    update quá nhanh 😉

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: