Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.util.HashSet int iteration order [duplicate]

Tags:

java

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));
like image 416
karlkeller Avatar asked Jun 27 '13 12:06

karlkeller


People also ask

Does HashSet allow duplicates in Java?

Duplicates: HashSet doesn't allow duplicate values. HashMap stores key, value pairs and it does not allow duplicate keys.

Does Java HashSet maintain order?

HashSet does not maintain any order while LinkedHashSet maintains insertion order of elements much like List interface and TreeSet maintains sorting order or elements.

Does HashSet store in order?

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.


2 Answers

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

like image 157
Suresh Atta Avatar answered Oct 01 '22 01:10

Suresh Atta


HashSet doesn't maintain insertion order. What you need is a LinkedHashSet.

like image 34
Ravi K Thapliyal Avatar answered Oct 01 '22 02:10

Ravi K Thapliyal