The Collections class can be used to sort Lists with a Comparator. The Arrays class can do the same for arrays. Is there a way to sort a TreeSet according to a different Comparator after it's already been created?
Here is some sample code to help make clear what I'm asking.
[Joshua]: Is there a way to sort a TreeSet according to a different Comparator after it's already been created?
No. The algorithms used in TreeSet assume that the sort order will not change after the TreeSet has been created, and they intentionally do not offer you the option to change it. (E.g. there's no setComparator(), because you might call that when you shouldn't.) If you want to sort a different way, you can create a newTreeSet and load it from the old one:
You may or may not choose to let the old set be garbage collected at this point, depending on whether you still have a use for the original order. It's perfectly possibly to simultaneously have two sets containing the same elements in different order, if that's useful to you.
Also, you may decide use a List or array instead of the set, and then use Collections.sort() or Arrays.sort() to change the order of an existing List or array.
"I'm not back." - Bill Harding, Twister
Joined: Aug 22, 2005
subject: How to sort existing TreeSets with a Comparator?