Comparable and Comparator Interfaces

Slides:



Advertisements
Similar presentations
Sets and Maps Part of the Collections Framework. 2 The Set interface A Set is unordered and has no duplicates Operations are exactly those for Collection.
Advertisements

Problem Solving 5 Using Java API for Searching and Sorting Applications ICS-201 Introduction to Computing II Semester 071.
Computer Science 209 Software Development Equality and Comparisons.
Chapter 7 Strings F To process strings using the String class, the StringBuffer class, and the StringTokenizer class. F To use the String class to process.
Using interfaces Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling How would you find the maximum.
CSE 143 Lecture 17 Binary Search Trees and Comparable slides created by Ethan Apter
Searching. 2 Searching an array of integers If an array is not sorted, there is no better algorithm than linear search for finding an element in it static.
Searching and Sorting I 1 Searching and Sorting 1.
Comparable and Comparator Nuts and Bolts. 2 Nuts and bolts Four methods underlie many of Java’s important Collection types: equals, compare and compareTo,
Unit 261 Introduction to Searching and Sorting Comparable Interface Comparator Interface Algorithm Complexity Classes Exercises.
CS 106 Introduction to Computer Science I 11 / 20 / 2006 Instructor: Michael Eckmann.
Comparable and Comparator. Outline of the Student class import java.util.*; public class Student implements Comparable { public Student(String name, int.
ICS201 Lecture 20 : Searching King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department.
Searching. 2 Searching an array of integers If an array is not sorted, there is no better algorithm than linear search for finding an element in it static.
CS 106 Introduction to Computer Science I 03 / 08 / 2010 Instructor: Michael Eckmann.
1 Introduction to Searching and Sorting Comparable Interface -Reading p Comparator Interface.
Unit 261 Introduction to Searching and Sorting Comparable Interface Comparator Interface Algorithm Complexity Classes Exercises.
Searching. Searching an array of integers If an array is not sorted, there is no better algorithm than linear search for finding an element in it static.
Introduction to Searching and Sorting
Comparable and Comparator. 2 Comparing our own objects The Object class provides public boolean equals(Object obj) and public int hashCode() methods –For.
Comparing Objects in Java. The == operator When you define an object, for instance Person p = new Person("John", 23); we talk about p as if its value.
Searching Also: Logarithms. 2 Searching an array of integers If an array is not sorted, there is no better algorithm than linear search for finding an.
Set, TreeSet, TreeMap, Comparable, Comparator. Def: The abstract data type set is a structure that holds objects and satifies ARC: Objects can be added.
CS-2851 Dr. Mark L. Hornick 1 Tree Maps and Tree Sets The JCF Binary Tree classes.
Collections F The limitations of arrays F Java Collection Framework hierarchy  Use the Iterator interface to traverse a collection  Set interface, HashSet,
Week 3 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
CS 206 Introduction to Computer Science II 09 / 10 / 2009 Instructor: Michael Eckmann.
CS 151: Object-Oriented Design September 26 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 10 - Interfaces.
Comparable and Comparator Nuts and Bolts. Sets A set is a collection in which all elements are unique—an element is either in the set, or it isn’t In.
SETS AND MAPS Collections of Data. Advanced Data Structures Often referred to as the Java Collections Framework…. Set and map data types Hash tables Binary.
Coding Bat: Ends in ly Given a string of even length, return a string made of the middle two chars, so the string "string" yields "ri". The string.
Sets and Maps Sets Maps The Comparator Interface Sets and Maps in Java Collections API – TreeSet – TreeMap Review for Exam Reading:
CS 106 Introduction to Computer Science I 03 / 02 / 2007 Instructor: Michael Eckmann.
Topic 7 Interfaces I once attended a Java user group meeting where James Gosling (one of Java's creators) was the featured speaker. During the memorable.
The Java Tutorials Comparable and Comparator. Object Ordering A List may be sorted as follows. Collections.sort(l); If the List consists of String elements,
Sets and Maps Part of the Collections Framework. 2 The Set interface A Set is unordered and has no duplicates Operations are exactly those for Collection.
COMP Inheritance and Polymorphism Yi Hong June 09, 2015.
19-Mar-16 Collections and ArrayLists.. 2 Collections Why use Collections. Collections and Object-Orientation. ArrayLists. Special Features. Creating ArrayLists.
Coming up Implementation vs. Interface The Truth about variables Comparing strings HashMaps.
Introduction to Java Collection. Java Collections What are they? –A number of pre-packaged implementations of common ‘container’ classes, such as LinkedLists,
Collections ABCD ABCD Head Node Tail Node array doubly linked list Traditional Arrays and linked list: Below is memory representation of traditional.
יסודות מדעי המחשב – תרגול 6
Lecture 23:More on Interfaces
Searching.
Software Development Java Classes and Methods
Efficiency of in Binary Trees
IST311 / 602 Cleveland State University – Prof. Victor Matos
Interfaces I once attended a Java user group meeting where James Gosling (Java's inventor) was the featured speaker. During the memorable Q&A session,
Java Collections Overview
Topic 7 Interfaces I once attended a Java user group meeting where James Gosling (one of Java's creators) was the featured speaker. During the memorable.
Introduction to Searching and Sorting
Introduction to Collections
Comparable and Comparator
Interfaces and Constructors
Testing and debugging A short interlude 2-Dec-18.
The compareTo interface
Comparable and Comparator
Comparable and Comparator Interfaces
ArrayLists 22-Feb-19.
Introduction to Collections
Lexical Ordering and Sorting
Searching.
Testing and debugging A short interlude 17-Apr-19.
IST311 / 602 Cleveland State University – Prof. Victor Matos
CSE 142 Lecture Notes Defining New Types of Objects, cont'd.
Creating and Modifying Text part 3
TCSS 143, Autumn 2004 Lecture Notes
Comparable and Comparator Interfaces
Introduction to Java Collection
Presentation transcript:

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

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 221 - Computer Science II

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 221 - Computer Science II

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 221 - Computer Science II

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 221 - Computer Science II

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 221 - Computer Science II

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 221 - Computer Science II

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 221 - Computer Science II

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 221 - Computer Science II

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 221 - Computer Science II

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 221 - Computer Science II

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 221 - Computer Science II

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 221 - Computer Science II

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 221 - Computer Science II

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 221 - Computer Science II

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 221 - Computer Science II

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 221 - Computer Science II

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 221 - Computer Science II

CS 221 - Computer Science II