COMPARABLE VS COMPARATOR

In this article, I will be explaining why java came up with COMPARATOR in the latest versions even though it already has a COMPARABLE interface

You can find small code snippets along the way for better understanding.

Let's dive into the article


  • Whenever we are designing the class, we will have some idea of what variables we need to store as part of this class

  • Similarly, if we also know how to sort that object then we will implement the Comparable interface and we will override the compareTo method 

  • In that compareTo method, we will be writing the sort logic whether it should return 1, -1, or 0, and based on that we will sort elements in the objects



class Movie implements Comparable<Movie>{
  private int id;
  private String name;
  private int rating;
  @Override
  public int compareTo(Movie o) {
      if(this.rating < o.rating) return -1;
      if(this.rating > o.rating) return 1;
      else return 0;
  }

class BoxOffice {
  public static void main(String[] args) {
      ArrayList<Movie> list = new ArrayList<Movie>();
      list.add(new Movie(1,"Home Alone", 9));
      list.add(new Movie(2,"HIT", 7));
      Collections.sort(list);
  }
}



  • In the future for some reason, if we want to sort the movie object based on the name, we can't achieve that because we can only have one compareTo method within the movie object 

  • In such cases to solve the problem we came up with the Comparator interface 

  • This interface has a compare method that can be written exclusively for that specific variable with which we want to sort 



class SortByMovieId implements Comparator<Movie> {
@Override
public int compare(Movie o1, Movie o2) {
return o1.getId() - o2.getId();
}
}

class BoxOffice {
  public static void main(String[] args) {
      ArrayList<Movie> list = new ArrayList<Movie>();
      list.add(new Movie(1,"Home Alone", 9));
      list.add(new Movie(2,"HIT", 7));
      SortByMovieId SBM = new SortByMovieId();

      Collections.sort(list, SBM);
  }
}




I hope the above code snippets helped you in understanding why comparator is brought into the picture, If you still have any doubts or suggestions, please comment below.


Comments

Popular posts from this blog

A complete guide to K-means clustering algorithm

What is Exploratory Data Analysis? | Part 1