很难想象有Java开发人员不曾使用过Collection框架。在Collection框架中,主要使用的类是来自List接口中的ArrayList,以及来自Set接口的HashSet、TreeSet,我们经常处理这些Collections的排序。

在本文中,我将主要关注排序Collection的ArrayList、HashSet、TreeSet,以及最后但并非最不重要的数组。

让我们看看如何对给定的整数集合(5,10,0,-1)进行排序:

数据(整数)存储在ArrayList中

private void sortNumbersInArrayList() {
List<Integer> integers = new ArrayList<>();
integers.add(5);
integers.add(10);
integers.add(0);
integers.add(-1);
System.out.println("Original list: " +integers);
Collections.sort(integers);
System.out.println("Sorted list: "+integers);
Collections.sort(integers, Collections.reverseOrder());
System.out.println("Reversed List: " +integers);
}

输出:

Original list: [5, 10, 0, -1]
Sorted list: [-1, 0, 5, 10]
Reversed List: [10, 5, 0, -1]

数据(整数)存储在HashSet中

private void sortNumbersInHashSet() {
Set<Integer> integers = new HashSet<>();
integers.add(5);
integers.add(10);
integers.add(0);
integers.add(-1);
System.out.println("Original set: " +integers); // Collections.sort(integers); This throws error since sort method accepts list not collection
List list = new ArrayList(integers);
Collections.sort(list);
System.out.println("Sorted set: "+list);
Collections.sort(list, Collections.reverseOrder());
System.out.println("Reversed set: " +list);
}

输出:

Original set: [0, -1, 5, 10]Sorted set: [-1, 0, 5, 10]Reversed set: [10, 5, 0, -1]

在这个例子中(数据(整数)存储在HashSet中),我们看到HashSet被转换为ArrayList进行排序。在不转换为ArrayList的情况下,可以通过使用TreeSet来实现排序。TreeSet是Set的另一个实现,并且在使用默认构造函数创建Set时,使用自然排序进行排序。

数据(整数)存储在TreeSet中

private void sortNumbersInTreeSet() {
Set<Integer> integers = new TreeSet<>();
integers.add(5);
integers.add(10);
integers.add(0);
integers.add(-1);
System.out.println("Original set: " + integers);
System.out.println("Sorted set: "+ integers);
Set<Integer> reversedIntegers = new TreeSet(Collections.reverseOrder());
reversedIntegers.add(5);
reversedIntegers.add(10);
reversedIntegers.add(0);
reversedIntegers.add(-1);
System.out.println("Reversed set: " + reversedIntegers);
}

输出:

Original set: [-1, 0, 5, 10]Sorted set: [-1, 0, 5, 10]Reversed set: [10, 5, 0, -1]

在这种情况下,“Original set:”和“Sorted set:”两者相同,因为我们已经使用了按排序顺序存储数据的TreeSet,所以在插入后不用排序。

到目前为止,一切都如期工作,排序似乎是一件轻而易举的事。现在让我们尝试在各个Collection中存储自定义对象(比如Student),并查看排序是如何工作的。

数据(Student对象)存储在ArrayList中

private void sortStudentInArrayList() {
List<Student> students = new ArrayList<>();
Student student1 = createStudent("Biplab", 3);
students.add(student1);
Student student2 = createStudent("John", 1);
students.add(student2);
Student student3 = createStudent("Pal", 5);
students.add(student3);
Student student4 = createStudent("Biplab", 2);
students.add(student4);
System.out.println("Original students list: " + students);
Collections.sort(students);// Error here
System.out.println("Sorted students list: " + students);
Collections.sort(students, Collections.reverseOrder());
System.out.println("Reversed students list: " + students);
}private Student createStudent(String name, int no) {
Student student = new Student();
student.setName(name);
student.setNo(no); return student;
}public class Student {
String name; int no; public String getName() { return name;
} public int getNo() { return no;
} public void setName(String name) { this.name = name;
} public void setNo(int no) { this.no = no;
}
@Override    public String toString() { return "Student{" + "name='" + name + '\'' + ", no=" + no + '}';
}
}

这会抛出编译时错误,并显示以下错误消息:

sort(java.util.List<T>)in Collections cannot be appliedto (java.util.List<com.example.demo.dto.Student>)reason: no instance(s) of type variable(s) T exist so that Student conforms to Comparable<? Super T>

为了解决这个问题,要么Student类需要实现Comparable,要么需要在调用Collections.sort时传递Comparator对象。在整型情况下,排序方法没有错误,因为Integer类实现了Comparable。让我们看看,实现Comparable或传递Comparator如何解决这个问题,以及排序方法如何实现Collection排序。

使用Comparable排序

