Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Comparator Doubt

 
Abhi vijay
Ranch Hand
Posts: 509
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
import java.util.*;

class Dog
{
public String name;
Dog(String n)
{
name=n;
}
public String toString()
{
return name;
}
public String getname()
{
return name;
}

}

public class It
{
public static void main(String[] args)
{
ArrayList<Dog> d =new ArrayList<Dog>();
Dog dog=new Dog("Aiko");
R r1 =new R();
d.add(dog);
d.add(new Dog("Pooki"));
d.add(new Dog("Tommy"));
System.out.println(d);
Collections.sort(d,r);
System.out.println(d);

}
}

class R implements Comparator<Dog>
{
public int compare(Dog a, Dog b)
{
return b.getname().compareTo(a.getname());
}
}

In this program, what does the compare method return, how does it affect the
sort() method?
 
Abhinav Srivastava
Ranch Hand
Posts: 354
Eclipse IDE Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
compare(): Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.


When you implement you own comparison logic, you supply it to Collections.sort().
 
Abhi vijay
Ranch Hand
Posts: 509
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But here the output is: Tommy,Pooki,Aiko. Why are they arranged in the reverse order?
 
Campbell Ritchie
Sheriff
Posts: 48453
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Abhi vijay:
But here the output is: Tommy,Pooki,Aiko. Why are they arranged in the reverse order?


Because you wrote to put "b" before "a."
 
Campbell Ritchie
Sheriff
Posts: 48453
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And you have been here long enough that you ought to know about the code tags.
 
Abhinav Srivastava
Ranch Hand
Posts: 354
Eclipse IDE Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The compare method returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
You should verify if your compare() method is fulfilling that contract.
 
Campbell Ritchie
Sheriff
Posts: 48453
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is working, but it says a before b in the arguments and b before a in the body. So it will sort in descending order.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic