首页 > 编程语言 >Comparable vs Comparator in Java

Comparable vs Comparator in Java

时间:2022-11-27 02:55:59浏览次数:71  
标签:sort Comparable Java Movie list vs year class

https://www.geeksforgeeks.org/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. 
 

  <iframe data-google-container-id="1" data-is-safeframe="true" data-load-complete="true" frameborder="0" height="250" id="google_ads_iframe_/27823234/GFG_Desktop_PostContent_336x280_0" marginheight="0" marginwidth="0" scrolling="no" src="https://4f5013a234ba0f99305f32211d15b794.safeframe.googlesyndication.com/safeframe/1-0-40/html/container.html" title="3rd party ad content" width="300"></iframe>  

 

  • Java
 
// 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 to sort movies by their rating and names as well. 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.

 

  • Java
 
//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.
  • A basic differentiating feature is that using comparable we can use only one comparison. Whereas, we can write more than one custom comparators as you want for a given type, all using different interpretations of what sorting means. Like in the comparable example we could just sort by only one attribute, i.e., year but in the comparator, we were able to use different attributes like rating, name, and year as well.

 

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

标签:sort,Comparable,Java,Movie,list,vs,year,class
From: https://www.cnblogs.com/kungfupanda/p/16928900.html

相关文章

  • equals() and hashCode() methods in Java
    https://www.geeksforgeeks.org/equals-hashcode-methods-java/ Java.lang.objecthastwoveryimportantmethodsdefined:publicbooleanequals(Objectobj)andp......
  • enum in Java
    https://www.geeksforgeeks.org/enum-in-java/Enumerationsservethepurposeofrepresentingagroupofnamedconstantsinaprogramminglanguage.Forexample,t......
  • Generics in Java
    https://www.geeksforgeeks.org/generics-in-java/ Generics means parameterizedtypes.Theideaistoallowtype(Integer,String,…etc.,anduser-defined......
  • java发送邮件
    一邮件协议收发邮件具有与HTTP协议相同的邮件传输协议.SMTP:(SimpleMailTransferProtocol,简单邮件传输协议)发邮件协议POP3:(PostOfficeProtocolVersion3,邮局协议第......
  • Java中YYYY-MM-dd在跨年时出现的bug
    先看一张图:Bug的产生原因:日期格式化时候,把yyyy-MM-dd写成了YYYY-MM-dd Bug分析:当时间是2019-08-31时,publicclassDateTest{publicstaticvoidmain(Strin......
  • java中乐观锁CAS的实现探究——AtomicInteger
    CASCAS——compareandswap,比较并交换。是一种乐观锁的实现方式。更新操作时,在每次更新之前,都先比较一下被更新的目标T,值是不是等于读取到的旧值O,如果相等,则认为在读取......
  • JAVA网络编程TCP实现聊天功能,附在IDEA中同时运行2个或以上相同的java程序
    在IDEA中同时运行2个或以上相同的java程序在日常编写测试代码时,有时候会需要在idea上同时运行两个及以上相同的java程序,如:想运行两个CLIENTLOGIN测试聊天室效果。1.点击E......
  • java9
    Java9新特性Java9发布于2017年9月22日,带来了很多新特性,其中最主要的变化是已经实现的模块化系统。接下来我们会详细介绍Java9的新特性。Java9新特性模块系......
  • 在vs2022中对于QT5的简单使用
    目录背景问题背景vs2022配置了QT5.14.2,然后尝试手写了一下qt程序,问题遇到的问题如下1.新建程序的时候,如果选择了类型为widget程序vs就默认启用qtcreator的接口,生成u......
  • 基于java+swing的图书管理系统
    功能展示登录管理员-主界面管理员-增加书籍管理员-更新和删除书籍管理员-查找书籍管理员-查找所有书籍管理员-添加用户管理员-更新和删除用户管理员-查找......