java实现两个数组合并去重



import java.util.Arrays;
import java.util.Scanner;
import java.util.TreeSet;


//数组合并    去重
public class Test {

public static void main(String[] args) {


// TODO Auto-generated method stub
boolean b = true;
Scanner sc = new Scanner(System.in);

while (b) {

System.out.println("请输入第一个数组的长度(大于等于0的整数):");
if (sc.hasNextInt()) {


int n = sc.nextInt();
int[] arr1 = new int[n];
for (int i = 0; i < n; i++) {
arr1[i] = (int) (Math.random() * 100 + 1);// 随机1到100的整数
System.out.print(arr1[i] + "\t");
}


System.out.println("");
System.out.println("请输入第二个数组的长度(大于等于0的整数):");
if (sc.hasNextInt()) {
int m = sc.nextInt();
int[] arr2 = new int[m];
for (int i = 0; i < m; i++) {
arr2[i] = (int) (Math.random() * 100 + 1);// 随机1到100的整数
System.out.print(arr2[i] + "\t");
}
System.out.println("");
// 数组添加到集合
TreeSet list = new TreeSet<>();


for (int i = 0; i < n; i++) {
list.add(arr1[i]);
}
for (int i = 0; i < m; i++) {
list.add(arr2[i]);
}
// 求得集合的长度
int listsize = list.size();
System.out.println("listsize=" + listsize);


// 集合转化为数组
Object[] arr3 = list.toArray();
System.out.println("arr3size=" + arr3.length); // 求得合并后数组arr3的长度
System.out.println("arr3=" + Arrays.toString(arr3));
Arrays.sort(arr3);
for (int i = 0; i < arr3.length; i++) {
System.out.print("arr[" + i + "]=" + arr3[i] + "\t\t");
}
b = false;

else {
System.out.println("输入有误!!!");
b = false;
}
}
else {
System.out.println("输入有误!!!");
b = false;
}


}
}


}

你可能感兴趣的:(Java编程)