如何在Java中将一个数组的值设置为另一个数组的值?

时间:2022-09-21 15:16:54

Lets say you had two arrays:

让我们说你有两个数组:

    int[] a = {2, 3, 4};
    int[] b = {4, 5, 6};

How would you set array a to array b and keep them different different objects? Like I thought of doing this:

你如何将数组a设置为数组b并保持它们不同的不同对象?就像我想的那样:

    a = b; 

But that doesn't work since it just makes "a" reference array b. So, is the only way to set two arrays equal, while keeping them separate objects, to loop through every element of one array and set it to the other?

但这不起作用,因为它只是制作一个“参考”数组b。那么,设置两个数组相同的唯一方法,同时保持它们是单独的对象,循环遍历一个数组的每个元素并将其设置为另一个数组?

And what about ArrayList? How would you set one ArrayList equal to another when you have objects in them?

那么ArrayList呢?当你有对象时,你如何设置一个ArrayList等于另一个?

2 个解决方案

#1


19  

You may want to use clone:

您可能想要使用clone:

a = b.clone();

or use arraycopy(Object source, int sourcePosition, Object destination, int destinationPosition, int numberOfElements)

或者使用arraycopy(Object source,int sourcePosition,Object destination,int destinationPosition,int numberOfElements)

System.arraycopy(b, 0, a, 0, b.length());

#2


6  

For arrays, take a look at:

对于数组,请看一下:

For ArrayList:

对于ArrayList:

I think this should give you enough pointers to make progress with your homework.

我认为这应该给你足够的指导,以便在你的功课上取得进步。

#1


19  

You may want to use clone:

您可能想要使用clone:

a = b.clone();

or use arraycopy(Object source, int sourcePosition, Object destination, int destinationPosition, int numberOfElements)

或者使用arraycopy(Object source,int sourcePosition,Object destination,int destinationPosition,int numberOfElements)

System.arraycopy(b, 0, a, 0, b.length());

#2


6  

For arrays, take a look at:

对于数组,请看一下:

For ArrayList:

对于ArrayList:

I think this should give you enough pointers to make progress with your homework.

我认为这应该给你足够的指导,以便在你的功课上取得进步。