I was surprised to find that using Java 17 here, converting from a List to a Set returned sorted results. Why is that? I thought the Set interface and its default implementation, HashSet, did no sorting.
I confirmed these results in at last one more online environment.
What am I missing?
import java.util.*;
public class MyClass {
static int[] arr = {5, 2, 3, 1, 76};
public static void main(String args[]) {
System.out.println(Arrays.toString(arr)); // [5, 2, 3, 1, 76]
Integer[] integerArr = Arrays.stream(arr).boxed().toArray(Integer[]::new);
System.out.println(Arrays.asList(integerArr)); // [5, 2, 3, 1, 76]
Set<Integer> myset = new HashSet<>(Arrays.asList(integerArr));
System.out.println(myset); // [1, 2, 3, 5, 76]
}
}
>Solution :
HashSet
internally uses an HashMap
to store values (the key is the element of the Set and the value is the same dummy object for each entry). In the source code of JDK’s HashMap are a few implementation notes that mention that ‘tree bins’ are primarily ordered by their hashCode
. You can see that the bin’s hashCode
is calculated from the hashCode
of it’s key and value. Without going into the details of this, we can just say there seems to be some implementation-specific ordering.
In your example, the map contains Integer
elements. The hashCode
of an Integer is its value. I would guess the ordering is likely just a special case caused by this an probably also luckily chosen input values.
As already mentioned in the comments, HashSet
does not specify an order. That doesn’t mean implementations are not allowed to order elements.