1、int[]数组 int[] a = {1,2,6};int[] b = {7,8,9}; 合并结果为: [1, 2, 6, 7, 8, 9] 2、String[]数组 String[] a = {"阿","java","so"
int[] a = {1,2,6};int[] b = {7,8,9};
合并结果为:
[1, 2, 6, 7, 8, 9]
String[] a = {"阿","java","so","easy"};String[] b = {"is","very","Good"};
合并结果为:
[阿, java, so, easy, is, very, good]
使用两个for循环将数组 a 和数组 b 中的元素复制到数组 c 中
第一个for循环将数组 a 中的元素复制到数组 c 的前半部分
第二个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 ()方法创建一个新的数组,并将数组 a 中的元素复制到数组 c 中
使用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);
使用Arrays.stream() 方法将数组 a 和数组 b 转换为 IntStream对象
使用Stream.concat() 方法将这两个 IntStream对象连接成一个单独的流
使用 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() 方法,将数组 a 中的元素复制到数组 c 的前半部分
第二个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);
来源地址:https://blog.csdn.net/SUMMERENT/article/details/131211918
--结束END--
本文标题: java两个数组合并为一个数组
本文链接: https://www.lsjlt.com/news/390534.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-04-03
2024-04-03
2024-04-01
2024-01-21
2024-01-21
2024-01-21
2024-01-21
2023-12-23
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0