• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to sort existing TreeSets with a Comparator?  RSS feed

 
Joshua Smith
Ranch Hand
Posts: 193
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.




Thanks,
Josh
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[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 new TreeSet 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.
 
Joshua Smith
Ranch Hand
Posts: 193
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Jim.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!