1

I need to understand the differences between comparable and comparator with proper examples. I have seen several books but the difference is not clear to me.

Rantu
  • 21
  • 1
  • 1
  • 2

2 Answers2

5

Comparable interface: Class whose objects to be sorted must implement this interface.In this,we have to implement compareTo(Object) method.

For example:

  public class State implements Comparable{
    @Override
    public int compareTo(Object arg0) {
        State state=(State) arg0;
        return (this.stateId < state.stateId ) ? -1: (this.stateId >  state.stateId ) ? 1:0 ;
}}

If any class implements comparable inteface then collection of that object can be sorted automatically using Collection.sort() or Arrays.sort().Object will be sort on the basis of compareTo method in that class.

Objects which implement Comparable in java can be used as keys in a SortedMap like TreeMap or SortedSet like TreeSet without implementing any other interface.

Comparator interface: Class whose objects to be sorted do not need to implement this interface.Some third class can implement this interface to sort.e.g.StateSortByIdComparator class can implement Comparator interface to sort collection of state object by id. For example:

 public class StateSortByIdComparator implements Comparator<State>{

    @Override
    public int compare(State state1, State state2) {

        return (state1.getStateId() < state2.getStateId() ) ? -1: (state1.getStateId() > state2.getStateId() ) ? 1:0 ;
    }

 }
0

Comparable defines that instances of a class have a natural ordering, e.g. numbers which can be ordered small to big. In other cases this defines the default ordering, e.g. when using strings.

A Comparator on the other hand is an object that might define a non-standard ordering, i.e. you could provide a comparator to sort numbers from big to small for example.

Thomas
  • 87,414
  • 12
  • 119
  • 157