Comparable and Comparator Interfaces

Slides:



Advertisements
Similar presentations
Problem Solving 5 Using Java API for Searching and Sorting Applications ICS-201 Introduction to Computing II Semester 071.
Advertisements

INTERFACES IN JAVA 1.Java Does not support Multiple Inheritance directly. Multiple inheritance can be achieved in java by the use of interfaces. 2.We need.
Computer Science 209 Software Development Equality and Comparisons.
Using interfaces Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling How would you find the maximum.
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.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 24 : Collections King Fahd University of Petroleum & Minerals College of Computer.
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.
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
Programming 2 LAB TA: Nouf Al-Harbi NoufNaief.net :::
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.
CMSC 202 Interfaces. 11/20102 Classes and Methods When a class defines its methods as public, it describes how the class user interacts with the method.
Goals for Today  implement a Deck of Cards  composition  Iterator interface  Iterable interface 1.
Inheritance. Inheritance Early programmers often wrote code very similar to existing code Example: A human resources system might handle different types.
© A+ Computer Science - public Triangle() { setSides(0,0,0); } Constructors are similar to methods. Constructors set the properties.
CS 206 Introduction to Computer Science II 09 / 10 / 2009 Instructor: Michael Eckmann.
CS-2852 Data Structures LECTURE 7A Andrew J. Wozniewicz Image copyright © 2010 andyjphoto.com.
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.
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.
SourceAnatomy1 Java Source Anatomy Barb Ericson Georgia Institute of Technology July 2008.
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.
Programming in Java Transitioning from Alice. Becomes not myFirstMethod but …. public static void main (String[] arg) { // code for testing classes goes.
יסודות מדעי המחשב – תרגול 6
Searching.
Chapter Goals To be able to declare and use interface types
Software Development Java Classes and Methods
ADT’s, Collections/Generics and Iterators
IST311 / 602 Cleveland State University – Prof. Victor Matos
Chapter 8 Classes and Objects
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,
CIS3023: Programming Fundamentals for CIS Majors II
String Handling in JAVA
SELECTION STATEMENTS (1)
Introduction to Searching and Sorting
Comparable and Comparator Interfaces
CSC 113 Tutorial QUIZ I.
Comparable and Comparator
CMSC 202 Interfaces.
Interfaces and Constructors
Abstract Class As per dictionary, abstraction is the quality of dealing with ideas rather than events. For example, when you consider the case of ,
The compareTo interface
Comparable and Comparator
مظفر بگ محمدی دانشگاه ایلام
OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS
CMSC 202 Interfaces.
ArrayLists 22-Feb-19.
Lexical Ordering and Sorting
Searching.
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
Methods/Functions.
CMSC 202 Interfaces.
Comparable and Comparator Interfaces
Introduction to Java Collection
Presentation transcript:

Comparable and Comparator Interfaces There's very little that's comparable to seeing the spark in a student's face when she gets something that she's been struggling with. - Alexi Zentner

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 of the objects, not their content The Object class does not provide any methods for comparing objects 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 A negative number if the calling object "comes before" the parameter A zero if the calling object "equals" the parameter other A positive number if the calling object "comes after" the parameter other 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. 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) { this.name = name; this.score = score; } Sort students according to score public int compareTo(Object o) { return score - ((Student)o).score; } CS 221 - Computer Science II

Using Student Class, Ver. 1 public static void main(String args[]) { TreeSet<Student> set = new TreeSet<Student>(); set.add(new Student("Ann", 87)); set.add(new Student("Bob", 83)); set.add(new Student("Cat", 99)); set.add(new Student("Dan", 25)); set.add(new Student("Eve", 76)); Iterator<Student> itr = set.iterator(); while (itr.hasNext()) { Student s = itr.next(); System.out.println(s.name + " " + s.score); } } CS 221 - Computer Science II

CS 221 - Computer Science II Output of Program Using an iterator, print out the values in order and get the following result: 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 So, can sort students only by their score If we wanted to sort students another way, such as by name, we are out of luck To make comparison using other criteria, 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 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.score – s2.score; } 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 If our parameters are Objects, they have to be cast to Students CS 221 - Computer Science II

Using Student Class, Ver. 2 public static void main(String args[]) { Comparator<Student> comp = new StudentComparator(); TreeSet<Student> set = new TreeSet<Student>(comp); set.add(new Student("Ann", 87)); set.add(new Student("Bob", 83)); set.add(new Student("Cat", 99)); set.add(new Student("Dan", 25)); set.add(new Student("Eve", 76)); Iterator<Student> itr = set.iterator(); while (itr.hasNext()) { Student s = itr.next(); System.out.println(s.name + " " + s.score); } } CS 221 - Computer Science II

CS 221 - Computer Science II Output of Program Using an iterator, print out the values in order and get the same result: Dan 25 Eve 76 Bob 83 Ann 87 Cat 99 What if want to sort the students by name instead of scores? CS 221 - Computer Science II

CS 221 - Computer Science II Another Comparator public class StudentByNameComparator implements Comparator<Student> { public int compare(Student s1, Student s2) { return s1.getName.compareTo(s2.getName); } } 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 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