Determines the common elements (intersection) between ArrayList A and ArrayList B - Java java.lang

Java examples for java.lang:int Array

Description

Determines the common elements (intersection) between ArrayList A and ArrayList B

Demo Code


//package com.java2s;
import java.util.ArrayList;

public class Main {
    /**/*from   w w  w.  j  av  a2  s  .co  m*/
     * Determines the common elements (intersection) between setA and setB 
     * 
     * @param setA - The first of the two Sets
     * @param setB - The second of the two sets 
     * @return a new set that consists of the common elements between A and B
     * @throws java.lang.IllegalArgumentException - 
     *                  when one of setA or setB is null or empty 
     */
    public static ArrayList<Integer> intersection(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) {
            throw new IllegalArgumentException(
                    "Arraylist arguments cannot be empty");
        }
        for (int i = 0; i < setA.size(); i++) {
            for (int j = 0; j < setB.size(); j++) {
                if (setA.get(i) == setB.get(j)) {
                    boolean addit = true;
                    for (int k = 0; k < returnValues.size(); k++) {
                        if (setA.get(i) == returnValues.get(k)) {
                            addit = false;
                            break;
                        }
                    }
                    if (addit) {
                        returnValues.add(setA.get(i));
                    }
                }
            }
        }

        return returnValues;
    }
}

Related Tutorials