package com.example.demo.dto;public class Student implements Comparable{
String name; int no; public String getName() { return name;
} public int getNo() { return no;
} public void setName(String name) { this.name = name;
} public void setNo(int no) { this.no = no;
} @Override
public String toString() { return "Student{" + "name='" + name + '\'' + ", no=" + no + '}';
} @Override
public int compareTo(Object o) { return this.getName().compareTo(((Student) o).getName());
}
}

输出:

Original students list: [Student{name='Biplab', no=3}, Student{name='John', no=1}, Student{name='Pal', no=5}, Student{name='Biplab', no=2}]
Sorted students list: [Student{name='Biplab', no=3}, Student{name='Biplab', no=2}, Student{name='John', no=1}, Student{name='Pal', no=5}]
Reversed students list: [Student{name='Pal', no=5}, Student{name='John', no=1}, Student{name='Biplab', no=3}, Student{name='Biplab', no=2}]

在所有示例中,为了颠倒顺序,我们使用“Collections.sort(students, Collections.reverseOrder()”,相反的,它可以通过改变compareTo(..)方法的实现而达成目标,且compareTo(…) 的实现看起来像这样 :

@Override
public int compareTo(Object o) { return (((Student) o).getName()).compareTo(this.getName());
}

输出:

Original students list: [Student{name='Biplab', no=3}, Student{name='John', no=1}, Student{name='Pal', no=5}, Student{name='Biplab', no=2}]
Sorted students list: [Student{name='Pal', no=5}, Student{name='John', no=1}, Student{name='Biplab', no=3}, Student{name='Biplab', no=2}]
Reversed students list: [Student{name='Biplab', no=3}, Student{name='Biplab', no=2}, Student{name='John', no=1}, Student{name='Pal', no=5}]

如果我们观察输出结果,我们可以看到“Sorted students list:”以颠倒的顺序(按学生name)输出学生信息。

到目前为止,对学生的排序是根据学生的“name”而非“no”来完成的。如果我们想按“no”排序,我们只需要更改Student类的compareTo(Object o)实现,如下所示:

 @Override
public int compareTo(Object o) { return (this.getNo() < ((Student) o).getNo() ? -1 : (this.getNo() == ((Student) o).getNo() ? 0 : 1));
}

输出:

Original students list: [Student{name='Biplab', no=3}, Student{name='John', no=1}, Student{name='Pal', no=5}, Student{name='Biplab', no=2}]
Sorted students list: [Student{name='John', no=1}, Student{name='Biplab', no=2}, Student{name='Biplab', no=3}, Student{name='Pal', no=5}]
Reversed students list: [Student{name='Pal', no=5}, Student{name='Biplab', no=3}, Student{name='Biplab', no=2}, Student{name='John', no=1}]

在上面的输出中,我们可以看到“no”2和3的两名学生具有相同的名字“Biplab”。

现在假设我们首先需要按“name”对这些学生进行排序,如果超过1名学生具有相同姓名的话,则这些学生需要按“no”排序。为了实现这一点,我们需要改变compareTo(…)方法的实现,如下所示:

@Override
public int compareTo(Object o) { int result = this.getName().compareTo(((Student) o).getName()); if(result == 0) {
result = (this.getNo() < ((Student) o).getNo() ? -1 : (this.getNo() == ((Student) o).getNo() ? 0 : 1));
} return result;
}

输出:

Original students list: [Student{name='Biplab', no=3}, Student{name='John', no=1}, Student{name='Pal', no=5}, Student{name='Biplab', no=2}]
Sorted students list: [Student{name='Biplab', no=2}, Student{name='Biplab', no=3}, Student{name='John', no=1}, Student{name='Pal', no=5}]
Reversed students list: [Student{name='Pal', no=5}, Student{name='John', no=1}, Student{name='Biplab', no=3}, Student{name='Biplab', no=2}]

使用Comparator排序

为了按照“name”对Students进行排序,我们将添加一个Comparator并将其传递给排序方法:

public class Sorting { private void sortStudentInArrayList() {
List<Student> students = new ArrayList<>();
Student student1 = createStudent("Biplab", 3);
students.add(student1);
Student student2 = createStudent("John", 1);
students.add(student2);
Student student3 = createStudent("Pal", 5);
students.add(student3);
Student student4 = createStudent("Biplab", 2);
students.add(student4);
System.out.println("Original students list: " + students);
Collections.sort(integers, new NameComparator());
System.out.println("Sorted students list: " + students);
}
}public class Student {
String name; int no; public String getName() { return name;
} public int getNo() { return no;
} public void setName(String name) { this.name = name;
} public void setNo(int no) { this.no = no;
} @Override
public String toString() { return "Student{" + "name='" + name + '\'' + ", no=" + no + '}';
}
}class NameComparator implements Comparator<Student> { @Override
public int compare(Student o1, Student o2) { return o1.getName().compareTo(o2.getName());
}
}

输出:

Original students list: [Student{name='Biplab', no=3}, Student{name='John', no=1}, Student{name='Pal', no=5}, Student{name='Biplab', no=2}]
Sorted students list: [Student{name='Biplab', no=3}, Student{name='Biplab', no=2}, Student{name='John', no=1}, Student{name='Pal', no=5}]

同样,如果我们想按照“no”对Students排序,那么可以再添加一个Comparator(NoComparator.java),并将其传递给排序方法,然后数据将按“no”排序。

现在,如果我们想通过“name”然后“no”对学生进行排序,那么可以在compare(…)内结合两种逻辑来实现。

class NameNoComparator implements Comparator<Student> {    @Override
public int compare(Student o1, Student o2) { int result = o1.getName().compareTo(o2.getName()); if(result == 0) {
result = o1.getNo() < o2.getNo() ? -1 : o1.getNo() == o2.getNo() ? 0 : 1;
} return result;
}
}

输出:

Original students list: [Student{name='Biplab', no=3}, Student{name='John', no=1}, Student{name='Pal', no=5}, Student{name='Biplab', no=2}]
Sorted students list: [Student{name='Biplab', no=2}, Student{name='Biplab', no=3}, Student{name='John', no=1}, Student{name='Pal', no=5}]

数据(Students对象)存储在Set中

在Set的这个情况下,我们需要将HashSet转换为ArrayList,或使用TreeSet对数据进行排序。此外,我们知道要使Set工作,equals(…)和hashCode()方法需要被覆盖。下面是基于“no”字段覆盖equals和hashcode的例子,且这些是IDE自动生成的代码。与Comparable或Comparator相关的其他代码与ArrayList相同。

@Override
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o; return no == student.no;
} @Override
public int hashCode() { return Objects.hash(no);
}

