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
2
  • what does i < copiedVals.arrayA mean? Where does copiedVals come from? Commented Oct 22, 2020 at 0:36
  • You perfectly can, but it depends what you want. Do you want all the values in the original array, or do you want a reference? Commented Oct 22, 2020 at 0:37

2 Answers 2

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

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

3 Comments

"Declare a new variable and copy each element" so it WON'T change arrayA. The last part of my answer is to warn him that he does not need to initialize a variable if he wants to use it as a reference. Where is the error??
Ah, my mistake :p
No worries haha :D
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.