Defining Comparisons
|
Python |
Java |
|
Comparable objects recognize the comparison operators ==, !=, <, >, =<, and >=. Strings are comparable. The str class includes the method __cmp__ which Python calls when a comparison operator is encountered. The header of this method is
def __cmp__(self, other)
where self is the left operand of the comparison and other is the right operand. This method returns 0 if the two operands are equal, -1 if the left operand is less, or 1 if the left operand is greater. The __cmp__ method is also automatically run when the cmp function is called with two comparable objects. A list of strings can be
sorted using the sort() method, but a list of Student objects cannot. However, the programmer can include the __cmp__ method in the Student class to solve this problem.
Each method uses the studentsŐ names as the comparable attributes. Note that the concepts
of less than and greater than are more restrictive than equality. That is, the types of objects being
compared are now assumed to be the same, so any errors will be
raised at run time. Example: class Student: NUM_GRADES = 5 def __init__(self, name):
self.name = name
self.grades = []
for i in range(Student.NUM_GRADES):
self.grades.append(0) def __eq__(self, other):
if self is other: return True
elif type(self) != type(other):
return False
else:
return self.name == other.name def __cmp__(self, other):
return cmp(self.name, other.name) Usage: s1 =
Student('Mary') s2 = Student('Bill') print s1 <
s2
# displays False print s1 >
s2
# displays True |
A class of comparable
objects implements the Comparable interface.
For example, the String class implements Comparable. This interface specifies a single compareTo method, as follows: public
interface Comparable<E>{ public int compareTo(E
element); } This interface is
generic; the element type E is filled in by the implementing class (usually,
the name of that class itself).
The method compares the relevant attributes of the receiver object and
the parameter object. compareTo returns 0 if the two objects are equal (using
the equals method), an integer less than 0 if the receiver
is less than the parameter, and an integer greater than 0 otherwise. The following example uses the
studentsŐ names as the comparable attributes: Example: public class
Student implements Comparable<Student>{ private String name; public Student(String
name){
this.name = name; } public int
compareTo(Student other){
return this.name.compareTo(other.name); } } Usage: Student s1 =
new Student("Mary"); Student s2 =
new Student("Bill"); System.out.println(s1.comapreTo(s2)
< 0); // displays false System.out.println(s1.compareTo(s2)
> 0); // displays true |