Hello Everyone,
I have a doubt related to sort sequences like how this sort(<list>,<comparator>
method is able to handle to display the result in ascending lexicographic order and then descending order after making a change in call to compareTo in terms of order of references to Objects.
like
public int compare(Object s1,Object s2)
{
return ((
String)s1).compareTo((String)s2);
}
results in increasing order while
return ((String)s2).compareTo((String)s1);
will result in decreasing order.
Even though the first as well as second gives a negative or positive or zero value ,then how it recognizes whether it has to be in increasing order or decreasing order.
I hope , i have made my doubt clear
Please Clarify it...i am not able to get it how it really works
import java.io.*;
import java.util.*;
public class Delete
{
public static void main(String...s)
{
ArrayList al = new ArrayList();
al.add("canada");
al.add("bhutan");
al.add("afghan");
System.out.println("Before sorting "+al);
Collections.sort(al);
System.out.println("After sorting and abt to sort using comparator "+al);
RevSort rs=new RevSort();
Collections.sort(al,rs);
System.out.println("After comparator creation "+al);
}
static class RevSort implements Comparator
{
public int compare(Object s1,Object s2)
{
return ((String)s2).compareTo((String)s1);
}
}
}
output is
*****************
Before sorting [canada, bhutan, afghan]
After sorting and abt to sort using comparator [afghan, bhutan, canada]
After comparator creation [canada, bhutan, afghan]