When I run below code it is always giving the o/p in natural/ alphabetical order. As per I know HashSet
doesn't sort the entries. I know that HashSet
is backed by HashMap
and not LinkedHashMap
. I tried to explore the source code of HashSet
and HashMap
but couldn't find the code for this behavior.
From the source code there is below constructor in HashSet
class:
HashSet(int initialCapacity, float loadFactor, boolean dummy) {
map = new LinkedHashMap<>(initialCapacity, loadFactor);
}
which uses LinkedHashMap
. If I had used this constructor I would think this is the reason for this behavior but I'm not using this constructor.
Could someone please explain the reason/ code for this behavior?
Here's my simple code:
Set<String> mySet = new HashSet<>();
mySet.add("D");
mySet.add("B");
mySet.add("1");
mySet.add("E");
mySet.add("A");
mySet.add("F");
mySet.stream().forEach(x -> System.out.println(x));
OP:
1
A
B
D
E
F