This document discusses the Comparable and Comparator interfaces in Java. Comparable allows an object to compare itself to another object, while Comparator allows two objects to be compared to each other based on arbitrary criteria. The document provides examples of implementing these interfaces to allow collections like lists to be sorted. It also discusses function objects and anonymous classes in Java.
Comparable/Comparator Interfaces
ďTopics:
ď Comparable and Comparator interfaces in JCF
ď âJava Collections Frameworkâ
ď Function objects
1
2.
Back to Java:Comparable / Comparator
ď In computing, we often want to order a set of items
ď Find the max/best or min/worst
ď Sort them in order
ď Note how this is different than what is needed for search
(where we just need equals)
ď Need a way to compare two items
ď Want a flexible way to âcompareâ using different criteria
ď In Java, letâs us use Collection(s) methods to meet our
own special needs. (Powerful!)
2
3.
Check out theCollections class
ď Class Collections
ď utility methods for doing operations on Collections, Lists (that
almost always contain homogenous elements)
ď 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
3
4.
Comparable Interface
ďFirst solution: Can we ask an object how it compares
to a second object?
ď Sure: string1.compareTo(string2)
ď Programming convention: Return value as follows:
ď zero if the same
ď negative value if first item strictly less than second
ď positive value if first item strictly greater than second
ď Java provides a Comparable interface
int compareTo(YourClass o)
ď Note the parameter is an object of the same type as the
class in which youâre defining compareTo()
4
5.
Hang on: Whatâsan Interface?
ď When defining a class, state that it âimplementsâ an
interface. E.g.
public class Watch implements TimeKeeper {
ď What else is the meaning of the interface TimeKeeper?
ď A set of methods that any implementing class must
include
ď TimeKeeper interface doesnât define how these methods
are coded
ď Watch (the implementing class) is promising to include
those in its definition
5
6.
Example
ď ATimeKeeper Interface defined with its 2 methods:
getTime() and set Time()
ď Now a Watch class is declared to implement
TimeKeeper
ď Watch is promising to have these 2 methods as part
of its definition (getTime() and setTime())
ď Watch can implement those how ever it wants
ď It means Watch, by implementing TimeKeeper, can
handle the TimeKeeper role
6
7.
Interface gives anObject another Type
ď With this definition:
public class Watch implements TimeKeeper {
ď 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)
7
8.
Interface gives anObject another Type
ď Interfaces are legal Java types. Therefore can be
used
ď To declare variables
ď As a parameter type (passing a variable to a
method)
ď As a return type
8
9.
Example
ď Ifyou have a method that took a TimeKeeper as a
parameter
ď A Watch could be used as a parameter to that method,
because a Watch plays the role of a TimeKeeper
ď If that method takes a TimeKeeper as a parameter, then
we can pass it a Watch
ď ď You can think of the Watch object as having more than
one type. (Every Watch also fills the role as Time Keeper)
9
10.
What are wegetting at?
ď The method sort can take an ArrayList as an argument (an
ArrayList of something) Of what? It can take an ArrayList of
anything that meets this interface called Comparable
ď The parameter has to be an ArrayList of any class that
implements the comparable interface â that means it has
the compareTo() method â which means inside of sort, it
knows it can call get() to get 2 items from the ArrayList and
use the compareTo() method â its guaranteed to have it
because that class implements the Comparable interface
10
11.
Writing compareTo forYour Classes
ď If you ever want to put your own objects in
Collections, and use sort(), max(), min(),âŚ
1. Make your class implement Comparable
2. Implement the compareTo() method in your class
ď How to write compareTo()?
ď Think about state-variables that determine natural order
ď Compare them and return proper-value
ď Note: For number values, you can subtract.
ď For object values, call compareTo() on them.
11
12.
Letâs Get Practical
ď You can sort an ArrayList⌠BUT the ArrayList has
to have things inside it that implement the
Comparable Interface
ď Can we sort an ArrayList of Strings?
ď Go to API for class String (Google: âjava api stringâ)
ď On âAll Implemented Interfacesâ â one of them is
comparable!
ď Scroll to âMethod Summaryâ â has compareTo()
method!
ď So you can definitely sort an ArrayList of Strings
12
13.
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;
}
13
Under the Hoodfor Sorting
ď How might a sort() or any other method use this? Imagine:
ď Its parameter is of the type List<Comparable>
ď ArrayList is a type-of List in Java (more on this later)
ď Inside a loop, code might look like this:
Comparable item1 = theList.get(i);
Comparable item2 = 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!
15
16.
Flexible Design usingComparators
ď Solution #1: Make classes Comparable
ď Disadvantage: 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
16
17.
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
17
18.
Function Objects inJava
ď 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
18
19.
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!
19
20.
Example: Comparator objects
ď 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
20
21.
Writing a ComparatorClass
ď Example like one from MSD text, p. 647
ď We have a Dog class with name, breed and gender
ď Compare two doggies by breed and then name
public class CmpDogByBreedAndName implements Comparator<Dog> {
public int compare(Dog d1, Dog d2) {
int retVal = d1.getBreed().compareTo(d2.getBreed());
if ( retVal != 0 ) return retVal;
return d1.getName().compareTo( d2.getName() );
}
}
21
22.
Use of Comparatormethods
ď How to use with Collections.sort()
ď ArrayList dogList = âŚ;
Collections.sort( dogList, new CmpDogByName() );
Collections.sort( dogList, new CmpDogByBreed() );
ď (Do you understand what new does here?)
ď Inside sort(), code looks something like this:
sort ( List theList, Comparator cmpObj ) {
// in some loop
Object item1 = list.get(i);
Object item2 = list.get(j);
cmpResult = cmpObj.compare(item1,item2);
22
Java Aside: AnonymousClasses
ď Thereâs a Java technique called anonymous classes
ď One of several types of nested class definition
ď Youâll very often see it in GUI programming (Swing) and
with threads
ď Situation:
ď Sometimes Javaâs design encourages us to create some
thing that might be used just once
ď That thing needs to be wrapped up in a class, say
because we need a function object
24
25.
Creating and Usingan Anonymous Class
ď Example: sort a list of Strings by their length
ď Collections.sort ( stringList, new Comparator() {
public int compare( Object o1, Object o2 ) {
return ((String) o1).length() â
((String) o2).length();
}
} ) ;
ď Weâve created a new Comparator âon the flyâ
ď new creates a new instance, but what kind?
ď Some object that implements Comparator
ď Object not named, and its âtrueâ class not named!
ď What must a Comparator have? compare()
ď We defined it right here, where itâs used! 25
26.
Anonymous Classes: Comments
ď Anonymous classes are
unlike other classes
ď They have no name
ď Typically only implement
methods in their interface or
superclass. No new
methods!
ď Since they have no name,
can only define and use
them at one point in your
code!
ď Hard to understand at first?
Sure!
ď Naming an abstraction is
important for human
understanding!
ď Sorting, a Collection,
Comparing
ď Advice
ď Keep them very short (and
simple)!
ď Be ready to understand
them when you see them in
Swing and with threads
26