欢迎访问宙启技术站
智能推送

Java函数:求两个数组的交集和并集

发布时间:2023-07-03 03:53:38

求两个数组的交集和并集可以使用Java语言中提供的集合类来实现。Java中的集合类有HashSet和ArrayList等可以帮助我们方便地求解交集和并集。

首先,我们需要定义两个数组,并将它们存储为ArrayList类型的集合对象。下面是示例代码:

import java.util.ArrayList;
import java.util.HashSet;

public class IntersectionAndUnion {

    public static void main(String[] args) {
        int[] array1 = {1, 2, 3, 4, 5};
        int[] array2 = {4, 5, 6, 7, 8};

        ArrayList<Integer> list1 = new ArrayList<>();
        ArrayList<Integer> list2 = new ArrayList<>();

        for (int num : array1) {
            list1.add(num);
        }

        for (int num : array2) {
            list2.add(num);
        }
    }

}

接下来,我们可以使用HashSet集合类来求解交集。HashSet是一种不允许重复元素的集合,它可以帮助我们方便地去除重复的元素。我们可以通过遍历一个数组,在另一个数组中查找是否存在相同的元素,如果存在,则将该元素添加到交集的集合中。代码如下:

    HashSet<Integer> intersectionSet = new HashSet<>();

    for (int num : list1) {
        if (list2.contains(num)) {
            intersectionSet.add(num);
        }
    }

最后,我们可以使用HashSet的addAll()方法将两个集合的元素合并到一起,得到并集。代码如下:

    HashSet<Integer> unionSet = new HashSet<>();
    unionSet.addAll(list1);
    unionSet.addAll(list2);

最后,我们可以根据需求将交集和并集转换成数组。代码如下:

    int[] intersectionArray = new int[intersectionSet.size()];
    int[] unionArray = new int[unionSet.size()];

    int i = 0;
    for (int num : intersectionSet) {
        intersectionArray[i++] = num;
    }

    i = 0;
    for (int num : unionSet) {
        unionArray[i++] = num;
    }

最后,我们可以将交集和并集打印输出,代码如下:

    System.out.print("Intersection: ");
    for (int num : intersectionArray) {
        System.out.print(num + " ");
    }

    System.out.print("
Union: ");
    for (int num : unionArray) {
        System.out.print(num + " ");
    }

综上所述,以上就是使用Java语言求解两个数组的交集和并集的方法。我们可以定义两个数组,将它们转换成集合对象,并使用HashSet集合类求解交集和并集。最后,将交集和并集转换回数组,并打印输出。