Trying to Sort with java.util.Comparator
Hello,
A bit puzzled here.
Having three classes;
(1) called the Starter - here is my Main-method.
(2) called the GolfHole.
(3) called the GolfHoleComparator.
Wanting to sort my golfHoles according to their difficulties.
The problem is that I am only able to add 2 GolfHoles to Set in the Starter class.
What am I doing wrong here?
here are the classes:
(1)
import java.util.*;
publicclass Starter{
publicstaticvoid main(String args[]){
System.out.println("GolfCourse");
Set golfCourseSet =new TreeSet(new HoleComparator() );
golfCourseSet.add(new Hole(1,5,13) );
golfCourseSet.add(new Hole(2,4,3) );
golfCourseSet.add(new Hole(3,3,15) );
Iterator iterator = golfCourseSet.iterator();
System.out.println("A sorted list of the holes on the course based on their difficulty");
System.out.println("number of holes is: " + golfCourseSet.size());
while(iterator.hasNext()){
Hole theHole = (Hole)iterator.next();
System.out.println( theHole );
}
}// end main
}// end class
(2)
publicclass Hole{
private String name;
privateint holeNr;
privateint par;
privateint hcp;
protected Hole(int holeNr,int par,int hcp){
this.holeNr=holeNr;
this.par=par;
this.hcp=hcp;
}
publicint getHoleNr(){
return this.holeNr;
}
publicint getPar(){
return this.par;
}
publicint getHcp(){
return this.hcp;
}
public String toString(){
return"Hole nr: "+holeNr +". Par: "+par+". Difficulty order: "+hcp;
}
}
(3)
import java.util.Comparator;
import java.io.Serializable;
publicclass HoleComparatorimplements Comparator,Serializable{
// Sorint according to difficulty
publicint compare(Object o1,Object o2){
if(!(o1instanceof Hole))thrownew ClassCastException();
if(!(o2instanceof Hole))thrownew ClassCastException();
Hole hole1 = (Hole)o1;
Hole hole2 = (Hole)o2;
int hcp1 = hole1.getHcp();
int hcp2 = hole2.getHcp();
System.out.println("Hcp 1: "+ hcp1 );
System.out.println("Hcp 2: "+ hcp2 );
if (hcp1 < hcp2)
return -1;
if ( hcp2 > hcp2)
return 1;
elsereturn 0;
}
}
The outcome of this code is the following.
GolfCourse
Hcp 1: 3
Hcp 2: 13
Hcp 1: 15
Hcp 2: 13
A sorted list of the holes on the course based on their difficulty
number of holes is: 2
Hole nr: 2. Par: 4. Difficulty order: 3
Hole nr: 1. Par: 5. Difficulty order: 13
I am expecting the following
GolfCourse
Hcp 1: 3
Hcp 2: 13
Hcp 1: 15
Hcp 2: 13
A sorted list of the holes on the course based on their difficulty
number of holes is:3
Hole nr: 2. Par: 4. Difficulty order: 3
Hole nr: 1. Par: 5. Difficulty order: 13
Hole nr: 1. Par: 5. Difficulty order: 15
Where is my mistake ?
Using jdk1.5.0_07, though I do not think that is where my problem is.
And running under the open source EJE IDE fetched from sourceforge
Hope that you can help me out here ....
or point me in the right direction.
regards, i

