aspose file tools*
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
Author

compare method in comparator interface

sweety singh
Greenhorn

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 (p1.name).compareTo(p2.name);
}
or
2)public int compare(pet p1,pet p2)
{
return (p1.name).compareTo(p2.name);
}

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
Greenhorn

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
Greenhorn

Joined: Mar 28, 2006
Posts: 15
import java.util.*;
class Pet {
String name;
Pet(String name){
this.name=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();
Collections.sort(list,mp);

for(Pet p:list)
System.out.println("::"+p.name);


}
}
hope the above code will help
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: compare method in comparator interface