Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to restrict default ordering of Hash Set in java

I have some of values in my java program. I just stored those values in HashSet. I have stored it by for loop. The values iterating by loop has been ordered differently after the set formed. How can restrict this order change of HashSet as I get from the loop. Can anyone help me please?

like image 611
Sangeetha Krishnan Avatar asked Nov 30 '25 05:11

Sangeetha Krishnan


2 Answers

If you want the set to maintain the insertion order, you can use a LinkedHashSet:

Implementation of the Set interface, with predictable iteration order. This implementation differs from HashSet in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order).

Alternatively, if you want your set to be ordered, you can use a TreeSet.

like image 82
assylias Avatar answered Dec 02 '25 17:12

assylias


A HashSet is unordered, as the javadocs specify:

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.

You might want to consider using a LinkedHashSet, which maintains the order of insertions.

An alternative is using one of the NavigableSet implementations, such as the TreeSet which guarantee order according to the natural order or Comparator, if given.

like image 26
amit Avatar answered Dec 02 '25 19:12

amit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!