Comparable and Comparator Interfaces Ben Rodes. Disclaimer.

Slides:



Advertisements
Similar presentations
Introduction to Java 2 Programming Lecture 5 The Collections API.
Advertisements

Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
Chapter 12 Lists and Iterators. List Its an abstract concept not a vector, array, or linked structure. Those are implementations of a List. A list is a.
Generics, Lists, Interfaces
Introduction to Recursion and Recursive Algorithms
How do Methods Work?. Let’s write a method that adds two integer values together and returns the result.
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.
Computer Science 209 Software Development Equality and Comparisons.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 11: Sorting and Searching  Searching Linear Binary  Sorting.
CS 106 Introduction to Computer Science I 11 / 20 / 2006 Instructor: Michael Eckmann.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Interfaces. In this class, we will cover: What an interface is Why you would use an interface Creating an interface Using an interface Cloning an object.
Lists and the Collection Interface Chapter 4. Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.
CS 106 Introduction to Computer Science I 03 / 07 / 2008 Instructor: Michael Eckmann.
Fall 2007CS 2251 Lists and the Collection Interface Chapter 4.
CS 106 Introduction to Computer Science I 03 / 03 / 2008 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 03 / 08 / 2010 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 04 / 21 / 2008 Instructor: Michael Eckmann.
CS 2511 Fall Features of Object Oriented Technology  Abstraction Abstract class Interfaces  Encapsulation Access Specifiers Data Hiding  Inheritance.
CS 2511 Fall  Abstraction Abstract class Interfaces  Encapsulation Access Specifiers Data Hiding  Inheritance  Polymorphism.
CS 106 Introduction to Computer Science I 04 / 28 / 2010 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 10 / 15 / 2007 Instructor: Michael Eckmann.
Interfaces and Inner Classes. What is an Interface?  What is “presented to the user”?  The public part of a class?  What is the substance of an interface?
CS 106 Introduction to Computer Science I 10 / 16 / 2006 Instructor: Michael Eckmann.
Chapter 10 2D Arrays Collection Classes. Topics Arrays with more than one dimension Java Collections API ArrayList Map.
CS 106 Introduction to Computer Science I 04 / 30 / 2010 Instructor: Michael Eckmann.
Building Java Programs Interfaces, Comparable reading: , 16.4, 10.2.
CSE 332: C++ templates and generic programming I Motivation for Generic Programming in C++ We’ve looked at procedural programming –Reuse of code by packaging.
Intro to Generic Programming Templates and Vectors.
Abstract Data Types (ADTs) Data Structures The Java Collections API
OOP Languages: Java vs C++
Object Oriented Software Development
Programming Languages and Paradigms Object-Oriented Programming.
CS2110: SW Development Methods Textbook readings: MSD, Chapter 8 (Sect. 8.1 and 8.2) But we won’t implement our own, so study the section on Java’s Map.
CS 106 Introduction to Computer Science I 03 / 19 / 2007 Instructor: Michael Eckmann.
Chapter 9: Polymorphism Coming up: Creating Objects Revisited.
Programming Languages and Paradigms Object-Oriented Programming (Part II)
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Chapter 7 Objects and Classes 1 Fall 2012 CS2302: Programming Principles.
5-Aug-2002cse Arrays © 2002 University of Washington1 Arrays CSE 142, Summer 2002 Computer Programming 1
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Chapter 2 Introducing Interfaces Summary prepared by Kirk Scott.
Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???
CS 106 Introduction to Computer Science I 04 / 23 / 2010 Instructor: Michael Eckmann.
Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.
Linked List. Iterators Operation to find a link, deleting, and inserting before or after a specified link, also involve searching through the list to.
C Functions Three major differences between C and Java functions: –Functions are stand-alone entities, not part of objects they can be defined in a file.
RUN-Time Organization Compiler phase— Before writing a code generator, we must decide how to marshal the resources of the target machine (instructions,
CS2210: SW Development Methods Topics: Comparable and Comparator interfaces in JCF Function objects Textbook readings: More from MSD, Chapter 9 Pages
Problem of the Day  Simplify this equation: (x - a) * (x - b) * (x - c) * … * (x - z)
Design Patterns David Talby. This Lecture Re-routing method calls Chain of Responsibility Coding partial algorithms Template Method The Singleton Pattern.
M1G Introduction to Programming 2 5. Completing the program.
Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.
Introduction to Object-Oriented Programming Lesson 2.
CS 106 Introduction to Computer Science I 03 / 02 / 2007 Instructor: Michael Eckmann.
CSE 143 Lecture 2 More ArrayList ; classes and objects reading: 10.1; slides created by Marty Stepp and Hélène Martin
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.
CS2 Module 26 Category: OO Concepts Topic: Interfaces Objectives –Interfaces.
C# Fundamentals An Introduction. Before we begin How to get started writing C# – Quick tour of the dev. Environment – The current C# version is 5.0 –
Interfaces & Sub-types Weiss sec Scenario Instructor says: “Implement a class IntegerMath with two methods pow and fact with the following signatures:
CSC 243 – Java Programming, Spring, 2014 Week 4, Interfaces, Derived Classes, and Abstract Classes.
CPSC 252 ADTs and C++ Classes Page 1 Abstract data types (ADTs) An abstract data type is a user-defined data type that has: private data hidden inside.
Lecture 5:Interfaces and Abstract Classes Michael Hsu CSULA.
Today Encapsulation. Build a fully encapsulated Halloween class, going from Halloween1 to Halloween6 (eventually!): –The final version will have overloaded.
Lecture 6:Interfaces and Abstract Classes Michael Hsu CSULA.
Java Algorithms.
Abstract Class As per dictionary, abstraction is the quality of dealing with ideas rather than events. For example, when you consider the case of ,
Ben’s Lecture Cliff Notes
Interfaces.
Java Programming Language
Presentation transcript:

Comparable and Comparator Interfaces Ben Rodes

Disclaimer

Interfaces  Problem: You don’t know what an interface is yet! Seems problematic  So what is an interface? Its not a class! A group of related methods with no bodies (no definition, just method signatures)

Interfaces  A class may implement any number of interfaces.  To implement an interface is a contract. The implementer must define the interface functions!  Why do this? We can use objects of an interface type, without knowing their actual instance type. Let’s look at an example.

Interfaces public interface TimeKeeper { public Time getTime(); public void setTime(Time); …. }

Interfaces public class Watch implements TimeKeeper { //Whatever fields go here //Constructor, methods …. public Time getTime() { //Define this function } public void setTime() { //Define this function }

Interfaces You can think of Watch in these ways: You can treat a Watch object as a TimeKeeper A Watch object can do “TimeKeeper things” A Watch object can be used anywhere a TimeKeeper is legal to use  A Watch object has more than one type It’s a Watch (defined by the class Watch) It’s a TimeKeeper (defined by the interface)

Interfaces  Okay but why? Hold on, I am getting there!  Let’s pretend you want to write some generic function to work on TimeKeepers

Interfaces public Time getAVGClkDiff(ArrayList clocks) { //Loop over each element in clocks //for each element e e.getTime(); //Get the time, store it, take an average }  This may not be the exactly right syntax, but the right idea

Interfaces  Okay, dumb example, but … We don’t care what the actual time keepers are Because an interface is a contract, we know a TimeKeeper has a getTime function, and we can treat each element as a TimeKeeper, rather than whatever instance it actually is.  Similar idea to inheritance, but is subtly different. Interfaces do not show inheritance. Relationships are maintained among diverse objects. More to come later.

The Comparable Interface  Comparable is an interface Defined in the Java API  Contains only one method compareTo(SomeObject o2)  There are functions in the Java API you can use to do useful things if your objects implement this interface.

Check out the Collections class  Class Collections utility methods for doing operations on Collections  Note very similar Arrays class See MSD textbook, Section 9.5, pp. 666f  Methods (static, mostly for Lists) search a list for an item: binarySearch() sort(), max(), min() -- uses compareTo() or Comparator object reverse(), fill(), shuffle(), copy(), replaceAll() List list2 = Collections.unmodifiableList(list1); // p. 668

Collections Sort  Accepts a List of comparable objects.  How might a sort() or any other method use this? Imagine: Perhaps items stored as a list of Objects: List theList …;  Inside a loop, code might look like this: Comparable item1 = (Comparable) theList.get(i); Comparable item2 = (Comparable) theList.get(j); int cmpResult = item1.compareTo(item2);  Such code will work when the list stores any class that implements Comparable!  But, what happens if list-elements are of different classes (still Comparable, but different)? compareTo() fails!  Lets look at an example!

Example: Writing compareTo()  Imagine something like an entry in a phonebook Order by last name, first name, then number int compareTo(PhoneBookEntry item2 ) { int retVal= last.compareTo(item2.last); if ( retVal != 0 ) return retVal; retVal = first.compareTo(item2.first); if ( retVal != 0 ) return retVal; retVal = phNum - item2.phNum; return retVal; }

Comparable Problems  Lack of flexibility  Just one way to compare is possible, because there’s just one compareTo method per class  Possible solutions: Separate functions: sortByName(), sortByNum(),…  We can’t predict in advance how you’ll want to sort! Pass a parameter to indicate control: sort(theList, “byName”) or sort(theList, “byNum”);  Ugh. Same problem as before  And the internals of sort() will grow to become very ugly

Function Objects  We need to somehow pass “how to execute” information as a parameter to sort() We pass objects as parameters Can we pass a method/operation as an object?  Many languages support this, but in different ways: C and C++ – pointers to functions C# – delegates Java – “function objects” that  implement a specified interface, and  the one method in that interface does the needed work

Function Objects in Java  Idea: encapsulate a function inside a class  Note: not our usual idea of a class State? (None.) Identity? (Just need one instance.) Represents an entity? (Nope! Just a place to stash a function so it can be passed as a parameter.)  Warning / caveat! This idea is contrary to many OO principles, but… Useful if done in limited circumstances Use it when the libraries make it available Not often part of your own class-design  But use it in libraries when it’s part of the framework

Example: Comparator objects  We want to pass a function-object to a method: Collections.sort(someList, function-object-goes-here); But what type should this object be? Use an Interface:  Interface name can be used as a type in the parameter list  Interface defines the method name itself!  Java’s Comparator interface: int compare( Object o1, Object o2); Notes: not compareTo()! Takes two parameters!  Define a class for each kind of comparison you want. E.g. Classes: CmpStudentByGpa, CmpStudentByGpaDesc Classes: CmpDogByName, CmpDogByBreed  Example?

Writing a Comparator Class  Example on following slides like one from MSD text, p We have a Dog class with name, breed and gender  But see simpler example in Java on website list of Student objects sort by name, gpa  Also sort in descending order too  Look at testSorting1() in TestDriver class  Look at compareTo() in Student  Look at use of comparator classes