wchargin
wchargin

Reputation: 16037

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

Upvotes: 1

Views: 226

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726639

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.

Upvotes: 2

Related Questions