Add obj to list if obj is NOT exist in list, otherwise don't do any thing. - Android java.util

Android examples for java.util:List

Description

Add obj to list if obj is NOT exist in list, otherwise don't do any thing.

Demo Code


//package com.book2s;

import java.util.List;

public class Main {
    /**//from  w  w w . j av a  2 s  . c om
     * Add obj to list if obj is NOT exist in list, otherwise don't do any thing.
     * 
     * @param list
     * @param obj
     */
    public static <T> void addIfNotExist(List<T> list, T obj) {
        boolean isexist = false;
        for (T t : list) {
            if (t.equals(obj)) {
                isexist = true;
                break;
            }
        }
        if (!isexist) {
            list.add(obj);
        }
    }
}

Related Tutorials