Is there a no-duplicate List implementation out there?

后端 未结 11 682
悲哀的现实
悲哀的现实 2020-11-29 00:53

I know about SortedSet, but in my case I need something that implements List, and not Set. So is there an implementation out there, in the API or e

11条回答
  •  执笔经年
    2020-11-29 01:07

    NOTE: it does not take subList implementation into account.

    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.HashSet;
    import java.util.Set;
    
    public class UniqueList extends ArrayList {
    
        private static final long serialVersionUID = 1L;
    
        /** Unique elements SET */
        private final Set set=new HashSet();
    
        /** Used by addAll methods */
        private Collection addUnique(Collection col) {
            Collection unique=new ArrayList();
            for(T e: col){
                if (set.add(e)) unique.add(e);
            }
            return unique;
        }
    
        @Override
        public boolean add(T e) {
            return set.add(e) ? super.add(e) : false;
        }
    
        @Override
        public boolean addAll(Collection col) {
            return super.addAll(addUnique(col));
        }
    
        @Override
        public void add(int index, T e) {
            if (set.add(e)) super.add(index, e);
        }
    
        @Override
        public boolean addAll(int index, Collection col) {
            return super.addAll(index, addUnique(col));
        }
    
    }
    

提交回复
热议问题