集册 Java实例教程 确定两个ArrayList的并集

确定两个ArrayList的并集

欢马劈雪     最近更新时间:2020-01-02 10:19:05

642
确定两个ArrayList的并集

/**
来 自 nowjava
**/

//package com.nowjava;

import java.util.ArrayList;


public class Main {

    /**

     * Determine the union of two sets 

     * 

     * @param setA - the first of the two sets for the union

     * @param setB - the second of the two sets for the union 

     * @return a union between setA and setB

     * @throws java.lang.IllegalArgumentException - 

     *                  when one of setA or setB is null or empty 

     */

    public static ArrayList<Integer> union(ArrayList<Integer> setA,

            ArrayList<Integer> setB) throws IllegalArgumentException {

        ArrayList<Integer> returnValues = new ArrayList<Integer>();

        if (null == setA || null == setB) {

            throw new IllegalArgumentException(

                    "Arralist arguments cannot be null");

        }

        if (setA.size() == 0 || setB.size() == 0) {//时 代 J a v a - N o w J a v a . c o m

            throw new IllegalArgumentException(

                    "Arraylist arguments cannot be empty");

        }


        for (int i = 0; i < setA.size(); i++) {

            boolean isAddable = true;

            for (int j = 0; j < returnValues.size() && isAddable; j++) {

                isAddable = setA.get(i) != returnValues.get(j);

            }

            if (isAddable) {

                returnValues.add(setA.get(i));

            }

        }


        for (int i = 0; i < setB.size(); i++) {

            boolean isAddable = true;

 
展开阅读全文