Why do the second and third sets preserve order:
Integer[] j = new Integer[]{3,4,5,6,7,8,9};
LinkedHashSet i = new LinkedHashSet
@Behrang's answer is good but to be more specific, the only reason why the HashSet
seems to be in the same order as the LinkedHashSet
is that integer.hashCode()
happens to be the integer value itself so the numbers happen to be in order in the HashSet
internal storage. This is highly implementation specific and as @Behrang says, really a coincidence.
For example, if you use new HashSet<>(4)
which sets the initial number of buckets to be 4 (instead of 16) then you might have gotten the following output:
HashSet hi = new HashSet(4);
...
[3, 4, 5, 6, 7, 8, 9]
[8, 9, 3, 4, 5, 6, 7]
[8, 9, 3, 4, 5, 6, 7]
If you had stuck in values >= 16, you might get something like this:
Integer[] j = new Integer[] { 3, 4, 5, 6, 7, 8, 9, 16 };
...
[3, 4, 5, 6, 7, 8, 9, 16]
[16, 3, 4, 5, 6, 7, 8, 9]
[16, 3, 4, 5, 6, 7, 8, 9]