开发者

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

开发者 https://www.devze.com 2023-03-16 06:58 出处:网络
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.

This question was caused by a typo or a problem that can no lon开发者_StackOverflow中文版ger be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.

Closed 8 years ago.

Improve this question

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];
        }
    }
}


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:

b[i] = a[i]; // NOT a[i] = b[i];


I think your assignment is backwards:

a[i] = b[i];

should be:

b[i] = a[i];


Use Arrays.copyOf my friend.

0

精彩评论

暂无评论...
验证码 换一张
取 消