Java List Add Unique addUnique(List aList, T anObj)

Here you can find the source of addUnique(List aList, T anObj)

Description

Adds an object to the given list if object is absent (creates list if missing).

License

Open Source License

Declaration

public static <T> List<T> addUnique(List<T> aList, T anObj) 

Method Source Code


//package com.java2s;

import java.util.*;

public class Main {
    /**/*  www  . j av  a 2 s  . c  o m*/
     * Adds an object to the given list if object is absent (creates list if missing).
     */
    public static <T> List<T> addUnique(List<T> aList, T anObj) {
        return contains(aList, anObj) ? aList : add(aList, anObj);
    }

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

    /**
     * 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;
    }
}

Related

  1. addUniq(List list, Object object)
  2. addUnique(java.util.List l, String e)
  3. addUnique(List list, T item)
  4. addUnique(List list, T item)
  5. addUniqueId(List aList, T anObj)
  6. addUniqueItems(List from, List to)

  7. HOME | Copyright © www.java2s.com 2016