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

Most of the Java Collections can be extended for tweaking. Subclass LinkedHashSet, overriding the add method. class TweakedHashSet<T> extends LinkedHashSet<T> { @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” … Read more

HashSet vs LinkedHashSet

The difference between the two are, as you’ve stated: A LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements. Use this class instead of HashSet when you care about the iteration order. When you iterate through a HashSet the order is unpredictable, while a LinkedHashSet lets you iterate through … Read more

tech