使用旧数组中的内容创建新数组,同时保持旧数组不变 [英] Creating new array with contents from old array while keeping the old array static
问题描述
说我有一个整数数组,
int[] array = new int[7];
for(int i = 0; i < 7; i++)
{
array[i] = i;
}
现在,我只想获取该array
中的前四个数字,然后将其放入另一个数组中.
Now i want to get only the first four numbers in that array
, and turn put that into another array.
所以我真的想要类似...
So I really want something like...
newArray = array[0-3].
我知道语法是错误的,但是我只是给出了我想做的一般想法,是否可能这样?还是我必须创建一个循环并将其手动添加到newArray
中?
I know that syntax is wrong, but I'm just giving the general idea of what I'm trying to do, is anything like that possible? Or do i have to create a loop and add it manually into the newArray
?
推荐答案
方法1
int[] newArr = new int[4];
System.arraycopy(array, 0, newArr, 0, 4);
该方法有五个参数:
-
src
:源数组. -
srcPosition
:源中您希望开始的位置 复制. -
des
:目标数组. -
desPosition
:目标数组中复制到的位置 应该开始. -
length
:要复制的元素数.
src
: The source array.srcPosition
: The position in the source from where you wish to begin copying.des
: The destination array.desPosition
: The position in the destination array to where the copy should start.length
: The number of elements to be copied.
如果src或des为null,则此方法引发NullPointerException. 在以下情况下,它还会引发ArrayStoreException:
This method throws a NullPointerException if either of src or des are null. It also throws an ArrayStoreException in the following cases:
- 如果src不是数组.
- 如果des不是数组.
- 如果src和des是不同数据类型的数组.
方法2
使用
Arrays.copyOf(array,4)
复制前4个元素,其余部分截短.
Arrays.copyOf(array,4)
to copy the first 4 elements, truncating the rest.
个
Arrays.copyOfRange(array,1,5)
如果需要数组的中间,则将元素1-4复制.
Arrays.copyOfRange(array,1,5)
to copy elements 1-4 if you need the middle of an array.
这篇关于使用旧数组中的内容创建新数组,同时保持旧数组不变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!