• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Rob Spoor
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Henry Wong
  • Liutauras Vilda
  • Jeanne Boyarsky
Saloon Keepers:
  • Jesse Silverman
  • Tim Holloway
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Mikalai Zaikin
  • Piet Souris

compare method in comparator interface

 
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
You showed up just in time for the waffles! And this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic