LinkedHashSet

LinkedHashSet is a HashSet that also maintains a doubly linked list of the elements it holds. When we iterate through a HashSet, there is no guaranteed order of the element. When HashSet is modified, the new elements are inserted into one of the buckets and, possibly, the hash table gets resized. This means that the elements get rearranged and get into totally different buckets. Iteration over the elements in HashSet just takes the buckets and the elements in it as they are in some order that is arbitrary from the caller's point of view.

LinkedHashSet, however, iterates over the elements using the linked list it maintains, and the iteration is guaranteed to happen in the order the elements were inserted. This way, the LinkedHashSet ...

Get Java Projects - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.