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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With