File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes compare method in comparator interface Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "compare method in comparator interface" Watch "compare method in comparator interface" New topic

compare method in comparator interface

sweety singh

Joined: Dec 04, 2006
Posts: 13
i just wanted to know what is the signature of compare(),if i have overriden this method for comparision of pet class object
format should be
1)public int compare(Object o1,Object o2)

pet p1=(pet)o1;
pet p2=(pet)o2;
return (;
2)public int compare(pet p1,pet p2)
return (;

in kathy sierra 2)format given
but when i tried to run 1) was teh correct one
What to do about such questions
Ahmed Khan Mohammed

Joined: Dec 07, 2006
Posts: 13
It depends on how you implement the Comparator interface, suppose you say
implements Comparator<Pet> then you must implement
public int compare(Pet p1, Pet p2)
and if you implement just Comparator without the <Pet> then
you must implement
public int compare(Object tc1, Object tc2)

Hope that helpl.
hemadri raju

Joined: Mar 28, 2006
Posts: 15
import java.util.*;
class Pet {
String name;
Pet(String name){;
public boolean equals(Object o){
return name.equals(((Pet)o).name);
public int hashCode(){
return name.length();
class myComp implements Comparator<Pet>{
public int compare(Pet p1, Pet p2){
return (((Pet)p2).name).compareTo(((Pet)p1).name);

class TestInts
public static void main(String[] args)

List<Pet> list=new ArrayList<Pet>();
list.add(new Pet("One"));
list.add(new Pet("Two"));
list.add(new Pet("Three"));
list.add(new Pet("Abc"));

myComp mp=new myComp();

for(Pet p:list)

hope the above code will help
I agree. Here's the link:
subject: compare method in comparator interface
It's not a secret anymore!