java求两个数组的并集
时间: 2023-05-18 09:07:02 浏览: 126
您好,以下是求两个数组的并集的 Java 代码:
```java
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
int[] arr1 = {1, 2, 3, 4, 5};
int[] arr2 = {4, 5, 6, 7, 8};
int[] union = getUnion(arr1, arr2);
for (int i : union) {
System.out.print(i + " ");
}
}
public static int[] getUnion(int[] arr1, int[] arr2) {
HashSet<Integer> set = new HashSet<>();
for (int i : arr1) {
set.add(i);
}
for (int i : arr2) {
set.add(i);
}
int[] union = new int[set.size()];
int index = 0;
for (int i : set) {
union[index++] = i;
}
return union;
}
}
```
希望能对您有所帮助!
阅读全文