java编写合并两个数组,{1,2,3,4,5} {4,5,6,7,8}

如题所述

分为两步:
1.连接两个数组.
2.清除重复的元素.

import java.util.Arrays;

public class Combine{
public static void main(String[] args){
int a[]={1,2,3,4,5};
int b[]={4,5,6,7,8};

int temp[]=new int[a.length+b.length];

//连接两个数组
for(int i=0;i<a.length;i++){
temp[i]=a[i];
}
for(int i=0;i<b.length;i++){
temp[a.length+i]=b[i];
}

//连接数组完成,开始清除重复元素
int size=temp.length;
for(int i=0;i<temp.length;i++){
if(temp[i]!=-1){
for(int j=i+1;j<temp.length;j++){
if(temp[i]==temp[j]){
temp[j]=-1;//将发生重复的元素赋值为-1
size--;
}
}
}
}

int[] result=new int[size];
for(int i=0,j=0;j<size && i<temp.length;i++,j++){
if(temp[i]==-1){
j--;
}
else{
result[j]=temp[i];
}
}

//打印结果
System.err.println(Arrays.toString(result));
}
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2009-08-17
/**
* 将两个数组连接起来
*
* @param first:
* 第一个数组
* @param second:
* 第二个数组
* @return :返回连接起来的新数组
*/
public static int[] connect(int[] frist, int[] second) {
int x [] = new int [frist.length + second.length];
int c = 0;
for(int i = 0 ; i < frist.length; i ++){
x[i] = frist[i];
}

for(int i = frist.length; i < x.length; i ++){
x[i] = second[c];
c ++;
}
return x;
}

public static void main(String[] args) {
int a [] = {1,2,3,4,5};
int b [] = {4,5,6,7,8};
int x [] = new int [a.length + b.length];
x = Arrays.connect(a,b);
for(int i = 0;i < a.length + b.length ;i ++){
System.out.println(x[i]);
}
}
第2个回答  2009-08-18
public class A
{

static void tt()
{
int[] s3 = {1,2,3,4,5,6,7,8};
}

public static void main(String[] args)
{
tt();
}
}
第3个回答  2009-08-17
有没有addAll方法啊

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网