我见过类似的问题,但没有一个能提供我正在寻找的答案,所以如果这被认为是重复的,我提前道歉。 我正在尝试将数组 {1, 2, 3} 和 {4, 5, 6} 组合成 {1, 2, 3, 4, 5, 6}。我做错了什么?我是 java 的 super 新手。对不起,如果这个问题很愚蠢。
public class combine {
public static void main(String[]args){
int[]a = {1, 2, 3};
int[]b = {4, 5, 6};
int[]c = new int[a+b];
for(int i=0; i<a.length; i++)
System.out.print(c[i]+" ");
}
public static int[]merge(int[]a, int[]b){
int[]c = new int[a.length+b.length];
int i;
for(i=0; i<a.length; i++)
c[i] = a[i];
for(int j=0; j<b.length; j++)
c[i++]=b[j];
return c;
}
}
最佳答案
不要自己做,用System.arrayCopy()
将两个数组复制到组合大小的新数组中。这样效率更高,因为它使用 native 操作系统代码。
关于java - 在java中将两个整数数组组合成一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20316526/