Assigning Array to new variable, changing original changes the new one

前端 未结 4 1328
暖寄归人
暖寄归人 2020-12-11 22:22
int[] test = {0,1,2,3,4,5};
    int[] before = test;
    System.out.println(before[2]);
    test[2] = 65;
    System.out.println(before[2]);

The fi

相关标签:
4条回答
  • 2020-12-11 22:57

    When you do before = test;, before is just a reference to test array, NO new array has been created and assigned to test. So when you look the value of before[i] you basically look at the value of test[i] and vice versa. before is just an alias of test. That's why in the second print you get 65.

    Check this text from Thinking in Java book, it will definitely help you.

    0 讨论(0)
  • 2020-12-11 23:04

    For the int's, you are correct they do not reference each other. But when you use an array, they are considered objects, so when you did the before = test, in memory they are pointing to the same object.

    0 讨论(0)
  • 2020-12-11 23:08

    Why would you not expect this to happen. You are simply assigning two variables to the same array, and then You are assigning index #2 of that array as 65, so, you should get 65 the next time you print what's on index #2.

    see examples at http://download.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html

    0 讨论(0)
  • 2020-12-11 23:08

    This is normal behavior. If you want to copy an array then you need to copy it.

    class ArrayCopyDemo {
        public static void main(String[] args) {
            char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
                    'i', 'n', 'a', 't', 'e', 'd' };
            char[] copyTo = new char[7];
    
            System.arraycopy(copyFrom, 2, copyTo, 0, 7);
            System.out.println(new String(copyTo));
        }
    }
    

    via http://download.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html

    0 讨论(0)
提交回复
热议问题