0

I know when copy array in java one need copy each element individually, but it seems use arrayA = arrayB, and later modify arrayB will also modify arrayA. Could anyone explain why is that? For example:

  int i;
  int[] arrayA = new int[ ]{0,1,2,3,-4,-5,-6,-7};
  int[] arrayB = new int[8];

  // directly use = gives unexpcted result
  arrayB = arrayA;
  
  for (i = 0; i < arrayA.length; ++i) {
      if (arrayA[i] < 0) {
          arrayA[i] = 0;
      }
  }

  /*
  The normal method
  for (i = 0; i < arrayB.length; ++i) {
     if (arrayB[i] < 0) {
        arrayB[i] = 0;
     }
  }
  */

  System.out.println("\nOriginal and new values: ");
  for (i = 0; i < arrayA.length; ++i) {
     System.out.println("arrayA: " +arrayA[i] + "   ArrayB: " + arrayB[i]);
  }
  System.out.println();

The out put is:

Original and new values: 
arrayA: 0   ArrayB: 0
arrayA: 1   ArrayB: 1
arrayA: 2   ArrayB: 2
arrayA: 3   ArrayB: 3
arrayA: 0   ArrayB: 0
arrayA: 0   ArrayB: 0
arrayA: 0   ArrayB: 0
arrayA: 0   ArrayB: 0
sxy
  • 61
  • 6

2 Answers2

4

When you say arrayB = arrayA, arrayB is not the array itself, it's just a reference to arrayA. So, if you want arrayB to be an independent array, you should declare it

int[] arrayB = new int[<array size>];

Then, you should copy each element of arrayA to arrayB

But if you don't need arrayB to be an independent array, you do not need to initialize it, you could just do

int[] arrayB = arrayA;

Please check out THIS link

Aleksandrus
  • 1,589
  • 2
  • 19
  • 31
1

In your case arrayA and arrayB both are references when referred without the [] brackets.

arrayA = arrayB;

This changes the reference of arrayA to point to arrayB. This refers to the memory address of the first block of the array. Direct assignment simply points the reference to this memory allocation but does not copy actual values.

This question is related and you should check for a detailed explanation. Array assignment and reference in Java

mayankbatra
  • 2,578
  • 3
  • 16
  • 16