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

How is this HashSet producing sorted output?

EDIT: As of Java 8 and later, the following is no longer applicable. This proves that you shouldn’t rely on undocumented Java behaviours. This behaviour is caused by several separate reasons: Integers hash to themselves in Java, HashMaps and HashSets are backed up by an array they also modify hashes using the higher bits to … Read more

Remove Elements from a HashSet while Iterating [duplicate]

You can manually iterate over the elements of the set: Iterator<Integer> iterator = set.iterator(); while (iterator.hasNext()) { Integer element = iterator.next(); if (element % 2 == 0) { iterator.remove(); } } You will often see this pattern using a for loop rather than a while loop: for (Iterator<Integer> i = set.iterator(); i.hasNext();) { Integer element … Read more

Iteration order of HashSet

Absolutely not. The insertion order directly influences the iteration order whenever you have a bucket collision: When two elements end up in the same bucket, the first one that was inserted will also be the first one returned during iteration, at least if the implementation of collision handling and iteration is straightforward (and the one … Read more