Search code examples
javacollectionstreeset

Reliability of `TreeSet` for orderability


Is it reliable to use the following Java code:

TreeSet<String> ts = new TreeSet<String>();
String stringAtIndexThree = Arrays.<Tag> asList(list.toArray(new Tag[list.size()])).get(3);

to get the object at the third index (assuming that ts.size() > 3)?

That is, will TreeSet<T>#toArray(T[]) always return the elements in the same order, if no modifications are made to the set?

If it matters, this is for a ComboBoxModel implementation that should have only unique elements (optimally, I would use the non-existent UniqueList).

Thanks!

WC


Solution

  • will TreeSet#toArray(T[]) always return the elements in the same order, if no modifications are made to the set?

    Absolutely - TreeSet returns elements in the same sorted order. Of course your elements should play nicely when it comes to implementing comparable in order for that sorting order to be what you expect.