This week's book giveaway is in the OCMJEA forum. We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line! See this thread for details.
Basically I have Objects of type Item which have a name of type String and weight of type int. :
Well, if I create a TreeSet and I start to add objects they are sorted by name as I specified in the compareTo method.
At this point my question is: How can I sort the treeSet using for example the weight?
My approach is as follows:
- I have created a comparator and I am trying to sort the TreeSet with it.
But I don't know how to sort the TreeSet without creating a new one.... I got the items sorted by weight using an array:
How can I sort the treeSet without having to create a new one?
Joined: Mar 20, 2009
I have read in the API that TreeSet is a Red-black implementation of the NavigableSet interface. And the NavigableSet is a SortedSet extended with navigation methods.
Following with SortedSet the API says that is a Set whose elements are automatically sorted when the SortedSet is created.
Probably the answer to my previous answer could be that : Does not make sense to sort several times a TreeSet! , it is sorted using the sorting we specified in the moment of its creation. And when we add new elements it continues sorted.