I think you got it backwards.
compareTo() is used to compare Objects. It tests if THIS object is of the same type as the parameterized object. For instance,
String s = "t";
String s2 = "sdfsa";
s.compareTo(s2); ///would be true
.equals() compares the contents of the object. For instance,
String s = "t";
String s2 = "sfsdf";
s.equals(s2); // would return false.... "t" is not equal to "sdfdf"
server_crash
Postaholic
2,111 posts since Jun 2004
Reputation Points: 113
Solved Threads: 20
compareTo is used for sequential placement of Objects. It's mainly useful in conjunction with sorted collections.
equals is used to simply check for logical equality.
In case of Strings compareTo will tell you which of the Strings being compared would come first in a case sensitive dictionary, equals would simply tell you if the two String references contain the same data.
But it's quite possible to define the methods in your own classes to have quite different behaviour (though not often recommended for the obvious reasons).
Most useful when defining them for your own classes is to compare only part of the fields in the objects, for example in case of objects representing database records you'd only want to compare the fields representing the primary key for the database table.
implementing compareTo is really only useful in combination with implementing the marker interface Comparable which is an indicator to sorted Collections that the compareTo method can be used to sort object instances of the class (if not a Comparator class is expected instead).
jwenting
duckman
8,392 posts since Nov 2004
Reputation Points: 1,662
Solved Threads: 337