Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
185 views
in Technique[技术] by (71.8m points)

Problem with assigning an array to other array in Java

public class TestingArray {

    public static void main(String[] args) {

        int iCheck = 10;
        int j = iCheck;
        j = 11;
        System.err.println("value of iCheck "+iCheck);

        int[] val1 = {1,2,9,4,5,6,7};
        int[] val2 = val1;
        val2[0] = 200;
        System.err.println("Array Value "+val1[0]);
    }
}

Output:

value of iCheck 10
Array Value 200

From the above code, I found that if any array val2 is being assigned to another array val1 and if we change any value of val2 array, the result is as well reflected for the array val1 while the same scenario is not with variable assignment. Why?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The following statement makes val2 refer to the same array as val1:

int[] val2 = val1;

If you want to make a copy, you could use val1.clone() or Arrays.copyOf():

int[] val2 = Arrays.copyOf(val1, val1.length);

Objects (including instances of collection classes, String, Integer etc) work in a similar manner, in that assigning one variable to another simply copies the reference, making both variables refer to the same object. If the object in question is mutable, then subsequent modifications made to its contents via one of the variables will also be visible through the other.

Primitive types (int, double etc) behave differently: there are no references involved and assignment makes a copy of the value.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...