This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan 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 Android Security Essentials Live Lessons this week in the Android 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: 38045
    
  22
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: 38045
    
  22
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: 38045
    
  22
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Comparator Doubt
 
Similar Threads
K&B chapter 7 question 15. Collections.
ArrayList.indexOf
ClassCastException when converting Object[] to DDog[]
Confusion in Generics
NoSuchMethod error ?