This week's book giveaway is in the OCPJP forum. We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line! See this thread for details.
I have a doubt in sorting part of the collections.
~ If we talk about List, They are ordered but not sorted . So in order to sort them we use sort() of Collections class, where therefore invoke the compareTo() of the class implementing Comparable interface.
~ If we talk about TreeSet, they are ordered and sorted . So if we add String objects in it, It sort them in alphabetical order .
Question : TreeSet is able to sort the String objects because it itself implements Comparable interface & Hence implemented compareTo() ?
Tarun Oohri wrote:Question : TreeSet is able to sort the String objects because it itself implements Comparable interface & Hence implemented compareTo() ?
A TreeSet can also be created with a Comparator that will be used to determine the order of its elements. This allows to insert elements into the set that do not implement Comparable, assuming that the comparator of the set is able to handle them, as well as using a comparator to define ordering different from the one imposed by Comparable implementation of the elements (such as having a TreeSet of Strings sorted in inverse order - using Collections.reverseOrder() for example).