使用旧数组中的内容创建新数组,同时保持旧数组不变 [英] Creating new array with contents from old array while keeping the old array static

查看:91
本文介绍了使用旧数组中的内容创建新数组,同时保持旧数组不变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个整数数组,

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);

该方法有五个参数:

  1. src:源数组.
  2. srcPosition:源中您希望开始的位置 复制.
  3. des:目标数组.
  4. desPosition:目标数组中复制到的位置 应该开始.
  5. length:要复制的元素数.
  1. src: The source array.
  2. srcPosition: The position in the source from where you wish to begin copying.
  3. des: The destination array.
  4. desPosition: The position in the destination array to where the copy should start.
  5. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