复制一个数组 [英] Make copy of an array

查看:35
本文介绍了复制一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个不断更新的数组 a.假设 a = [1,2,3,4,5].我需要制作 a 的完全副本并将其命名为 b.如果 a 要更改为 [6,7,8,9,10]b 仍应为 [1,2,3,4,5].做这个的最好方式是什么?我尝试了一个 for 循环,例如:

I have an array a which is constantly being updated. Let's say a = [1,2,3,4,5]. I need to make an exact duplicate copy of a and call it b. If a were to change to [6,7,8,9,10], b should still be [1,2,3,4,5]. What is the best way to do this? I tried a for loop like:

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.

推荐答案

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

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

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

但是,在大多数情况下使用 clone() 可能更好:

But, probably better to use clone() in most cases:

int[] src = ...
int[] dest = src.clone();

这篇关于复制一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