Is there a no-duplicate List implementation out there?

后端 未结 11 643
悲哀的现实
悲哀的现实 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 00:57

    So here's what I did eventually. I hope this helps someone else.

    class NoDuplicatesList extends LinkedList {
        @Override
        public boolean add(E e) {
            if (this.contains(e)) {
                return false;
            }
            else {
                return super.add(e);
            }
        }
    
        @Override
        public boolean addAll(Collection collection) {
            Collection copy = new LinkedList(collection);
            copy.removeAll(this);
            return super.addAll(copy);
        }
    
        @Override
        public boolean addAll(int index, Collection collection) {
            Collection copy = new LinkedList(collection);
            copy.removeAll(this);
            return super.addAll(index, copy);
        }
    
        @Override
        public void add(int index, E element) {
            if (this.contains(element)) {
                return;
            }
            else {
                super.add(index, element);
            }
        }
    }   
    

提交回复
热议问题