Home > Mobile >  The behavior of Array within an object is not making sense
The behavior of Array within an object is not making sense

Time:11-05

I am a Java beginner. I am trying to change the third element value of only "array1" within the object "ta". However, "arr1" is also getting updated even though I do not believe I changed it and I do not intend to change it. I am unable to understand why this is happening.


    public class testArrays {
    
        private int array1[] ;

    
        public testArrays(int[] arr) {
           this.array1 = arr;
        }
    
    public String toString(String name, int arr[]) {
           String outStr = "[";
           for (int i=0; i<= arr.length-1; i  ) {
           if(i < arr.length-1) 
              outStr = outStr   arr[i]   ", ";
           else
              outStr = outStr   arr[i]   "]";   
           }
           return name   " = "   outStr;    
    }
    
    public static void main(String[] args) {
        int arr1[] = {1, 2, 3, 4, 5, 6, 7};
        
        testArrays ta = new testArrays(arr1);
        
        System.out.println(ta.toString("arr1 Before ",arr1));   
        System.out.println(ta.toString("ta.array1 Before ", ta.array1));    
        
        ta.array1[2] = 333;
        
        System.out.println(ta.toString("arr1 After ",arr1));    
        System.out.println(ta.toString("ta.array1 After ", ta.array1)); 
        
    }
    
   }

Here's the output:

arr1 Before  = [1, 2, 3, 4, 5, 6, 7]
ta.array1 Before  = [1, 2, 3, 4, 5, 6, 7]
arr1 After  = [1, 2, 333, 4, 5, 6, 7]
ta.array1 After  = [1, 2, 333, 4, 5, 6, 7]

I have used debugger to trace my steps but after line 33 both arr1 and ta.array1 are getting updated instantaneously.

Here's the output I was expecting:

arr1 Before  = [1, 2, 3, 4, 5, 6, 7]
ta.array1 Before  = [1, 2, 3, 4, 5, 6, 7]
arr1 After  = [1, 2, 3, 4, 5, 6, 7]
ta.array1 After  = [1, 2, 333, 4, 5, 6, 7]

CodePudding user response:

When you do

testArrays ta = new testArrays(arr1);

It creates a new object/instance of type testArrays and it assigns the instance variable array1. It now holds the same reference as arr1 (in main). In other words, both array1 and arr1 point to the same array object in memory. Hence, you can update the array through either reference.

To avoid this, you have to create a copy of the array and pass it to testArrays class. Or you can make a copy inside the testArrays constructor as well

 testArrays ta = new testArrays(Arrays.copyOf(arr, arr.length));
 //or
 public testArrays(int[] arr) {
       this.array1 = Arrays.copyOf(arr, arr.length);
 }

Now, we have two array objects in memory. arr1 in main points to the initial array you've created and array1 points to the cloned array.


P.S: You have to update your class name from testArrays to TestArrays to follow Java's naming convention (class names start with upper case).

  • Related