当前位置: 代码迷 >> 综合 >> Java Sorting: Comparator vs Comparable
  详细解决方案

Java Sorting: Comparator vs Comparable

热度:68   发布时间:2024-01-05 09:41:33.0

     Java Comparators and Comparables? What are they? How do we use them? This is a question we received from one of our readers. This article will discuss the java.lang.Comparator and java.lang.Comparable in details with a set of sample codes for further clarifications.
     Java中 comparator 和comparable是什么?怎么使用它们?这是许多读者经常问到的问题。这篇文章详细讨论了java.lang.Comparator和java.lang.Comparable,并且使用例子做了进一步说明



What are Java Comparators and Comparables?  Java中 comparator 和comparable是什么?
     As both names suggest (and you may have guessed), these are used for comparing objects in Java. Using these concepts; Java objects can be sorted according to a predefined order.
    从两者的名字可以猜出,它们是用来比较对象的。使用它们,一句之前定义的顺序就可以对java对象进行排序了。

Two of these concepts can be explained as follows.两者的概念解释如下:
Comparable
    A comparable object is capable of comparing itself with another object. The class itself must implements the java.lang.Comparable interface in order to be able to compare its instances.
     一个comparable对象能够将自身和其他对象进行比较。这个类本省必须实现java.lang.Comparable接口,以便比较它们的实例。
Comparator
     A comparator object is capable of comparing two different objects. The class is not comparing its instances, but some other classs instances. This comparator class must implement the java.lang.Comparator interface.
     一个comparator对象能够比较两个不同的对象。这个类不是比较它们的实例,而是比较其他类的实例。comparator类必须红丝线java.lang.Comparator接口。
Do we need to compare objects? 我们需要比较对象吗?
     The simplest answer is yes. When there is a list of objects, ordering these objects into different orders becomes a must in some situations. For example; think of displaying a list of employee objects in a web page. Generally employees may be displayed by sorting them using the employee id. Also there will be requirements to sort them according to the name or age as well. In these situations both these (above defined) concepts will become handy.
     最简单的答案是yes。当有一组对象时,以不同的排序标准对这些对象进行排序在一些情况下市必须的。例如,在网页中显示一些员工的信息。一般而言,可以使用员工号进行排序显示。有时也需要根据他们的名字或者部分进行排序。以上这些情况中,有排序就会变的很容易。
How to use these? 如何使用它们?
     There are two interfaces in Java to support these concepts, and each of these has one method to be implemented by user.
      Java中有两种接口支持这些概念,每一个都有要被用户实现的方法
java.lang.Comparable: int compareTo(Object o1)
    This method compares this object with o1 object. Returned int value has the following meanings.
    这个方法将自身和01对象比较。返回值的含义如下。
   1. positive  this object is greater than o1,自身大于01
   2. zero  this object equals to o1       自身等于01
   3. negative  this object is less thano1   自身小于o1


java.lang.Comparator: int compare(Object o1, Objecto2)
     This method compares o1 and o2 objects. Returned int value has the following meanings.
    这个方法比较o1和o2对象,返回值含义与上面相同
   1. positive  o1 is greater than o2
   2. zero  o1 equals to o2
   3. negative  o1 is less than o1


     java.util.Collections.sort(List) and java.util.Arrays.sort(Object[]) methods can be used to sort using natural ordering of objects.
     Java中java.util.Collections.sort(List) 和 java.util.Arrays.sort(Object[])方法使用对象的自然比较进行排序
     java.util.Collections.sort(List, Comparator) and java.util.Arrays.sort(Object[], Comparator) methods can be used if a Comparator is available for comparison.
    java.util.Collections.sort(List, Comparator) 和java.util.Arrays.sort(Object[], Comparator) 使用比较类comparator对对象进行比较
    The above explained Employee example is a good candidate for explaining these two concepts. First well write a simple Java bean to represent the Employee.
     上面提到的员工例子可以很好的解释这两个概念。首先是一个简单的Employee类.  




Next well create a list of Employees for using in different sorting requirements. Employees are added to a List without any specific order in the following class.




Sorting in natural ordering
Employees natural ordering would be done according to the employee id. For that, above Employee class must be altered to add the comparing ability as follows.




The new compareTo() method does the trick of implementing the natural ordering of the instances. So if a collection of Employee objects is sorted using Collections.sort(List) method; sorting happens according to the ordering done inside this method.

Well write a class to test this natural ordering mechanism. Following class use the Collections.sort(List) method to sort the given list in natural order.




Run the above class and examine the output. It will be as follows. As you can see, the list is sorted correctly using the employee id. As empId is an int value, the employee instances are ordered so that the int values ordered from 1 to 8.

EmpId Name Age
1 Jorge 19
2 Mark 30
3 Michel 10
4 Clerk 16
5 Frank 28
6 Bill 34
7 Simp 8
8 Lee 40


Sorting by other fields
If we need to sort using other fields of the employee, well have to change the Employee classs compareTo() method to use those fields. But then well loose this empId based sorting mechanism. This is not a good alternative if we need to sort using different fields at different occasions. But no need to worry; Comparator is there to save us.

By writing a class that implements the java.lang.Comparator interface, you can sort Employees using any field as you wish even without touching the Employee class itself; Employee class does not need to implement java.lang.Comparable or java.lang.Comparator interface.
Sorting by name field
Following EmpSortByName class is used to sort Employee instances according to the name field. In this class, inside the compare() method sorting mechanism is implemented. In compare() method we get two Employee instances and we have to return which object is greater.



Watch out: Here, String classs compareTo() method is used in comparing the name fields (which are Strings).

Now to test this sorting mechanism, you must use the Collections.sort(List, Comparator) method instead of Collections.sort(List) method. Now change the TestEmployeeSort class as follows. See how the EmpSortByName comparator is used inside sort method.



Now the result would be as follows. Check whether the employees are sorted correctly by the name String field. Youll see that these are sorted alphabetically.

EmpId Name Age
6 Bill 34
4 Clerk 16
5 Frank 28
1 Jorge 19
8 Lee 40
2 Mark 30
3 Michel 10
7 Simp 8

Sorting by empId field
Even the ordering by empId (previously done using Comparable) can be implemented using Comparator; following class does that.



Explore further
Do not stop here. Work on the followings by yourselves and sharpen knowledge on these concepts.

   1. Sort employees using name, age, empId in this order (ie: when names are equal, try age and then next empId)
   2. Explore how & why equals() method and compare()/compareTo() methods must be consistence.


If you have any issues on these concepts; please add those in the comments section and well get back to you.

  相关解决方案