001    /**
002     * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.util;
016    
017    import java.util.ArrayList;
018    import java.util.Collection;
019    import java.util.Iterator;
020    
021    /**
022     * @author Brian Wing Shun Chan
023     */
024    public class UniqueList<E> extends ArrayList<E> {
025    
026            public UniqueList() {
027                    super();
028            }
029    
030            public boolean add(E e) {
031                    if (!contains(e)) {
032                            return super.add(e);
033                    }
034                    else {
035                            return false;
036                    }
037            }
038    
039            public void add(int index, E e) {
040                    if (!contains(e)) {
041                            super.add(index, e);
042                    }
043            }
044    
045            public boolean addAll(Collection<? extends E> c) {
046                    c = new ArrayList<E>(c);
047    
048                    Iterator<? extends E> itr = c.iterator();
049    
050                    while (itr.hasNext()) {
051                            E e = itr.next();
052    
053                            if (contains(e)) {
054                                    itr.remove();
055                            }
056                    }
057    
058                    return super.addAll(c);
059            }
060    
061            public boolean addAll(int index, Collection<? extends E> c) {
062                    c = new ArrayList<E>(c);
063    
064                    Iterator<? extends E> itr = c.iterator();
065    
066                    while (itr.hasNext()) {
067                            E e = itr.next();
068    
069                            if (contains(e)) {
070                                    itr.remove();
071                            }
072                    }
073    
074                    return super.addAll(index, c);
075            }
076    
077            public E set(int index, E e) {
078                    if (!contains(e)) {
079                            return super.set(index, e);
080                    }
081                    else {
082                            return e;
083                    }
084            }
085    
086    }