File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

compare method in comparator interface

 
sweety singh
Greenhorn
Posts: 13
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 13
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 15
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic