Defining Comparisons

 

Python

Java

 

Comparable objects recognize the comparison operators ==, !=, <, >, =<, and >=.  Strings are comparable. The str class includes the methods __eq__ and __lt__. Using these two methods, Python automatically generates the code for the appropriate comparisons when it encounters any of the other comparison operators that are used with strings.

 

A list of strings can be sorted using the sort() method, but a list of Student objects cannot.  However, the programmer can include the __eq__ and __lt__ methods 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 __lt__(self, other):

        return 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

 

 

Previous

Index

Next