VERSION 1
CIS265Lecture Notes
V. MatosChapter 14: Using the Compare Interface
Driver class
packagecsu.matos;
publicclass Driver {
/**
* Author: Matos
* Date: 11-July-2011
* Goal: Using the Compare interface on a Person class
*/
publicstaticvoid main(String[] args) {
Person p1 = newPerson("Maria Macarena", 28);
Person p2 = newPerson("Charlie Brown", 10);
int result = p1.compareTo(p2);
System.out.println("Macarena compared to Charlie: " + result);
}//main
}//Driver class
Person class
packagecsu.matos;
publicclass Person implements Comparable {
// class variables
private String mPersonName;
privateintmPersonAge;
// Constructor(s)
public Person(String mPersonName, intmPersonAge) {
super();
this.mPersonName = mPersonName;
this.mPersonAge = mPersonAge;
}
// Mutators
public String getmPersonName() {
returnmPersonName;
}
publicvoidsetmPersonName(String mPersonName) {
this.mPersonName = mPersonName;
}
publicintgetmPersonAge() {
returnmPersonAge;
}
publicvoidsetmPersonAge(intmPersonAge) {
this.mPersonAge = mPersonAge;
}
//custom method(s)
public String showData() {
return"Name: " + mPersonName + " Age: " + mPersonAge;
}
// our version of how to compare two Person objects
@Override
publicintcompareTo(Object otherPerson) {
if (this.mPersonAge == ((Person) otherPerson).getmPersonAge())
return 0;
elseif(this.mPersonAge < ((Person) otherPerson).getmPersonAge())
return -1;
else
return +1;
}
}//Person
Note:
The Compare Java Interface consists of only one method as follows
public interface Compare {
publicintcompareTo (ObjectotherObject);
}
VERSION 2Person class is implemented again, this time using a more ‘robust’ approach
CIS265Using Interfaces: Comparable, Comparator, Cloneable, Serializable
V. Matos
DRIVER
packagecsu.matos;
importjava.io.FileNotFoundException;
importjava.util.ArrayList;
importjava.util.Collections;
publicclass Driver {
/**
* Author: Matos
* Date:12-Sept-2011
* Goal:Contrasting Comparable and Comparator interfaces
* Illustrating the SerializableCloneable interfaces
*/
publicstaticvoid main(String[] args) throwsFileNotFoundException,
CloneNotSupportedException {
Person p1 = newPerson("Maria", 50);
Person p2 = newPerson("Charlie", 25);
// testing Comparable
if (p1.compareTo(p2) == 0 )
System.out.println("the same");
elseif (p1.compareTo(p2) < 0)
System.out.println("p2 is bigger");
else
System.out.println("p1 is bigger");
// testing Serializable "Marker" interface
p1.makePersistent();
p2.makePersistent();
// testing Compare interface
ArrayList<Person> list = newArrayList<Person>();
list.add(p1);
list.add(p2);
Person oldest = oldestPerson(list);
oldest.showData("oldest");
// testing Cloneable interface
Person p3 = (Person) p2.clone();
p2.showData("p2");
p3.showData("p3");
p2.setAge(1);
p2.showData("p2");
p3.showData("p3");
}//main
// ////////////////////////////////////////////////////////////////
// using the PersonComparator class as argument to the sort method
privatestatic Person oldestPerson(ArrayList<Person> list) {
Collections.sort(list, newPersonComparator());
return list.get(list.size()-1);
}
}
Person Class
packagecsu.matos;
importjava.io.File;
importjava.io.FileNotFoundException;
importjava.io.FileReader;
importjava.io.PrintWriter;
importjava.io.Serializable;
importjava.util.Scanner;
publicclass Person implements Comparable<Person>, Serializable, Cloneable {
privatestaticfinallongserialVersionUID = 1L;
// class variables
private String mPersonName;
privateintmAge;
// mutators
public String getPersonName() {
returnmPersonName;
}
publicvoidsetPersonName(String mPersonName) {
this.mPersonName = mPersonName;
}
publicintgetAge() {
returnmAge;
}
publicvoidsetAge(intmAge) {
this.mAge = mAge;
}
// constructor
public Person(String mPersonName, intmAge) {
super();
this.mPersonName = mPersonName;
this.mAge = mAge;
}
// custom methods /////////////////////////////////////////////////
publicvoidshowData() {
showData("");
}
publicvoidshowData(String userMsg) {
System.out.println(userMsg + " Person Name: " + this.mPersonName
+ " Age: "+ this.mAge);
}
// /////////////////////////////////////////////////////////////////
// implementing on behalf of Comparable interface
// ordering based on age (arbitrary decision)
@Override
publicintcompareTo(Person theOtherPerson) {
if (theOtherPerson.getAge() == this.getAge())
return 0;
elseif (theOtherPerson.getAge() > this.getAge())
return -1;
else
return 1;
}// compareTo
// NOT NEEDED. playing with methods to set/get persistent objects
publicvoidmakePersistent() throwsFileNotFoundException {
// serialize method - transfer object to output file
PrintWriteroutFile = newPrintWriter(
NewFile("c:\\temp\\person.txt"));
outFile.append(this.mPersonName + "\n");
outFile.append(this.mAge + "\n");
outFile.close();
// deserialize method - from file data to memory object
FileReadermyFile = newFileReader("c:\\temp\\person.txt");
Scanner inFile = newScanner(myFile);
while (inFile.hasNext()) {
String theName = inFile.nextLine();
String theAge = inFile.nextLine();
System.out.println (theName + " " + theAge);
}
}
// ///////////////////////////////////////////////////////////////////
@Override
protected Object clone() throwsCloneNotSupportedException {
returnsuper.clone();
}
}
PersonComparator Class
packagecsu.matos;
importjava.util.Comparator;
publicclassPersonComparatorimplements Comparator<Person>{
@Override
publicint compare(Person p1, Person p2) {
if (p1.getAge() == p2.getAge())
return 0;
elseif (p1.getAge() > p2.getAge())
return 1;
else
return -1;
}
}
Console
p1 is bigger
Maria 50
Charlie 25
oldest Person Name: Maria Age: 50
p2 Person Name: Charlie Age: 25
p3 Person Name: Charlie Age: 25
p2 Person Name: Charlie Age: 1
p3 Person Name: Charlie Age: 25
VERSION 3A variation in the compareTo method to operate on similar object types.
Replace compareTo(…) method in the Circle class with the following code
// ////////////////////////////////////////////////////////
@Override
publicintcompareTo(Object arg0) throwsIllegalArgumentException {
if (arg0 instanceof Circle) {
Circle otherCircle = (Circle) arg0;
if ((this.getRadius() == otherCircle.getRadius())
& (this.getColor().compareTo(otherCircle.getColor()) == 0))
return 0;
elseif (this.getRadius() > otherCircle.getRadius())
return 1;
else
return -1;
} else
thrownewIllegalArgumentException(
"Invalid type, expecting a Circle and receiving: "
+ arg0.getClass().getName());
}
Test the method adding the following fragment to the Driver class
Circle c1 = newCircle(2);
Circle c2 = newCircle(2);
Rectangle r1 = newRectangle(10, 20);
try {
int c1c2 = c1.compareTo(c2);
System.out.println( c1c2 );
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
System.out.println ("End of test1 - life goes on\n");
try {
int c1r1 = c1.compareTo(r1);
System.out.println( c1r1 );
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
System.out.println ("End of test2 - life goes on\n");
Console
0
End of test1 - life goes on
java.lang.IllegalArgumentException: Invalid type, expecting a Circle and receiving: csu.matos.Rectangle
atcsu.matos.Circle.compareTo(Circle.java:72)
atcsu.matos.Driver.main(Driver.java:53)
End of test2 - life goes on