Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have an IntArray A.

int[] A={1,2,3};

and I copy it to B.

int[] B=A;

now I want to change element in A;

A[1]=B[2];

I would expect A now becomes {1,3,3} where B stays the same {1,2,3}.

Why is B changed to [1,3,3]?

See Question&Answers more detail:os

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

1 Answer

They both are not individual arrays.

You wrote

int[] B=A;

Because there are pointing to the same array.

If you change A automatically B changes.

If you want to make B constant create a new array in the name of B.

int[] B = new int[3];

As you confused with pass by reference and value :Is Java "pass-by-reference" or "pass-by-value"?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...