Best way to copy from one array to another [closed]

怎甘沉沦 提交于 2019-12-31 09:44:48

问题


When I run the following code, nothing gets copied - what am I doing wrong?

Also, is this the best/most efficient way to copy data from one array to another?

public class A {
    public static void main(String args[]) {
        int a[] = { 1, 2, 3, 4, 5, 6 };
        int b[] = new int[a.length];

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

回答1:


I think your assignment is backwards:

a[i] = b[i];

should be:

b[i] = a[i];




回答2:


There are lots of solutions:

b = Arrays.copyOf(a, a.length);

Which allocates a new array, copies over the elements of a, and returns the new array.

Or

b = new int[a.length];
System.arraycopy(a, 0, b, 0, b.length);

Which copies the source array content into a destination array that you allocate yourself.

Or

b = a.clone();

which works very much like Arrays.copyOf(). See this thread.

Or the one you posted, if you reverse the direction of the assignment in the loop.




回答3:


Use Arrays.copyOf my friend.



来源:https://stackoverflow.com/questions/6537589/best-way-to-copy-from-one-array-to-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!