java中两个int型数组怎么合并啊?
答案:6 悬赏:30 手机版
解决时间 2021-04-26 22:48
- 提问者网友:暗中人
- 2021-04-26 18:59
java中两个int型数组怎么合并啊?
最佳答案
- 五星知识达人网友:纵马山川剑自提
- 2021-04-26 19:42
int a1[] = new int[4];
a1[0] = 1;
a1[1] = 2;
int a2[] = { 3, 4 };
System.arraycopy(a2, 0, a1, 2, 2);
System.out.println(Arrays.toString(a1));
结果是:[1, 2, 3, 4]
a1[0] = 1;
a1[1] = 2;
int a2[] = { 3, 4 };
System.arraycopy(a2, 0, a1, 2, 2);
System.out.println(Arrays.toString(a1));
结果是:[1, 2, 3, 4]
全部回答
- 1楼网友:长青诗
- 2021-04-26 23:30
刚运行过 //有问题可以继续交流
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
int[] a = {1, 2, 3, 4};
int[] b = {5, 6, 7, 8};
int[] c = new int[a.length + b.length];
for(int i = 0; i < a.length; i++) {
c[i] = a[i] ;
}
for(int j = 0; j < b.length; j++) {
c[a.length + j] = b[j];
}
System.out.println(Arrays.toString(c));
}
}
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
int[] a = {1, 2, 3, 4};
int[] b = {5, 6, 7, 8};
int[] c = new int[a.length + b.length];
for(int i = 0; i < a.length; i++) {
c[i] = a[i] ;
}
for(int j = 0; j < b.length; j++) {
c[a.length + j] = b[j];
}
System.out.println(Arrays.toString(c));
}
}
- 2楼网友:躲不过心动
- 2021-04-26 23:21
用System.arraycopy()就能将这两个数组合并成一个,具体做法看下面程序
public static void main(String[] agrs){
int a[] = {1,2,3,4};
int b[] = {5,6,7,8};
int c[]=null;
c=new int[a.length+b.length];
System.arraycopy(a,0,c,0,a.length);
System.arraycopy(b,0,c,a.length,b.length);
for(int i=0;i System.out.println(c[i]);
}
}
public static void main(String[] agrs){
int a[] = {1,2,3,4};
int b[] = {5,6,7,8};
int c[]=null;
c=new int[a.length+b.length];
System.arraycopy(a,0,c,0,a.length);
System.arraycopy(b,0,c,a.length,b.length);
for(int i=0;i
}
}
- 3楼网友:你哪知我潦倒为你
- 2021-04-26 22:01
循环遍历b数组,然后一个数一个数插入到a数组中。
- 4楼网友:等灯
- 2021-04-26 20:35
新建一个C数组,长度为a和b长度之和,然后做个遍历a和b添加进c就可以了
int a[] = {1,2,3,4};
int b[] = {5,6,7,8};
int c[]=new int[a.length+b.length];
for(int i=0;ic[i]=a[i];
}
for(int j=0;j c[a.length+i]=b[j];
}
for(int k=0;k System.out.println(k);
}
int a[] = {1,2,3,4};
int b[] = {5,6,7,8};
int c[]=new int[a.length+b.length];
for(int i=0;ic[i]=a[i];
}
for(int j=0;j
}
for(int k=0;k
}
- 5楼网友:愁杀梦里人
- 2021-04-26 20:07
public class ContactIntegerArray {
public static int[] contact(int a[], int b[]){
int[] f = new int[a.length+b.length];
for(int i = 0 ; i < f.length; i++)
if(i < a.length)
f[i] = a[i];
else
f[i]= b[i-a.length];
return f;
}
public static void main(String[] args) {
int a[] = {1,3,4,7};
int b[] = {2,3,5};
int c[] =ContactIntegerArray.contact(a, b);
}
}
public static int[] contact(int a[], int b[]){
int[] f = new int[a.length+b.length];
for(int i = 0 ; i < f.length; i++)
if(i < a.length)
f[i] = a[i];
else
f[i]= b[i-a.length];
return f;
}
public static void main(String[] args) {
int a[] = {1,3,4,7};
int b[] = {2,3,5};
int c[] =ContactIntegerArray.contact(a, b);
}
}
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