Presentation is loading. Please wait.

Presentation is loading. Please wait.

Comparable and Comparator Interfaces

Similar presentations


Presentation on theme: "Comparable and Comparator Interfaces"— Presentation transcript:

1 Comparable and Comparator Interfaces
There is no comparison between that which is lost by not succeeding and that which is lost by not trying. - Francis Bacon

2 Comparing Java Objects
The Object class provides a way to test equality of two objects: public boolean equals(Object obj) But this method just compares the memory location of the objects, not their content. The Object class does not provide any methods for comparing objects. And there is no way to test whether one object is “less than” or “greater than” another object. CS Computer Science II

3 Comparable and Comparator Interfaces
Instead, Java provides two interfaces that provide methods for determining the ordering of objects: the Comparable interface in java.lang library the Comparator interface in java.util library CS Computer Science II

4 The Comparable Interface
Implemented by a class of objects you want to compare (i.e. Students, Rectangles, Aliens, etc.) The interface requires one method: public int compareTo(Object o) The compareTo method must return: int < 0, if the calling object "comes before" the parameter. 0, if the calling object "equals" the parameter. int > 0, if the calling object "comes after" the parameter. CS Computer Science II

5 The Comparable Interface
Notice that the parameter is an Object. In order to implement this interface, our parameter must also be an Object, even if that’s not what we want. When implementing the compareTo method, should use casting to ensure the parameter is of the correct class. Used to determine “natural ordering” of objects. CS Computer Science II

6 Example Using Student Class
public class Student implements Comparable { public Student(String name, int score) {...} public int compareTo(Object o) {...} public String getName() {. . . } public int getScore() { } public void setName(String name) {. . . } public void setScore(int score) {. . .} // other methods } CS Computer Science II

7 Constructor for Student
Nothing special here: public Student(String name, int score) { setName(name); setScore(score); } Sort students according to scores: public int compareTo(Object o) { return score - ((Student)o).getScore(); } CS Computer Science II

8 Using Comparable Interface
public static void main(String args[]) { TreeSet<Student> class = new TreeSet<Student>(); class.add(new Student("Ann", 87)); class.add(new Student("Bob", 83)); class.add(new Student("Cat", 99)); class.add(new Student("Dan", 25)); class.add(new Student("Eve", 76)); foreach(Student s : class) { System.out.println(s.getName() + " " + s.getScore()); } } A NavigableSet implementation based on a TreeMap. The elements are ordered using their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used. Iterator<E> iterator() Returns an iterator over the elements in this set in ascending order. CS Computer Science II

9 CS 221 - Computer Science II
Output of Program Print out students according to their scores, in ascending order: Dan 25 Eve 76 Bob 83 Ann 87 Cat 99 How did the iterator know that it should sort Students by score, rather than by name? CS Computer Science II

10 Using a Separate Comparator
Above, Student implemented the Comparable interface. Uses compareTo method to make comparisons. Can only sort students by their score. If we wanted to sort students another way, such as by name, we’re out of luck. To make comparison using other criteria or if class doesn’t implement Comparable, can use separate class that implements the Comparator interface. This is more flexible, but also clumsier. The Comparator requires the compare method: public int compare(T obj1, T obj2) CS Computer Science II

11 Outline of StudentComparator
Assume Student class doesn’t implement Comparable interface. But want to way to compare Students according to scores. Because of generics, our compare method can take Student arguments: import java.util.*; public class StudentComparator implements Comparator<Student> { public int compare(Student s1, Student s2) {...} } CS Computer Science II

12 CS 221 - Computer Science II
The compare Method public int compare(Student s1, Student s2) { return s1.getScore() - s2.getScore(); } How different from compareTo(Object o)? Different method name. It takes both objects as parameters, not just one. We have to either use generics, or check the type of both objects. No need to cast objects. CS Computer Science II

13 Using Compatator Interface I
public static void main(String args[]) { Comparator<Student> comp = new StudentComparator(); TreeSet<Student> class = new TreeSet<Student>(comp); class.add(new Student("Ann", 87)); class.add(new Student("Bob", 83)); class.add(new Student("Cat", 99)); class.add(new Student("Dan", 25)); class.add(new Student("Eve", 76)); foreach(Student s : class) { System.out.println(s.getName() + " " + s.getScore()); } } TreeSet class uses “natural” ordering of objects stored in data structure, or a comparator. Iterator will return objects in that order. CS Computer Science II

14 CS 221 - Computer Science II
Output of Program Again print out by score, in ascending order: Dan 25 Eve 76 Bob 83 Ann 87 Cat 99 But what if now want to print by name alphabetically? CS Computer Science II

15 CS 221 - Computer Science II
A By-Name Comparator public class StudentByNameComparator implements Comparator<Student> { public int compare(Student s1, Student s2) { return s1.getName().compareTo(s2.getName()); } } The String class implements Comparable interface. CS Computer Science II

16 Using Compatator Interface II
public static void main(String args[]) { Comparator<Student> comp = new StudentByNameComparator(); TreeSet<Student> class = new TreeSet<Student>(comp); class.add(new Student("Ann", 87)); class.add(new Student("Bob", 83)); class.add(new Student("Cat", 99)); class.add(new Student("Dan", 25)); class.add(new Student("Eve", 76)); foreach(Student s : class) { System.out.println(s.getName() + " " + s.getScore()); } } TreeSet class uses “natural” ordering of objects stored in data structure, or a comparator. Iterator will return objects in that order. CS Computer Science II

17 CS 221 - Computer Science II
Output of Program Print out by name in alphabetical order: Ann 87 Bob 83 Cat 99 Dan 25 Eve 76 CS Computer Science II

18 CS 221 - Computer Science II
When to Use Each The Comparable interface is simpler and less work. Your class implements the Comparable interface. It provides a compareTo method. Uses the same comparison method every time, it’s “natural ordering.” The Comparator interface is more flexible but slightly more work. Create as many different classes that implement Comparator as you like. You can sort using the objects using the comparator you want. For example, sort Students by score or by name. CS Computer Science II

19 CS 221 - Computer Science II


Download ppt "Comparable and Comparator Interfaces"

Similar presentations


Ads by Google