java.util.HashSet int iteration order
This question already has an answer here:
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
.
The HashSet
class does not guarantee the order in which you have entered the data.
If you do not put your List
in the HashSet
and instead continue with List
you will get the order in which you are adding the values in it.
You can use LinkedHashSet
to keep the insertion order.
If you want to sort the List
then you can use Collections.sort()
. (Extra information, ignore if you do not need it)
上一篇: 迭代/更新HashMap