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
132 views
in Technique[技术] by (71.8m points)

Java Array Copy

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

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

1 Reply

0 votes
by (71.8m points)

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"?


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

...