欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

转:Comparable vs Comparator in Java

程序员文章站 2023-08-26 08:36:07
Comparable vs Comparator in Java Java provides two interfaces to sort objects using data members of the class: Comparable Comparator Using Comparable ......

comparable vs comparator in java

 

java provides two interfaces to sort objects using data members of the class:

  1. comparable
  2. comparator

using comparable interface

a comparable object is capable of comparing itself with another object. the class itself must implements the java.lang.comparable interface to compare its instances.

consider a movie class that has members like, rating, name, year. suppose we wish to sort a list of movies based on year of release. we can implement the comparable interface with the movie class, and we override the method compareto() of comparable interface.



// a java program to demonstrate use of comparable
import java.io.*;
import java.util.*;
  
// a class 'movie' that implements comparable
class movie implements comparable<movie>
{
    private double rating;
    private string name;
    private int year;
  
    // used to sort movies by year
    public int compareto(movie m)
    {
        return this.year - m.year;
    }
  
    // constructor
    public movie(string nm, double rt, int yr)
    {
        this.name = nm;
        this.rating = rt;
        this.year = yr;
    }
  
    // getter methods for accessing private data
    public double getrating() { return rating; }
    public string getname()   {  return name; }
    public int getyear()      {  return year;  }
}
  
// driver class
class main
{
    public static void main(string[] args)
    {
        arraylist<movie> list = new arraylist<movie>();
        list.add(new movie("force awakens", 8.3, 2015));
        list.add(new movie("star wars", 8.7, 1977));
        list.add(new movie("empire strikes back", 8.8, 1980));
        list.add(new movie("return of the jedi", 8.4, 1983));
  
        collections.sort(list);
  
        system.out.println("movies after sorting : ");
        for (movie movie: list)
        {
            system.out.println(movie.getname() + " " +
                               movie.getrating() + " " +
                               movie.getyear());
        }
    }
}

output:

movies after sorting : 
star wars 8.7 1977
empire strikes back 8.8 1980
return of the jedi 8.4 1983
force awakens 8.3 2015

now, suppose we want sort movies by their rating and names also. when we make a collection element comparable(by having it implement comparable), we get only one chance to implement the compareto() method. the solution is using comparator.

 

using comparator

unlike comparable, comparator is external to the element type we are comparing. it’s a separate class. we create multiple separate classes (that implement comparator) to compare by different members.

collections class has a second sort() method and it takes comparator. the sort() method invokes the compare() to sort objects.

to compare movies by rating, we need to do 3 things :

  1. create a class that implements comparator (and thus the compare() method that does the work previously done by compareto()).
  2. make an instance of the comparator class.
  3. call the overloaded sort() method, giving it both the list and the instance of the class that implements comparator.
//a java program to demonstrate comparator interface
import java.io.*;
import java.util.*;
  
// a class 'movie' that implements comparable
class movie implements comparable<movie>
{
    private double rating;
    private string name;
    private int year;
  
    // used to sort movies by year
    public int compareto(movie m)
    {
        return this.year - m.year;
    }
  
    // constructor
    public movie(string nm, double rt, int yr)
    {
        this.name = nm;
        this.rating = rt;
        this.year = yr;
    }
  
    // getter methods for accessing private data
    public double getrating() { return rating; }
    public string getname()   {  return name; }
    public int getyear()      {  return year;  }
}
  
// class to compare movies by ratings
class ratingcompare implements comparator<movie>
{
    public int compare(movie m1, movie m2)
    {
        if (m1.getrating() < m2.getrating()) return -1;
        if (m1.getrating() > m2.getrating()) return 1;
        else return 0;
    }
}
  
// class to compare movies by name
class namecompare implements comparator<movie>
{
    public int compare(movie m1, movie m2)
    {
        return m1.getname().compareto(m2.getname());
    }
}
  
// driver class
class main
{
    public static void main(string[] args)
    {
        arraylist<movie> list = new arraylist<movie>();
        list.add(new movie("force awakens", 8.3, 2015));
        list.add(new movie("star wars", 8.7, 1977));
        list.add(new movie("empire strikes back", 8.8, 1980));
        list.add(new movie("return of the jedi", 8.4, 1983));
  
        // sort by rating : (1) create an object of ratingcompare
        //                  (2) call collections.sort
        //                  (3) print sorted list
        system.out.println("sorted by rating");
        ratingcompare ratingcompare = new ratingcompare();
        collections.sort(list, ratingcompare);
        for (movie movie: list)
            system.out.println(movie.getrating() + " " +
                               movie.getname() + " " +
                               movie.getyear());
  
  
        // call overloaded sort method with ratingcompare
        // (same three steps as above)
        system.out.println("\nsorted by name");
        namecompare namecompare = new namecompare();
        collections.sort(list, namecompare);
        for (movie movie: list)
            system.out.println(movie.getname() + " " +
                               movie.getrating() + " " +
                               movie.getyear());
  
        // uses comparable to sort by year
        system.out.println("\nsorted by year");
        collections.sort(list);
        for (movie movie: list)
            system.out.println(movie.getyear() + " " +
                               movie.getrating() + " " +
                               movie.getname()+" ");
    }
}  

output :

sorted by rating
8.3 force awakens 2015
8.4 return of the jedi 1983
8.7 star wars 1977
8.8 empire strikes back 1980

sorted by name
empire strikes back 8.8 1980
force awakens 8.3 2015
return of the jedi 8.4 1983
star wars 8.7 1977

sorted by year
1977 8.7 star wars 
1980 8.8 empire strikes back 
1983 8.4 return of the jedi 
2015 8.3 force awakens  
  • comparable is meant for objects with natural ordering which means the object itself must know how it is to be ordered. for example roll numbers of students. whereas, comparator interface sorting is done through a separate class.
  • logically, comparable interface compares “this” reference with the object specified and comparator in java compares two different class objects provided.
  • if any class implements comparable interface in java then collection of that object either list or array can be sorted automatically by using collections.sort() or arrays.sort() method and objects will be sorted based on there natural order defined by compareto method.

 

to summarize, if sorting of objects needs to be based on natural order then use comparable whereas if you sorting needs to be done on attributes of different objects, then use comparator in java.


 

this article is contributed by souradeep barua. please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

 

reference:

https://www.geeksforgeeks.org/comparable-vs-comparator-in-java/