compareTo
The Comparable Interface in
Java contains just one method: compareTo.
compareTo is used to check to see if two objects are the same.
If you implement the Comparable Interface, you must provide a body
for the compareTo method and you the Programmer must decide the
criteria for what makes your two objects the same. The
specification for the compareTo method states that if the two
objects are the same, you should return the integer 0 back.
If the first object is greater than second object, return 1.
If the first object is less than second object, return -1.
Example of
compareTo method:
(Checking to see if two Frogs are the same)
Example:
public int compareTo(Object
obj) {
//since a generic object is coming in
//you must always - first cast to your object, which is a Frogs
Frogs f = (Frogs)obj;
//in our design
two Frogs are the same - if they have same name
//we have a method in our Frogs class called getName which returns
//back the name of the Frogs object
if (getName().equals(f.getName))
return 0;
return 1;
}
//the above two
lines of code - do the following: the method
//getName() all by itself (no object reference in front) gets the
current name
// of this object's name -- returning back a string
//we then do the same for the f object which is the Object obj
coming
//into the compareTo method as a parameter we pass both of these
//returned strings to the equals method -- and since both objects
for equals are
//strings - we are using the equals method in the Java Strings
class to check
//the equals method returns either true if both strings have same
character
//information or false if they do not |