java两个数组合并为一个数组

1、int[]数组

int[] a = {1,2,6};
int[] b = {7,8,9};

合并结果为:

[1, 2, 6, 7, 8, 9] 

2、String[]数组

String[] a = {"阿","java","so","easy"};
String[] b = {"is","very","good"};

合并结果为:

[阿, java, so, easy, is, very, good]

方法一:使用for循环

1、使用两个for循环将数组 a 和数组 b 中的元素复制到数组 c 中

2、第一个for循环将数组 a 中的元素复制到数组 c 的前半部分

3、第二个for循环将数组 b 中的元素复制到数组 c 的后半部分

// int[]数组
int[] c = new int[a.length + b.length];
for (int i = 0; i < a.length; i++) {
    c[i] = a[i];
}
for (int i = 0; i < b.length; i++) {
    c[a.length +i] = b[i];
}
// String[]数组
String[] c = new String[a.length + b.length];
for (int i = 0; i < a.length; i++) {
    c[i] = a[i];
}
for (int i = 0; i < b.length; i++) {
    c[a.length + i] = b[i];
}

方法二:使用Arrays.copyOf()方法 

1、使用Arrays.copyOf ()方法创建一个新的数组,并将数组 a 中的元素复制到数组 c 中

2、使用System.arraycopy ()方法将数组 b 中的元素复制到数组 c 的后半部分。

// int[]数组
int[] c = Arrays.copyOf(a,a.length+b.length);
System.arraycopy(b,0,c,a.length,b.length);
// String[]数组
String[] c = Arrays.copyOf(a,a.length+b.length);
System.arraycopy(b,0,c,a.length,b.length);

方法三:使用IntStream.concat方法

1、使用Arrays.stream() 方法将数组 a 和数组 b 转换为 IntStream对象

2、使用Stream.concat() 方法将这两个 IntStream对象连接成一个单独的流

3、使用 toArray() 方法将连接后的流转换为一个数组 c

// int[]数组
int[] c = IntStream.concat(Arrays.stream(a), Arrays.stream(b)).toArray();
// String[]数组
Object[] c = Stream.concat(Arrays.stream(a), Arrays.stream(b)).toArray();

方法四:使用System.arraycopy()方法

1、第一个System.arraycopy() 方法,将数组 a 中的元素复制到数组 c 的前半部分

2、第二个System.arraycopy() 方法,将数组 b 中的元素复制到数组 c 的后半部分。

方法:System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length);

参数:
src – 源数组。

srcPos – 源数组中的起始位置。

dest – 目标数组。

destPos – 目标数据中的起始位置。

length – 要复制的数组元素的数量

// int[]数组
int[] c = new int[a.length + b.length];
System.arraycopy(a,0,c,0,a.length);
System.arraycopy(b,0,c,a.length,b.length);
// String[]数组
String[] c = new String[a.length + b.length];
System.arraycopy(a,0,c,0,a.length);
System.arraycopy(b,0,c,a.length,b.length);

猜你喜欢

转载自blog.csdn.net/SUMMERENT/article/details/131211918
今日推荐