博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
转:Comparable vs Comparator in Java
阅读量:6570 次
发布时间:2019-06-24

本文共 6582 字,大约阅读时间需要 21 分钟。

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());
        
}
    
}
}

Copy CodeRun on IDE

Output:

Movies after sorting : Star Wars 8.7 1977Empire Strikes Back 8.8 1980Return of the Jedi 8.4 1983Force 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 

 

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()+
" "
);
    
}
}  

Copy CodeRun on IDE

Output :

Sorted by rating8.3 Force Awakens 20158.4 Return of the Jedi 19838.7 Star Wars 19778.8 Empire Strikes Back 1980Sorted by nameEmpire Strikes Back 8.8 1980Force Awakens 8.3 2015Return of the Jedi 8.4 1983Star Wars 8.7 1977Sorted by year1977 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/

 

转载于:https://www.cnblogs.com/andychhr/p/9896943.html

你可能感兴趣的文章
SQL Server 合并复制遇到identity range check报错的解决
查看>>
深入理解C# 静态类与非静态类、静态成员的区别
查看>>
精灵菜单
查看>>
【Leetcode】Path Sum II
查看>>
设计模式 总揽 通过这篇随笔可以访问所需要了解的设计模式
查看>>
Photoshop和WPF双剑配合,打造炫酷个性的进度条控件
查看>>
2014最不受欢迎10编程语言种
查看>>
LVM逻辑卷管理@设备、格式、摩、引导自己主动安装一个完整的章节
查看>>
iOS 开发笔记-加载/初始化
查看>>
(转)SqlServer基础之(触发器)(清晰易懂)
查看>>
lintcode :Count and Say 报数
查看>>
浅谈矩阵分解在推荐系统中的应用
查看>>
视频编解码器,bbv 缓冲区溢出和下溢
查看>>
一些小知识
查看>>
android 71 ArrayAdapter和SimpleAdapter
查看>>
android:#FFFFFFFF 颜色码解析
查看>>
POJ 2151 Check the difficulty of problems (动态规划-可能DP)
查看>>
jQuery-1.9.1源码分析系列(十) 事件系统——事件包装
查看>>
谢惠民,恽自求,易法槐,钱定边编数学分析习题课讲义习题参考解答
查看>>
禅道 Rest API 开发
查看>>