数据(Students对象)存储在数组中

为了对数组排序,我们需要做与排序ArrayList相同的事情(要么执行Comparable要么传递Comparable给sort方法)。在这种情况下,sort方法是“Arrays.sort(Object[] a )”而非“Collections.sort(..)”。

private void sortStudentInArray() {
Student [] students = new Student[4];
Student student1 = createStudent("Biplab", 3);
students[0] = student1;
Student student2 = createStudent("John", 1);
students[1] = student2;
Student student3 = createStudent("Pal", 5);
students[2] = student3;
Student student4 = createStudent("Biplab", 2);
students[3] = student4;
System.out.print("Original students list: "); for (Student student: students) {
System.out.print( student + " ,");
}
Arrays.sort(students);
System.out.print("\nSorted students list: "); for (Student student: students) {
System.out.print( student +" ,");
}
Arrays.sort(students, Collections.reverseOrder());
System.out.print("\nReversed students list: " ); for (Student student: students) {
System.out.print( student +" ,");
}
}//Student class// All properties goes here
@Override   public int compareTo(Object o) { int result =this.getName().compareTo(((Student)o).getName()); if(result ==0) {
result = (this.getNo() < ((Student) o).getNo() ? -1 : (this.getNo() == ((Student) o).getNo() ? 0 : 1));
} return result;
}

输出:

Original students list: Student{name='Biplab', no=3} ,Student{name='John', no=1} ,Student{name='Pal', no=5} ,Student{name='Biplab', no=2} ,
Sorted students list: Student{name='Biplab', no=2} ,Student{name='Biplab', no=3} ,Student{name='John', no=1} ,Student{name='Pal', no=5} ,
Reversed students list: Student{name='Pal', no=5} ,Student{name='John', no=1} ,Student{name='Biplab', no=3} ,Student{name='Biplab', no=2} ,

结论

我们经常对Comparable/Comparator的使用以及何时使用哪个感到困惑。下面是我总结的Comparable/Comparator的使用场景。

Comparator:

  • 当我们想排序一个无法修改的类的实例时。例如来自jar的类的实例。

  • 根据用例需要排序不同的字段时,例如,一个用例需要通过“name”排序,还有个想要根据“no”排序,或者有的用例需要通过“name和no”来排序。

Comparable:

应该在定义类时知道排序的顺序时使用,并且不会有其他任何需要使用Collection /数组来根据其他字段排序的情况。

注意:我没有介绍Set / List的细节。我假设读者已经了解了这些内容。此外,没有提供使用Set / array进行排序的详细示例,因为实现与ArrayList非常相似,而ArrayList我已经详细给出了示例。

