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

Categories

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

java - 复制数组(Make copy of an array)

I have an array a which is constantly being updated.

(我有一个数组a被不断更新。)

Let's say a = [1,2,3,4,5] .

(假设a = [1,2,3,4,5] 。)

I need to make an exact duplicate copy of a and call it b .

(我需要的精确副本a并将其命名为b 。)

If a were to change to [6,7,8,9,10] , b should still be [1,2,3,4,5] .

(如果a更改为[6,7,8,9,10] ,则b仍应为[1,2,3,4,5] 。)

What is the best way to do this?

(做这个的最好方式是什么?)

I tried a for loop like:

(我尝试了像这样的for循环:)

for(int i=0; i<5; i++) {
    b[i]=a[i]
}

but that doesn't seem to work correctly.

(但这似乎无法正常工作。)

Please don't use advanced terms like deep copy, etc., because I do not know what that means.

(请不要使用深层复制等高级术语,因为我不知道这意味着什么。)

  ask by badcoder translate from so

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

1 Answer

0 votes
by (71.8m points)

You can try using System.arraycopy()

(您可以尝试使用System.arraycopy())

int[] src  = new int[]{1,2,3,4,5};
int[] dest = new int[5];

System.arraycopy( src, 0, dest, 0, src.length );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...