When i run the code which shown in below, the output is [50, 20, 5, 40, 10, 30]. I didn't understand this order. Why the output is not [10, 5, 20, 30, 40, 50] ?
List list = Arrays.asList(10, 5, 10, 20, 30, 40, 50);
System.out.println(new HashSet(list));
Duplicates: HashSet doesn't allow duplicate values. HashMap stores key, value pairs and it does not allow duplicate keys.
HashSet does not maintain any order while LinkedHashSet maintains insertion order of elements much like List interface and TreeSet maintains sorting order or elements.
It means that HashSet does not maintains the order of its elements. Hence sorting of HashSet is not possible. However, the elements of the HashSet can be sorted indirectly by converting into List or TreeSet, but this will keep the elements in the target type instead of HashSet type.
Docs says
This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element.
go for LinkedHashSet
HashSet
doesn't maintain insertion order. What you need is a LinkedHashSet
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With