posted 15 years ago
the compareTo() is the sole method of the Comparable interface in the collections framework, and is implemented on objects within a particular collection classes to implement equality checking, it is similar in part to the .equals() method of the Object class, which in good practice should always be overriden if used (in addition to the hashCode() method of the Object class.
According to the Api, overriding the compareTo() method of the Comparable interface the following contract must be honored:
anti-commutation : x.compareTo(y) is the opposite sign of y.compareTo(x) .
exception symmetry : x.compareTo(y) throws exactly the same exceptions as y.compareTo(x) .
transitivity : if x.compareTo(y)>0 and y.compareTo(z)>0, then x.compareTo(z)>0 (and same for less than) .
if x.compareTo(y)==0, then x.compareTo(z) has the same sign as y.compareTo(z) .
consistency with equals is highly recommended, but not required : x.compareTo(y)==0, if and only if x.equals(y) ; consistency with equals is required for ensuring
sorted collections (such as TreeSet) are well-behaved.
Take a look at the APi and the Sun Collections tutorial.
With your particular example the expression:
the reference i is referring to an Object (or variable of) which implements the Comparable interface. It is calling the compareTo() method (which should be overridden). The method is taking an Object reference 'o' and casting it to a Dog Object Type, and then using the 'dot' (.)notation to call the variable i of the o Object. Thus the algorithm compares the value contained in the reference i of the comparator Object with the value of i of the o object (which is being cast as a Dog object).
I am unsure if the guide applies here, but when overriding the Object.equals() method, it is good practice to add a further check the type of Object with the 'instanceo'f operator o' before Casting, otherwise there is a danger of typecast exceptions and such like for example (in the overridden equals method, if used in your example:
Again, I'm unsure as to whether this design reccomendation applies to compareTo(), but I assume it would be a good error-check if Class-casting is involved. Perhaps, one of our wise moderators can offer some direction on this?
Hope this helps!
be a well encapsulated person, don't expose your privates, unless you public void getWife()!