2

In below code, assigning the a array object to another array object t. these two are different objects in the memory right? why changing one object is impacting other object content?

package test.main; import java.util.LinkedHashSet; import java.util.Set; public class C1 implements I1,I2{ /** * @param args */ public static void main(String[] args) { int [][] a= {{1,2}}; int [][] t= {}; t=a; t[0][0] = 3; System.out.println("t "+t[0][0]); System.out.println("a "+a[0][0]); } @Override public void staticMethod() { // TODO Auto-generated method stub } } 

output:

t 3 a 3 

2 Answers 2

5

these two are different objects in the memory right?

No, they are two different variables that refer to the very same array object.

The key is in understanding the difference between a reference variable and the object that it refers to. If you want to create two arrays that are completely different then you will want to use System.arraycopy(...). If you need to copy the array items as well, and if it is an array of objects, of references acxtually, then you'll need to do a deep copy.

Sign up to request clarification or add additional context in comments.

Comments

0
int [][] a= {{1,2}}; 

This creates one object, referenced by the variable a.

int [][] t= {}; 

This creates another object, referenced by the variable t.

t=a; 

Now the object formerly referenced by t is "forgotten", and t points to the same object as a.

That's why, when you use the variable t to modify the object, it is the same as using the variable a. It is just 2 ways of accessing the same thing. Like 2 doors to access the same room.

3 Comments

thanks, what is the best way to make a copy of an array in this case? using clone() or using temporary array?
Neither of them. As @HovercraftFullOfEels pointed out, you can use System.arraycopy().
In java 1.6 , they have introduced the Array Util class to do the same: int[] newArray = Arrays.copyOf(a, newLength);

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.