Wednesday, 27 June 2012

Tips & Trick of Java Comparator


When compartor return 1, swap happen and for -1 swap not happen.

What happen when it return 0?

Based on the collection we use, its action change

If we use List, its not changing the order and if its a Set it eliminates the record.

public class Test {

   public static void main(String[] args) throws Exception {

      Comparator c = new Comparator<String>() {
         @Override
         public int compare(String first, String second) {
            return 0;
         }
      };

      Set<String> comp = new TreeSet<String>(c);

      comp.add("A");
      comp.add("C");
      comp.add("B");

      System.out.println("Comp : " + comp);
   }
}

Result
   Comp : [A]