This week's book giveaway is in the OCMJEA forum.
We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Comparator Doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Comparator Doubt" Watch "Comparator Doubt" New topic
Author

Comparator Doubt

Abhi vijay
Ranch Hand

Joined: Sep 16, 2008
Posts: 509
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

Joined: Nov 19, 2002
Posts: 349

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

Joined: Sep 16, 2008
Posts: 509
But here the output is: Tommy,Pooki,Aiko. Why are they arranged in the reverse order?
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38517
    
  23
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

Joined: Oct 13, 2005
Posts: 38517
    
  23
And you have been here long enough that you ought to know about the code tags.
Abhinav Srivastava
Ranch Hand

Joined: Nov 19, 2002
Posts: 349

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

Joined: Oct 13, 2005
Posts: 38517
    
  23
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.
 
jQuery in Action, 2nd edition
 
subject: Comparator Doubt