java sort using anonymous class

Osman Khalid picture Osman Khalid · May 20, 2012 · Viewed 59.7k times · Source

I have class in which I am sorting a list.

import java.util.*;

public class First 
{

    private static HashMap<String,Second> msgs;

    public static void main(String[] args) 
    {           

    List<String> ls=new ArrayList<String>();


   ls.add("fourth");
   ls.add("2");
   ls.add("second");
   ls.add("first");
   ls.add("third");
   ls.add("1");

   Iterator it=ls.iterator();

   // before sorting
   while(it.hasNext())
   {
     String s=(String)it.next();
     System.out.println(s);
   }

   Collections.sort(ls, new Comparator(){
       public int compare(Object o1, Object o2) {
           return -1;
           // it can also return 0, and 1
        }
    });

System.out.println(" ");

//after sorting
   Iterator iti=ls.iterator();
   while(iti.hasNext())
   {
     String s=(String)iti.next();

     System.out.println(s);
   }

}


}

After the program is run, I get these values:

1    
third
first
second
2
fourth

My question is what is the behavior of Collection.sort() function here. On returning -1 from compare function, we get the reverse order of the list. Then how can we get other sorting orders? What is the role of returning 0, and 1?

Answer

Osman Khalid picture Osman Khalid · May 20, 2012

Finally, I modified the sort function in this manner to get sorted data.

 Collections.sort(ls, new Comparator() 
                           {

                            public int compare(Object o1, Object o2) 
                            {
                            String sa = (String)o1;
                            String sb = (String)o2;

                            int v = sa.compareTo(sb);

                            return v;           

                                // it can also return 0, and 1
                            }
                           }    
                    );