LinkedHashSet - insertion order and duplicates - keep newest “on top”

前端 未结 4 2186
离开以前
离开以前 2021-01-01 09:11

I need a collection that keeps insertion order and has unique values. LinkedHashSet looks like the way to go, but there\'s one problem - when two items are equal, it removes

4条回答
  •  南笙
    南笙 (楼主)
    2021-01-01 10:03

    Most of the Java Collections can be extended for tweaking.

    Subclass LinkedHashSet, overriding the add method.

    class TweakedHashSet extends LinkedHashSet {
    
        @Override
        public boolean add(T e) {
            // Get rid of old one.
            boolean wasThere = remove(e);
            // Add it.
            super.add(e);
            // Contract is "true if this set did not already contain the specified element"
            return !wasThere;
        }
    
    }
    

提交回复
热议问题