- 浏览: 387713 次
- 性别:
- 来自: 上海
文章分类
- 全部博客 (213)
- 面试题目 (9)
- 设计模式 (7)
- Core Java (28)
- 杂记 (10)
- 代码模板 (6)
- 数据库 (6)
- oracle plsql (2)
- strut2 study note (1)
- Oracle Database 10g SQL开发指南学习笔记 (7)
- Unix.Shell编程(第三版) 学习笔记 (1)
- Servlet (1)
- Hibernate (1)
- 敏捷开发 (1)
- Linux (13)
- Velocity (1)
- webx (1)
- Svn (2)
- 页面html,css (2)
- English (4)
- Astah usage (1)
- UML与设计思考 (2)
- JavaScript (3)
- 读书 (4)
- 好的网址 (1)
- 网址 (0)
- JMS (1)
- 持续集成环境 (1)
- 生活 (1)
- Spring (3)
- Tomcat Server (1)
- MySQL (2)
- 算法与数据结构 (6)
- Oracle数据库 (1)
- 分布式计算 (1)
- Maven (1)
- XML (2)
- Perl (2)
- 游戏 (1)
最新评论
-
chen_yi_ping:
请问楼主,怎么测试?String filePath = arg ...
使用多线程模拟多用户并发访问一个或多个tomcat,测试性能 -
adam_zs:
好,谢谢分享。
ArrayDeque实现Stack的功能 -
zjfgf:
int.class==Integer.class 返回fals ...
Class study -
kimmking:
xslt太难写的。
在java中调用xls格式化xml
Java Sorting: Comparator vs Comparable
Hello All …
hope everyone is in good health and enjoying the Allah Almighty’s blessings.
I was working on a task where i need to sort a collection (List) of objects on the basis of some attribute within single element of that list. Though i have used comparators many times in applications but today first time i wrote my first comparator and sort a list using Collection.sort(listName, comparatorClass). Sharing this knowledge with you people too.
What are Java Comparators and Comparables? 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.
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.
Comparator
A comparator object is capable of comparing two different objects. The class is not comparing its instances, but some other class’s instances. This comparator class must implement the java.util.Comparator interface.
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.
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.
Those are;
java.lang.Comparable: int compareTo(Object o1)
This method compares this object with o1 object. Returned int value has the following meanings.
1. positive – this object is greater than o1
2. zero – this object equals to o1
3. negative – this object is less than o1
java.util.Comparator: int compare(Object o1, Objecto2)
This method compares o1 and o2 objects. Returned int value has the following meanings.
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.util.Collections.sort(List, Comparator) and java.util.Arrays.sort(Object[], Comparator) methods can be used if a Comparator is available for comparison.
The above explained Employee example is a good candidate for explaining these two concepts. First we’ll write a simple Java bean to represent the Employee.
public class Employee {
private int empId;
private String name;
private int age;
public Employee(int empId, String name, int age) {
// set values on attributes
}
// getters & setters
}
Next we’ll 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.
import java.util.*;
public class Util {
public static List<Employee> getEmployees() {
List<Employee> col = new ArrayList<Employee>();
col.add(new Employee(5, "Frank", 28));
col.add(new Employee(1, "Jorge", 19));
col.add(new Employee(6, "Bill", 34));
col.add(new Employee(3, "Michel", 10));
col.add(new Employee(7, "Simpson",8));
col.add(new Employee(4, "Clerk",16 ));
col.add(new Employee(8, "Lee", 40));
col.add(new Employee(2, "Mark", 30));
return col;
}
}
Sorting in natural ordering
Employee’s 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.
public class Employee implements Comparable<Employee> {
private int empId;
private String name;
private int age;
/**
* Compare a given Employee with this object.
* If employee id of this object is
* greater than the received object,
* then this object is greater than the other.
*/
public int compareTo(Employee o) {
return this.empId - o.empId ;
}
….
}
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.
We’ll 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.
import java.util.*;
public class TestEmployeeSort {
public static void main(String[] args) {
List coll = Util.getEmployees();
Collections.sort(coll); // sort method
printList(coll);
}
private static void printList(List<Employee> list) {
System.out.println("EmpId\tName\tAge");
for (Employee e: list) {
System.out.println(e.getEmpId() + "\t" + e.getName() + "\t" + e.getAge());
}
}
}
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, we’ll have to change the Employee class’s compareTo() method to use those fields. But then we’ll 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.util.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.util.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.
public class EmpSortByName implements Comparator<Employee>{
public int compare(Employee o1, Employee o2) {
return o1.getName().compareTo(o2.getName());
}
}
Watch out: Here, String class’s 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.Watch out: Here, String class’s 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.
import java.util.*;
public class TestEmployeeSort {
public static void main(String[] args) {
List coll = Util.getEmployees();
//Collections.sort(coll);
//use Comparator implementation
Collections.sort(coll, new EmpSortByName());
printList(coll);
}
private static void printList(List<Employee> list) {
System.out.println("EmpId\tName\tAge");
for (Employee e: list) {
System.out.println(e.getEmpId() + "\t" + e.getName() + "\t" + e.getAge());
}
}
}
Now the result would be as follows. Check whether the employees are sorted correctly by the name String field. You’ll 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.
public class EmpSortByEmpId implements Comparator<Employee>{
public int compare(Employee o1, Employee o2) {
return o1.getEmpId().compareTo(o2.getEmpId());
}
}
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 we’ll get back to you.
转自:http://blog.csdn.net/russle/archive/2009/08/10/4430749.aspx
Hello All …
hope everyone is in good health and enjoying the Allah Almighty’s blessings.
I was working on a task where i need to sort a collection (List) of objects on the basis of some attribute within single element of that list. Though i have used comparators many times in applications but today first time i wrote my first comparator and sort a list using Collection.sort(listName, comparatorClass). Sharing this knowledge with you people too.
What are Java Comparators and Comparables? 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.
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.
Comparator
A comparator object is capable of comparing two different objects. The class is not comparing its instances, but some other class’s instances. This comparator class must implement the java.util.Comparator interface.
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.
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.
Those are;
java.lang.Comparable: int compareTo(Object o1)
This method compares this object with o1 object. Returned int value has the following meanings.
1. positive – this object is greater than o1
2. zero – this object equals to o1
3. negative – this object is less than o1
java.util.Comparator: int compare(Object o1, Objecto2)
This method compares o1 and o2 objects. Returned int value has the following meanings.
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.util.Collections.sort(List, Comparator) and java.util.Arrays.sort(Object[], Comparator) methods can be used if a Comparator is available for comparison.
The above explained Employee example is a good candidate for explaining these two concepts. First we’ll write a simple Java bean to represent the Employee.
public class Employee {
private int empId;
private String name;
private int age;
public Employee(int empId, String name, int age) {
// set values on attributes
}
// getters & setters
}
Next we’ll 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.
import java.util.*;
public class Util {
public static List<Employee> getEmployees() {
List<Employee> col = new ArrayList<Employee>();
col.add(new Employee(5, "Frank", 28));
col.add(new Employee(1, "Jorge", 19));
col.add(new Employee(6, "Bill", 34));
col.add(new Employee(3, "Michel", 10));
col.add(new Employee(7, "Simpson",8));
col.add(new Employee(4, "Clerk",16 ));
col.add(new Employee(8, "Lee", 40));
col.add(new Employee(2, "Mark", 30));
return col;
}
}
Sorting in natural ordering
Employee’s 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.
public class Employee implements Comparable<Employee> {
private int empId;
private String name;
private int age;
/**
* Compare a given Employee with this object.
* If employee id of this object is
* greater than the received object,
* then this object is greater than the other.
*/
public int compareTo(Employee o) {
return this.empId - o.empId ;
}
….
}
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.
We’ll 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.
import java.util.*;
public class TestEmployeeSort {
public static void main(String[] args) {
List coll = Util.getEmployees();
Collections.sort(coll); // sort method
printList(coll);
}
private static void printList(List<Employee> list) {
System.out.println("EmpId\tName\tAge");
for (Employee e: list) {
System.out.println(e.getEmpId() + "\t" + e.getName() + "\t" + e.getAge());
}
}
}
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, we’ll have to change the Employee class’s compareTo() method to use those fields. But then we’ll 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.util.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.util.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.
public class EmpSortByName implements Comparator<Employee>{
public int compare(Employee o1, Employee o2) {
return o1.getName().compareTo(o2.getName());
}
}
Watch out: Here, String class’s 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.Watch out: Here, String class’s 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.
import java.util.*;
public class TestEmployeeSort {
public static void main(String[] args) {
List coll = Util.getEmployees();
//Collections.sort(coll);
//use Comparator implementation
Collections.sort(coll, new EmpSortByName());
printList(coll);
}
private static void printList(List<Employee> list) {
System.out.println("EmpId\tName\tAge");
for (Employee e: list) {
System.out.println(e.getEmpId() + "\t" + e.getName() + "\t" + e.getAge());
}
}
}
Now the result would be as follows. Check whether the employees are sorted correctly by the name String field. You’ll 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.
public class EmpSortByEmpId implements Comparator<Employee>{
public int compare(Employee o1, Employee o2) {
return o1.getEmpId().compareTo(o2.getEmpId());
}
}
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 we’ll get back to you.
转自:http://blog.csdn.net/russle/archive/2009/08/10/4430749.aspx
发表评论
-
Log4j常用配置
2011-08-29 22:03 1681log4j.rootLogger=INFO, normal ... -
ArrayDeque实现Stack的功能
2011-08-17 15:58 7642在J2SE6引入了ArrayDeque类 ... -
Java的clone()方法,浅复制与深复制
2011-08-15 15:06 1405要想实现克隆,需要实 ... -
LinkedList源码分析
2011-08-10 15:18 1076http://blog.csdn.net/zhouyong0/ ... -
Java nio(文件读写 实例解析)
2011-08-09 18:07 4690http://blog.csdn.net/biexf/arti ... -
深入探讨 Java 类加载器
2011-08-08 15:23 777http://www.ibm.com/developerwor ... -
Java.nio 与Java.io的比较
2011-08-05 18:00 1496http://blogs.oracle.com/slc/ent ... -
java缓冲读写
2011-08-05 15:54 1105public static void main(String[ ... -
java多线程写入同一文件
2011-08-05 15:40 10040转自 :http://www.update8.com/Prog ... -
java线程及ComcurrentHashMap
2011-08-04 13:55 991http://blog.csdn.net/dimly113/a ... -
HashMap源码分析
2011-08-04 13:51 1823public class HashMap<K,V&g ... -
HashMap与HashTable的区别、HashMap与HashSet的关系
2011-08-04 10:44 3432转自http://blog.csdn.net/wl_ldy/a ... -
JVM内存模型及垃圾收集策略解析
2011-07-18 23:16 1325http://blog.csdn.net/dimly113/a ... -
Java关键字final、static使用总结
2011-06-03 12:47 9http://java.chinaitlab.com/base ... -
Java关键字final、static使用总结
2011-06-03 12:47 8一、final 根据程序上下文环境,Java关键字fina ... -
Java关键字final、static使用总结
2011-06-03 12:46 5一、final 根据程序上下文环境,Java关键字fina ... -
Java关键字final、static使用总结
2011-06-02 16:20 0转自:http://java.chinaitlab.com/b ... -
Java关键字final、static使用总结
2011-06-02 16:20 820转自:http://java.chinaitlab.com/b ... -
Java关键字final、static使用总结
2011-06-02 16:19 2转自:http://java.chinaitlab.com/b ... -
protected访问级别详解
2011-05-12 14:42 1682首先阅读:http://download.oracle.com ...
相关推荐
可以使用Java的`Collections.sort()`方法,但前提是要确保`Student`类实现了`Comparable`接口或者提供一个`Comparator`对象,定义如何比较GPA。 6. **方法设计**: - `addInfo`方法用于添加学生信息,`setInfo`...
尽管我们在课堂上讨论了Comparable和Comparator,但此处的排序算法仅需要对ListADT<Integer> ,就像提供的bubbleSort一样。没有提供签名。您将必须决定排序算法是修改列表(在BubbleSort中很容易)还是返回新列表...
在描述中提到的"Java sorting objects",通常涉及到`java.util.Comparator`接口或者重写对象的`compareTo`方法。在JDBC查询返回的结果集中,我们可能需要根据特定字段对对象进行排序。例如,如果我们有一个`Student`...
Lucene中的自定义排序功能和... SortComparatorSource接口的功能是返回一个用来排序ScoreDocs的comparator(Expert: returns a comparator for sorting ScoreDocs).该接口只定义了一个方法.如下: Java代码 /** * Crea
2. 自定义排序:通过实现Comparator接口或重写Comparable接口,可以自定义元素的比较规则,从而实现特定需求的排序。 3. 多线程排序:对于大数据量,可以考虑使用多线程进行并行排序,如Fork/Join框架下的...
此外,当涉及到对象排序时,需要定义比较规则,比如重写`Comparable`接口或提供`Comparator`。比较不同类型的对象时,必须确保比较规则的一致性和正确性。 最后,通过比较这三种简单的排序算法,我们可以发现它们在...
在Java编程语言中,堆排序可以通过实现Comparable接口或者Comparator类来完成。堆排序的时间复杂度为O(n log n),空间复杂度为O(1),是原地排序算法的一种。 堆排序的基本思想分为两个阶段: 1. **构建最大(最小...
对于自定义的类,需要实现Comparable接口或提供Comparator来确定元素的顺序。 在“sorting-and-tree-algorithm-example-master”这个压缩包中,我们可以期待找到用Java实现的排序算法和树算法的代码示例。这些示例...
对于对象数组,`Arrays.sort()`会调用元素类型的`Comparable`接口或自定义的`Comparator`来决定排序顺序。 1. `Arrays.sort(int[] a)`:对整型数组进行升序排序。 2. `Arrays.sort(double[] a)`:对浮点型数组进行...
对于自定义对象的排序,可以重写`Comparable`接口或者提供一个`Comparator`对象。 此外,搜索和排序也是算法竞赛和面试中常见的主题。理解并掌握这些基本算法对于提升编程技能和解决实际问题至关重要。例如,二分...
对于自定义排序逻辑,可以实现`Comparable`接口或提供`Comparator`对象。 4. **并发与多线程**:如果文件过大,可能需要多线程处理以提高效率。Java的`ExecutorService`和`Future`接口可以用来管理和控制并发任务。...