找出两个数组中不相同的元素,网上贴出的代码基本如下:
/** * 找出两个数组中不同的元素 */ public class Test3 { public static Set<Integer> compare(Integer[] a, Integer[] b) { Set<Integer> aSet = new HashSet<>(); Set<Integer> diffSet = new HashSet<>(); aSet.addAll(Arrays.asList(a)); for (Integer i : b) { if(!aSet.contains(i)) { diffSet.add(i); } } return diffSet; } public static void main(String[] args) throws InterruptedException { Integer[] a = {1, 2, 3}; Integer[] b = {1, 2, 3, 4}; System.out.println(compare(a, b)); } }
输出
[4]
猜猜有什么坑??
Integer[] a = {0, 1, 2, 3}; Integer[] b = {1, 2, 3, 4}; 输出 [4]
改进后的代码
/** * 找出两个数组中不同的元素 */ public class Test3 { public static Set<Integer> compare(Integer[] a, Integer[] b) { Set<Integer> aSet = new HashSet<>(); Set<Integer> diffSet = new HashSet<>(); aSet.addAll(Arrays.asList(a)); for (Integer i : b) { if(!aSet.contains(i)) { diffSet.add(i); } } return diffSet; } public static void main(String[] args) throws InterruptedException { Integer[] a = {0, 1, 2, 3}; Integer[] b = {1, 2, 3, 4}; Set<Integer> diffSetA = compare(a, b); Set<Integer> diffSetB = compare(b, a); diffSetA.addAll(diffSetB); System.out.println(diffSetA); } }
输出
[0, 4]
要调用两次方法,有点啰嗦,再次优化如下:
/** * 找出两个数组中不同的元素 */ public class Test4 { public static Set<Integer> compare(Integer[] a, Integer[] b) { // 存储所有元素 Set<Integer> allSet = new HashSet<>(); // 存储相同的元素 Set<Integer> sameSet = new HashSet<>(); allSet.addAll(Arrays.asList(a)); for (Integer i : b) { if(allSet.contains(i)) { sameSet.add(i); } } allSet.addAll(Arrays.asList(b)); // 移除相同的元素 allSet.removeAll(sameSet); return allSet; } public static void main(String[] args) throws InterruptedException { Integer[] a = {0, 1, 2, 3}; Integer[] b = {1, 2, 3, 4}; System.out.println(compare(a, b)); } }
打印
[0, 4]