Tuesday, July 5, 2011

Java : Comparable vs Comparator

Comparable

A comparable object is capable of comparing itself with another object. The class itself must implements the java.lang.Comparable interface in order to be able to compare its instances.

Comparator

A comparator object is capable of comparing two different objects. The class is not comparing its instances, but some other class’s instances. This comparator class must implement the java.util.Comparator interface.


With Comparable:
import java.util.Set;
import java.util.TreeSet;


public class Color implements Comparable {
      private String name = null;
     
      public Color(String name) {
            this.name = name;
      }

      public int compareTo(Color o) {
            return this.getName().compareTo(o.getName());
      }

      public String getName() {
            return name;
      }
     
      public String toString(){
            return "Color[" + this.name + "]";
      }
     
      public static void main(String[] args) {
            Set colors = new TreeSet();
            colors.add(new Color("Red"));
            colors.add(new Color("Orange"));
            colors.add(new Color("Yellow"));
            colors.add(new Color("Green"));
            colors.add(new Color("Blue"));
            colors.add(new Color("Indigo"));
            colors.add(new Color("Violet"));
            System.out.println(colors);
      }
}

Output:
[Color[Blue], Color[Green], Color[Indigo], Color[Orange], Color[Red], Color[Violet], Color[Yellow]]

With Comparator:
import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;


public class Color {
      private String name = null;
     
      public Color(String name) {
            this.name = name;
      }

      public String getName() {
            return name;
      }
     
      public String toString(){
            return "Color[" + this.name + "]";
      }
     
      public static void main(String[] args) {
            Comparator comp = new Comparator() {
                  public int compare(Color c1, Color c2) {                   
                        return c1.getName().compareTo(c2.getName());
                  }
            };
            Set colors = new TreeSet(comp);
            colors.add(new Color("Red"));
            colors.add(new Color("Orange"));
            colors.add(new Color("Yellow"));
            colors.add(new Color("Green"));
            colors.add(new Color("Blue"));
            colors.add(new Color("Indigo"));
            colors.add(new Color("Violet"));
            System.out.println(colors);
      }
}

Output:
[Color[Blue], Color[Green], Color[Indigo], Color[Orange], Color[Red], Color[Violet], Color[Yellow]]