Java List xor xor(List l1, List l2)

Here you can find the source of xor(List l1, List l2)

Description

Adds object from list 2 to list 1, unless they are already present (then removes them).

License

Open Source License

Declaration

public static void xor(List l1, List l2) 

Method Source Code


//package com.java2s;

import java.util.*;

public class Main {
    /**//from   www .  ja v a2s  . c om
     * Adds object from list 2 to list 1, unless they are already present (then removes them).
     */
    public static void xor(List l1, List l2) {
        int size = l1.size();

        // Add objects from l2 that aren't in l
        for (int i = 0, iMax = l2.size(); i < iMax; i++)
            if (!l1.contains(l2.get(i)))
                l1.add(l2.get(i));

        // Remove elements in l that are in l2
        for (int i = size - 1; i >= 0; i--)
            if (l2.contains(l1.get(i)))
                l1.remove(i);
    }

    /**
     * Returns the size of a list (accepts null list).
     */
    public static int size(List aList) {
        return aList == null ? 0 : aList.size();
    }

    /**
     * Returns whether list contains given object (accepts null list).
     */
    public static boolean contains(List aList, Object anObj) {
        return aList != null && aList.contains(anObj);
    }

    /**
     * Returns the object at the given index (returns null object for null list or invalid index).
     */
    public static <T> T get(List<T> aList, int anIndex) {
        return aList == null || anIndex < 0 || anIndex >= aList.size() ? null : aList.get(anIndex);
    }

    /**
     * Adds an object to the given list and returns list (creates list if missing).
     */
    public static <T> List<T> add(List<T> aList, T anObj) {
        // If list is null, create list
        if (aList == null)
            aList = new Vector();

        // Add object
        aList.add(anObj);

        // Return list
        return aList;
    }

    /**
     * Removes given object from given list (accepts null list).
     */
    public static boolean remove(List aList, Object anObj) {
        return aList == null ? false : aList.remove(anObj);
    }

    /**
     * Removes range of objects from given list (from start to end, not including end).
     */
    public static void remove(List aList, int start, int end) {
        for (int i = end - 1; i >= start; i--)
            aList.remove(i);
    }
}

Related

  1. xor(List blocs)
  2. xorOnLists(List l1, List l2)