Comparable and Comparator. Outline of the Student class import java.util.*; public class Student implements Comparable { public Student(String name, int.

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

DATA STRUCTURES Lecture: Interfaces Slides adapted from Prof. Steven Roehrig.
SUMMARY: abstract classes and interfaces 1 Make a class abstract so instances of it cannot be created. Make a method abstract so it must be overridden.
Problem Solving 5 Using Java API for Searching and Sorting Applications ICS-201 Introduction to Computing II Semester 071.
METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
Lecture 17 Abstract classes Interfaces The Comparable interface Event listeners All in chapter 10: please read it.
Lecture 27 Exam outline Boxing of primitive types in Java 1.5 Generic types in Java 1.5.
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.
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.
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
12-Jul-15 Lists in Java Part of the Collections Framework.
Comparable and Comparator. 2 Comparing our own objects The Object class provides public boolean equals(Object obj) and public int hashCode() methods –For.
1 Introduction to Searching and Sorting Comparable Interface -Reading p Comparator Interface.
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.
Java CourseWinter 2009/10. Introduction Object oriented, imperative programming language. Developed: Inspired by C++ programming language.
Collections. Why collections? Collections are used to hold a collection of objects. List holds objects based on order of insertion and can hold non unique.
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.
Sets and Maps Part of the Collections Framework. The Set interface A Set is unordered and has no duplicates Operations are exactly those for Collection.
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.
Polymorphism & Interfaces
Data Objects (revisited) Recall that values are stored in data objects, and that each data object holds one value of a particular type. Data objects may.
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.
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
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.
Java the UML Way versjon Only to be used in connection with the book "Java the UML Way", by Else Lervik and.
Recitation 4 Abstract classes, Interfaces. A Little More Geometry! Abstract Classes Shape x ____ y ____ Triangle area() base____ height ____ Circle area()
Puzzle 3 1  Write the class Enigma, which extends Object, so that the following program prints false: public class Conundrum { public static void main(String[]
1 Interfaces Reading for today: Sec and corresponding ProgramLive material. Also, compare with previous discussions of abstract classes (Sec. 4.7).
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.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
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.
Inheritance (Part 5) Odds and ends 1. Static Methods and Inheritance  there is a significant difference between calling a static method and calling a.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Interfaces and Inner Classes
Lecture 7 February 24, Javadoc version and author Tags These go in the comments before named classes. –Put your SS# on a separate line from the.
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
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.
FIT Objectives By the end of this lecture, students should: understand the role of constructors understand how non-default constructors are.
Classes Revisited Chapter 8.
COMP Inheritance and Polymorphism Yi Hong June 09, 2015.
Comp1004: Environments The Java Library. Coming up Recap – Encapsulation – Constructors – Loops – Arrays – ArrayList – Iterators The Java Library – Implementation.
Searching.
Interfaces and Inheritance
Java Collections Overview
Introduction to Searching and Sorting
Comparable and Comparator Interfaces
Comparable and Comparator
CMSC 202 Interfaces.
Java Programming Language
Fall 2018 CISC124 12/3/2018 CISC124 or talk to your grader with questions about assignment grading. Fall 2018 CISC124 - Prof. McLeod Prof. Alan McLeod.
Comparable and Comparator
مظفر بگ محمدی دانشگاه ایلام
Comparable and Comparator Interfaces
Searching.
Creating and Modifying Text part 3
Part of the Collections Framework
CMPE212 – Reminders Assignment 2 due next Friday.
Comparable and Comparator Interfaces
Presentation transcript:

Comparable and Comparator

Outline of the Student class import java.util.*; public class Student implements Comparable { public Student(String name, int score) {...} public int compareTo(Object o) throws ClassCastException {...} public static void main(String args[]) {...} }

Constructor for Student This is the same for both methods—nothing new here public Student(String name, int score) { this.name = name; this.score = score; } We will be sorting students according to their score

The main method, version 1 public static void main(String args[]) { TreeSet set = new TreeSet(); 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 iter = set.iterator(); while (iter.hasNext()) { Student s = (Student)iter.next(); System.out.println(s.name + " " + s.score); } }

Using the TreeSet In the main method we have the line TreeSet set = new TreeSet(); Later we use an iterator to 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 Student s by score, rather than, say, by name ?

Implementing Comparable public class Student implements Comparable This means it must implement the method public int compareTo(Object o) 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 public int compareTo(Object o) throws ClassCastException { if (o instanceof Student) return score - ((Student)o).score; else throw new ClassCastException("Not a Student!"); } A ClassCastException should be thrown if we are given a non- Student parameter

An improved method * Since casting an arbitrary Object to a Student may throw a classCastException for us, we don’t need to throw it explicitly public int compareTo(Object o) throws ClassCastException { return score - ((Student)o).score; } Moreover, since classCastException is a subclass of RuntimeException, we don’t even need to declare that we might throw one: public int compareTo(Object o) { return score - ((Student)o).score; } *Suggested by Randall Sidlinger

Using a separate Comparator In the program we just finished, Student implemented Comparable –Therefore, it had a compareTo method Now we will put the comparison method in a separate class This is more flexible (you can use a different Comparator to sort Students by name), but it’s also clumsier This new class will implement Comparator instead of Comparable Comparable requires a definition of compareTo but Comparator requires a definition of compare Comparator also (sort of) requires equals

Outline of StudentComparator import java.util.*; public class StudentComparator implements Comparator { public int compare(Object o1, Object o2) {...} public boolean equals(Object o1) {...} } Note: When we are using this Comparator, we don’t need the compareTo method in the Student class

The compare method public int compare(Object o1, Object o2) { return ((Student)o1).score - ((Student)o2).score; } This differs from compareTo(Object o) in Comparable in these ways: –The name is different –It takes both objects as parameters, not just one –We have to check the type of both objects –Both objects have to be cast to Student –Also note that Comparable is defined in java.lang (which is always imported automatically), but Comparator is defined in java.util.

The equals method This method is not used to compare two Student s— it is used to compare two Comparator s Even though it’s part of the Comparator interface, you don’t actually need to override it, since you inherit equals from Object anyway In fact, it’s always safe to ignore it The purpose is efficiency—you can replace one Comparator with an equal but faster one My opinion: ignore this method entirely!

The main method The main method is just like before, except that instead of TreeSet set = new TreeSet(); We have Comparator comp = new StudentComparator(); TreeSet set = new TreeSet(comp);

When to use each The Comparable interface is simpler and less work –Say your class implements Comparable –Provide a public int compareTo(Object o) method –Use no argument in your TreeSet or TreeMap constructor –You will use the same comparison method every time The Comparator interface is more flexible and more work –Create as many different classes that implement Comparator as you like –You can sort the TreeSet or TreeMap differently with each –For example, sort Student s by score or by name

Sorting differently Suppose you have students sorted by score, in a TreeSet you call studentsByScore Now you want to sort them again, this time by name Comparator myStudentNameComparator = new MyStudentNameComparator(); TreeSet studentsByName = new TreeSet(myStudentNameComparator); studentsByName.addAll(studentsByScore);

The End