Java 对象排序详解的更多相关文章

  1. JAVA对象头详解(含32位虚拟机与64位虚拟机)

    为什么要学习Java对象头 学习Java对象头主要是为了解synchronized底层原理,synchronized锁升级过程,Java并发编程等. JAVA对象头 由于Java面向对象的思想,在JV ...

  2. Java对象初始化详解

    在Java中,一个对象在可以被使用之前必须要被正确地初始化,这一点是Java规范规定的.本文试图对Java如何执行对象的初始化做一个详细深入地介绍(与对象初始化相同,类在被加载之后也是需要初始化的,本 ...

  3. Java对象初始化详解(转)

    在Java中,一个对象在可以被使用之前必须要被正确地初始化,这一点是Java规范规定的.本文试图对Java如何执行对象的初始化做一个详细深入地介绍(与对象初始化相同,类在被加载之后也是需要初始化的,本 ...

  4. 2018.6.15 Java对象序列化详解

    一.定义 Serializable 序列化:把Java对象转换为字节序列的过程. 反序列化:把字节序列恢复为Java对象的过程. ObjectOutputStream对象输出流 可以将实现了Seria ...

  5. Java对象序列化详解

    深入理解Java对象序列化 1. 什么是Java对象序列化 Java平台允许我们在内存中创建可复用的Java对象,但一般情况下,只有当JVM处于运行时,这些对象才可能存在,即,这些对象的生命周期不会比 ...

  6. 【转】Java对象初始化详解

    来源:MySun 链接:http://mysun.iteye.com/blog/1596959 在Java中,一个对象在可以被使用之前必须要被正确地初始化,这一点是Java规范规定的.本文试图对Jav ...

  7. Java对象克隆详解

    原文:http://www.cnblogs.com/Qian123/p/5710533.html 假如说你想复制一个简单变量.很简单: int apples = 5; int pears = appl ...

  8. js数组对象排序详解

    一.js对象遍历输出的时候真的是按照顺序输出吗? 下边就来实践一下: var obj={'3':'ccc',name:'abc',age:23,school:'sdfds',class:'dfd',h ...

  9. java选择排序详解

    排序算法--选择排序 public class Selector implements ISortAble{ @Override public void sort(int[] a) { int n=a ...

随机推荐

  1. Linux内核策略介绍学习笔记

    主要内容 硬件 策略 CPU 进程调度.系统调用.中断 内存 内存管理 外存 文件IO 网络 协议栈 其他 时间管理 进程调度 内核的运行时间 系统启动.中断发生.系统调用以及内核线程. 进程和线程的 ...

  2. java-实用的sql语句

    一.在数据库创建表格的SQL语句 1,创建一个link表格,包含属性:lid  主键,title 标题,  imgpath 图片地址 , url  网址  , info 说明,  isshow 显示1 ...

  3. Java模块化开发

    包配置, 静态资源, 视图解析器, 数据库,

  4. 【bzoj2938】[Poi2000]病毒 AC自动机

    题目描述 二进制病毒审查委员会最近发现了如下的规律:某些确定的二进制串是病毒的代码.如果某段代码中不存在任何一段病毒代码,那么我们就称这段代码是安全的.现在委员会已经找出了所有的病毒代码段,试问,是否 ...

  5. BZOJ4565 HAOI2016字符合并(区间dp+状压dp)

    设f[i][j][k]为将i~j的字符最终合并成k的答案.转移时只考虑最后一个字符是由哪段后缀合成的.如果最后合成为一个字符特殊转移一下. 复杂度看起来是O(n32k),实际常数极小达到O(玄学). ...

  6. hdu 2768 Cat vs. Dog (二分匹配)

    Cat vs. Dog Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total ...

  7. POJ2104:K-th Number——题解

    http://poj.org/problem?id=2104 题目大意:求区间第k小. —————————————————————————— 主席树板子题. ……我看了半天现在还是一知半解的状态所以应 ...

  8. Spring多个数据源问题:DataSourceAutoConfiguration required a single bean, but * were found

    原因: @EnableAutoConfiguration 这个注解会把配置文件号中的数据源全部都自动注入,不会默认注入一个,当使用其他数据源时再调用另外的数据源. 解决方法: 1.注释掉这个注解 2. ...

  9. 关于Mybatis的@Param注解 及 mybatis Mapper中各种传递参数的方法

    原文:https://blog.csdn.net/mrqiang9001/article/details/79520436 关于Mybatis的@Param注解   Mybatis 作为一个轻量级的数 ...

  10. 图片上传(方法一:jquery.upload.js)

    一.在JSP页面引入jquery.upload.js 文件: <script type="text/javascript" src="${ctx}/script/j ...