jQuery in Action, 3rd edition
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


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: 352

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: 43945
    
  33
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: 43945
    
  33
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: 352

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: 43945
    
  33
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.
 
Have you checked out Aspose?
 
subject: Comparator Doubt
 
It's not a secret anymore!