Comparator Iterface

Comparator Iterface

By using comparator object we can define our own customized sorting. Comparator Interface is available in java.util package. This interface defines the following 2 methods.

1. public int compare(Object obj1, Object obj2)

returns

 –ve if obj1 has to come before obj2
 +ve if obj1 has to come after obj2
 0 if obj1 and obj2 are equal. 

2. public boolean equals(Object obj)

When ever we are implementing comparator interface compulsory we should provide implementation for compare method. Implementing equals method is optional because it is already available from object class through inheritance.

package com.ashok.collections;

import java.util.*;

/**
 * 
 * @author ashok.mariyala
 *
 */
public class MyTreeSet {
   public static void main(String arg[]) {
      TreeSet tset = new TreeSet(new MyComparator());
      tset.add(85);
      tset.add(12);
      tset.add(68);
      tset.add(45);
      tset.add(0);
      System.out.println(tset);
   }
}

class MyComparator implements Comparator {
   public int compare(Object obj1, Object obj2) {
      Integer i1 = (Integer) obj1;
      Integer i2 = (Integer) obj2;
      if (i1 < i2)
         return +1;
      else if (i1 > i2)
         return -1;
      else
         return 0;
   }
}

Output

[85, 68, 45, 12, 0]
Comparator Iterface

Scroll to top