Bal*_*a R 543
您可以尝试使用System.arraycopy()
int[] src = new int[]{1,2,3,4,5};
int[] dest = new int[5];
System.arraycopy( src, 0, dest, 0, src.length );
Run Code Online (Sandbox Code Playgroud)
MeB*_*Guy 219
您可以使用
int[] a = new int[]{1,2,3,4,5};
int[] b = a.clone();
Run Code Online (Sandbox Code Playgroud)
同样.
Evg*_*eev 174
如果你想复制一份:
int[] a = {1,2,3,4,5};
Run Code Online (Sandbox Code Playgroud)
这是要走的路:
int[] b = Arrays.copyOf(a, a.length);
Run Code Online (Sandbox Code Playgroud)
Arrays.copyOf可能比a.clone()小阵列更快.两个复制元素同样快,但clone()返回,Object因此编译器必须插入一个隐式转换int[].您可以在字节码中看到它,如下所示:
ALOAD 1
INVOKEVIRTUAL [I.clone ()Ljava/lang/Object;
CHECKCAST [I
ASTORE 2
Run Code Online (Sandbox Code Playgroud)
Kan*_*mar 54
来自http://www.journaldev.com/753/how-to-copy-arrays-in-java的很好的解释
Java阵列复制方法
Object.clone():Object类提供clone()方法,由于java中的数组也是Object,可以使用此方法实现完整的数组复制.如果您想要数组的部分副本,则此方法不适合您.
System.arraycopy():系统类arraycopy()是执行数组部分复制的最佳方法.它为您提供了一种指定要复制的元素总数以及源和目标数组索引位置的简便方法.例如,System.arraycopy(source,3,destination,2,5)将5个元素从源复制到目标,从源的第3个索引开始到目标的第2个索引.
Arrays.copyOf():如果要复制数组的前几个元素或数组的完整副本,可以使用此方法.显然它不像System.arraycopy()那样通用,但它也不会让人感到困惑和易于使用.
Arrays.copyOfRange():如果要复制数组的少数元素,其中起始索引不为0,则可以使用此方法复制部分数组.
Ste*_*n C 32
我觉得所有这些"复制数组的更好方法"并不能解决你的问题.
你说
我试过像[...]这样的for循环,但似乎没有正常工作?
看看那个循环,没有明显的理由让它不起作用......除非:
a与b阵列弄乱了(例如a与b指代相同的阵列),或a数组.在任何一种情况下,进行复制的替代方法都无法解决潜在的问题.
第一种情况的修复是显而易见的.对于第二种情况,您必须找出一些同步线程的方法.原子数组类没有帮助,因为它们没有原子复制构造函数或克隆方法,但使用原始互斥体进行同步将起到作用.
(你的问题中有一些提示让我认为这确实与线程有关;例如你的陈述a不断变化.)
小智 14
您可以尝试在Java中使用Arrays.copyOf()
int[] a = new int[5]{1,2,3,4,5};
int[] b = Arrays.copyOf(a, a.length);
Run Code Online (Sandbox Code Playgroud)
从数组中调用长度的所有解决方案,添加代码冗余null checkersconsider示例:
int[] a = {1,2,3,4,5};
int[] b = Arrays.copyOf(a, a.length);
int[] c = a.clone();
//What if array a comes as local parameter? You need to use null check:
public void someMethod(int[] a) {
if (a!=null) {
int[] b = Arrays.copyOf(a, a.length);
int[] c = a.clone();
}
}
Run Code Online (Sandbox Code Playgroud)
我建议您不要发明轮子并使用实用程序类,其中已经执行了所有必要的检查.考虑来自apache commons的ArrayUtils.您的代码变得更短:
public void someMethod(int[] a) {
int[] b = ArrayUtils.clone(a);
}
Run Code Online (Sandbox Code Playgroud)
您可以在那里找到Apache公共资源
你也可以使用Arrays.copyOfRange.
示例:
public static void main(String[] args) {
int[] a = {1,2,3};
int[] b = Arrays.copyOfRange(a, 0, a.length);
a[0] = 5;
System.out.println(Arrays.toString(a)); // [5,2,3]
System.out.println(Arrays.toString(b)); // [1,2,3]
}
Run Code Online (Sandbox Code Playgroud)
这种方法类似Arrays.copyOf,但更灵活.它们都System.arraycopy在引擎盖下使用.
见:
| 归档时间: |
|
| 查看次数: |
690516 次 |
| 最近记录: |