Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java HashSet shows list in weird order, always starting with 3

I have array of Strings which actually in nothing but list of integers coming from file. I converted it to HashSet so as to remove duplicates as follows:

Set<String> intSet = new HashSet<String>(Arrays.asList(strArr));

I expected that it all the numbers to be in order but off course, since this is a string and not integer list, it may not come in order. But whenever I try to print this HashSet, I always get output as follows:

[3, 2, 1, 4]
[3, 2, 5, 4]

Every time, if 3 is present it is considered to be first element. I am not getting why it is acting this way? Can anyone please explain me this.

like image 269
Rahul Shelke Avatar asked Dec 01 '25 11:12

Rahul Shelke


1 Answers

The order of return is dependent on an internal hashing algorithm, to which you are supposed to be indifferent. (The idea behind the hashing algorithm is to disperse key values uniformly across an internal table. You probably get 3 back every time since this algorithm is probably deterministic).

If you want things back in lexographic order then use a TreeSet.

To preserve the order of insertion, use a LinkedHashSet.

like image 92
Bathsheba Avatar answered Dec 03 '25 01:12

Bathsheba



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!