Java Sorting: Comparator vs Comparable

本文深入讲解Java中的排序机制,包括Comparable和Comparator的概念及其应用。通过具体示例,演示如何使用这两种方式对对象进行排序,同时提供了按不同字段排序的实用技巧。

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类.

[java]  view plain copy
  1. public class Employee {  
  2.     private int empId;  
  3.     private String name;  
  4.     private int age;  
  5.     public Employee(int empId, String name, int age) {  
  6.         // set values on attributes  
  7.     }  
  8.     // getters & setters  
  9. }  
 




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.

[java]  view plain copy
  1. import java.util.*;  
  2. public class Util {  
  3.      
  4.     public static List<Employee> getEmployees() {  
  5.          
  6.         List<Employee> col = new ArrayList<Employee>();  
  7.          
  8.         col.add(new Employee(5"Frank"28));  
  9.         col.add(new Employee(1"Jorge"19));  
  10.         col.add(new Employee(6"Bill"34));  
  11.         col.add(new Employee(3"Michel"10));  
  12.         col.add(new Employee(7"Simpson"8));  
  13.         col.add(new Employee(4"Clerk",16 ));  
  14.         col.add(new Employee(8"Lee"40));  
  15.         col.add(new Employee(2"Mark"30));  
  16.          
  17.         return col;  
  18.     }  
  19. }  



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.

[java]  view plain copy
  1. public class Employee implements Comparable<Employee> {  
  2.     private int empId;  
  3.     private String name;  
  4.     private int age;  
  5.      
  6.     /** 
  7.      * Compare a given Employee with this object. 
  8.      * If employee id of this object is 
  9.      * greater than the received object, 
  10.      * then this object is greater than the other. 
  11.      */  
  12.     public int compareTo(Employee o) {  
  13.         return this.empId - o.empId ;  
  14.     }  
  15.    
  16. }  



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.

[java]  view plain copy
  1. import java.util.*;  
  2. public class TestEmployeeSort {  
  3.      
  4.     public static void main(String[] args) {      
  5.         List coll = Util.getEmployees();  
  6.         Collections.sort(coll); // sort method  
  7.         printList(coll);  
  8.     }  
  9.      
  10.     private static void printList(List<Employee> list) {  
  11.         System.out.println("EmpId/tName/tAge");  
  12.         for (Employee e: list) {  
  13.             System.out.println(e.getEmpId() + "/t" + e.getName() + "/t" + e.getAge());  
  14.         }  
  15.     }  
  16. }  



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.

[java]  view plain copy
  1. public class EmpSortByName implements Comparator<Employee>{  
  2.     public int compare(Employee o1, Employee o2) {  
  3.         return o1.getName().compareTo(o2.getName());  
  4.     }  
  5. }  


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.

[java]  view plain copy
  1. import java.util.*;  
  2. public class TestEmployeeSort {  
  3.      
  4.     public static void main(String[] args) {  
  5.          
  6.         List coll = Util.getEmployees();  
  7.         //Collections.sort(coll);  
  8.         //use Comparator implementation  
  9.         Collections.sort(coll, new EmpSortByName());  
  10.         printList(coll);  
  11.     }  
  12.      
  13.     private static void printList(List<Employee> list) {  
  14.         System.out.println("EmpId/tName/tAge");  
  15.         for (Employee e: list) {  
  16.             System.out.println(e.getEmpId() + "/t" + e.getName() + "/t" + e.getAge());  
  17.         }  
  18.     }  
  19. }   


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.

[java]  view plain copy
  1. public class EmpSortByEmpId implements Comparator<Employee>{  
  2.     public int compare(Employee o1, Employee o2) {  
  3.         return o1.getEmpId().compareTo(o2.getEmpId());  
  4.     }  
  5. }   


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.

出自:http://blog.youkuaiyun.com/russle/article/details/4430749

内容概要:本文系统介绍了算术优化算法(AOA)的基本原理、核心思想及Python实现方法,并通过图像分割的实际案例展示了其应用价值。AOA是一种基于种群的元启发式算法,其核心思想来源于四则运算,利用乘除运算进行全局勘探,加减运算进行局部开发,通过数学优化器加速函数(MOA)和数学优化概率(MOP)动态控制搜索过程,在全局探索与局部开发之间实现平衡。文章详细解析了算法的初始化、勘探与开发阶段的更新策略,并提供了完整的Python代码实现,结合Rastrigin函数进行测试验证。进一步地,以Flask框架搭建前后端分离系统,将AOA应用于图像分割任务,展示了其在实际工程中的可行性与高效性。最后,通过收敛速度、寻优精度等指标评估算法性能,并提出自适应参数调整、模型优化和并行计算等改进策略。; 适合人群:具备一定Python编程基础和优化算法基础知识的高校学生、科研人员及工程技术人员,尤其适合从事人工智能、图像处理、智能优化等领域的从业者;; 使用场景及目标:①理解元启发式算法的设计思想与实现机制;②掌握AOA在函数优化、图像分割等实际问题中的建模与求解方法;③学习如何将优化算法集成到Web系统中实现工程化应用;④为算法性能评估与改进提供实践参考; 阅读建议:建议读者结合代码逐行调试,深入理解算法流程中MOA与MOP的作用机制,尝试在不同测试函数上运行算法以观察性能差异,并可进一步扩展图像分割模块,引入更复杂的预处理或后处理技术以提升分割效果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值