Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a set's "toArray" deterministic?

Obviously, sets do not have any kind of ordering, so I cannot expect any specific ordering if I do

String[] string = mySet.toArray();

However, I am faced with a use case where I don't care what ordering the string array is in, but I DO need it to be the case that if two sets are equal to each other, then:

StringUtils.join(mySet.toArray(),',');

will produce the same exact string for those sets, always, no matter how many times I run the program assuming I stick with the same code.

Do I have this guarantee?

Similarly, does this whole true for the order that elements appear for a given Set in an iterator?

like image 562
Jeremy Avatar asked Mar 30 '12 21:03

Jeremy


2 Answers

In general, you cannot guarantee the order of a Set as you mention, so even if it does work now, it may not in the future. However, you can guarantee the order of a LinkedHashSet so you can just use that. This only works if the sets had the elements inserted in the same order though. If you don't have that situation, you probably just have to sort the set and print it.

like image 157
Dave Avatar answered Sep 21 '22 13:09

Dave


Technically, no you don't have a guarantee. Set is an Interface. Implementations will vary and may or may not obey this requirement.

Force the issue by sorting the array yourself after extracting the results from the Set.

like image 34
rfeak Avatar answered Sep 19 '22 13:09

rfeak