This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Implementing the java.util.Comparator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Implementing the java.util.Comparator" Watch "Implementing the java.util.Comparator" New topic

Implementing the java.util.Comparator

bapi dhar
Ranch Hand

Joined: Mar 02, 2001
Posts: 32
Dear friend
I could not sort the array by implementing the Comparator class
Please is in current dir.
import java.util.*;

class ClockComparator implements Comparator
public int compare(Object o1, Object o2) //-ve < then, 0 equal to, insertion sort +ve > than
if ((Clock)o1.getHours() > o2.getHours() ){ return 1;}
if (o2.getHours()> o2.getHours()){return -1;}
if (o1.getMinutes() > o2.getMinutes() ){ return 1;}
if (o2.getMinutes()> o2.getMinutes()){return -1;}
if (o1.getSeconds() > o2.getSeconds() ){ return 1;}
if (o2.getSeconds()> o2.getSeconds()){return -1;}
return 0;
public class Sort
static Clock clock[];
static Object temp;
public static void sort(Object[] c, ClockComparator cc)
for (int i=0;i<c.length;i++)>
for(int j=i+1;j<c.length;j++)>
if (([j],c[i]))<1)

public static void main(String args[])
if ( args.length !=1)
{ System.out.println("Please include number of Clock times in Command Line ... Thank You");
int nc=Integer.parseInt(args[0]);
clock =new Clock[nc];

for (int i=0;i<nc;i++)>
System.out.println("Enter Clock "+(i+1));

sort(clock,new ClockComparator());


private static Clock getTime(String timeType) {
Clock t;

while(true) {
System.out.print("Enter the " + timeType + " time in HH:MM:SS, 24-hr format: ");

try { t = Clock.valueOf(SavitchIn.readLine());
} catch (Throwable e) {
System.out.println("Problem, try again!");

System.out.println("The " + timeType + " time is " + t);
return t;

Mark Savory
Ranch Hand

Joined: Feb 08, 2001
Posts: 122
I see two problems:
1) In compare method, every reference to the o1 and o2 must be cast to Clock. You're only doing it once.
2) You should be using the static method: Arrays.sort(Object[], Comparator) method.
bapi dhar
Ranch Hand

Joined: Mar 02, 2001
Posts: 32
dear friend
John M. Gabriele
Ranch Hand

Joined: Feb 18, 2001
Posts: 232
when you post source code, it makes it much more readable to
place it within the CODE and /CODE delimiters. you've gotta
put []'s around the words CODE AND /CODE. see:
it makes text look like
ps. looks like you and i are both on the same page of van
der linden's "just java".
I agree. Here's the link:
subject: Implementing the java.util.Comparator
Similar Threads
BinarySearch Doubt
where is the bug?
Help me Debug the Code
sorting a Vector
Sorting two dimensional array