Java取两个int数组的交集和并集
时间: 2023-12-24 21:11:06 浏览: 112
Java取两个int数组的交集和并集的代码如下:
```java
public class ArrayIntersectionUnion {
public static void main(String[] args) {
int[] arr1 = { 1, 2, 3, 4, 5 };
int[] arr2 = { 4, 5, 6, 7, 8 };
// 求交集
Set<Integer> intersection = new HashSet<Integer>();
for (int i = 0; i < arr1.length; i++) {
for (int j = 0; j < arr2.length; j++) {
if (arr1[i] == arr2[j]) {
intersection.add(arr1[i]);
break;
}
}
}
System.out.println("Intersection: " + intersection);
// 求并集
Set<Integer> union = new HashSet<Integer>();
for (int i = 0; i < arr1.length; i++) {
union.add(arr1[i]);
}
for (int j = 0; j < arr2.length; j++) {
union.add(arr2[j]);
}
System.out.println("Union: " + union);
}
}
```
运行结果如下:
```
Intersection: [4, 5]
Union: [1, 2, 3, 4, 5, 6, 7, 8]
```
阅读全文