题目描述
请在下面的程序中插入一段代码,这段代码的功能是:将a、b数组中不同的数字保存到一个新的数组c中。
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] a = { 15, 20, 30, 40, 55, 60, 75, 80 }, b = { 15, 20, 40, 80,-5 };
int[] c;
//插入你的代码
Arrays.sort(c); //将新数组排序后输出其中的内容
System.out.println(Arrays.toString(c));
}
}
输出样例
[-5, 30, 55, 60, 75]
用户代码
package com.study.java8;
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
Integer[] a = { 15, 20, 30, 40, 55, 60, 75, 80 }, b = { 15, 20, 40, 80,-5 };
LinkedList<Integer> list = new LinkedList<Integer>();
for (Integer str : a) {
if(!list.contains(str)) {
list.add(str);
}
}
for (Integer str : b) {
if (list.contains(str)) {
list.remove(str);
}else{
list.add(str);
}
}
//差集为
System.out.println(list);
}
}
结果:
话说为啥这两个问题一模一样???
https://ask.csdn.net/questions/7548591
API调用专家:
public class Main {
public static void main(String[] args) {
Main main = new Main();
int[] a = { 15, 20, 30, 40, 55, 60, 75, 80 }, b = { 15, 20, 40, 80,-5 };
int[] c;
List<Integer> aList = Arrays.stream(a).boxed().collect(Collectors.toList());
List<Integer> bList = Arrays.stream(b).boxed().collect(Collectors.toList());
List<Integer> copyA = new ArrayList<>(aList);
List<Integer> copyB = new ArrayList<>(bList);
//这几句也行
//copyA.removeAll(bList);(A-B)
//copyB.removeAll(aList);(B-A)
//copyA.addAll(copyB);(A-B)+(B-A)
copyA.addAll(bList);//A+B
copyB.retainAll(aList);//A^B=B^A
copyA.removeAll(copyB);//(A+B)-(A^B)
c = copyA.stream().mapToInt(o->o).toArray();
Arrays.sort(c); //将新数组排序后输出其中的内容
System.out.println(Arrays.toString(c));
}
}