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.
In that first sample class, the class was modified by making it implement the Comparable interface, and thus the compareTo method.
The example there doesn't show a second class implemented differently. but assuming instead of wanting to have many instances of this class sorted by the property sorted here, we could subclass it and override the compareTo method.
in this example, it doesn't really show why we would do that, consider a class that had more than one string property, maybe an id, an age, a name. So the compareTo in this person class might by default sort by name. Now if we created a subclass birthday list entry say, to have it sort by age instead.
so jamming the object instances into something that naturally sorts, such as a TreeSet, or using a sort operation on the colletion, would cause the instances of person class to be sorted differently from the instances of birthday list class. I guess we could have some configurable external proparty that each object instance would know how to retreive somehow so that we could configure sorting by different properties in the one class, where this variable would drive the compareTo method implemented here, that would not need to have a new object type subclassed etc to have different sorting.
in that second example, you seem to be wanting to compare something that implements a comparable interface with something that does not. in that case you would have to come up with your own code that meticulously inspects each property in the A, and B ones, so that you end up coming with something that returns -1, 0,or +1 in a manner like the built in compare thingie would, but in this case, unless you made this logic into a wrapper class that implements Comparable interface, the Java built int utilities for comparing (or sorting) would not be able to make use of this.
Error: Keyboard not attached. Press F1 to continue.
1)In comparable the particular class itself will compare it with another object.
Do you mean to say that we are making the 2 objects of same class and comparing them with one another.Can we say this statement is same as the following
statement "You must modify the class whose instance you want to sort" .
2) In Comparator a third party will compare two objects and return the result
Do you mean to say that we will create a seperate class that implements comparator and write sorting logic as per our requirement and call Collection.sort(list,comparator).