一、前言

有时我们需要对类按照类中的某一个属性(或者多个属性)来对类的对象进行排序,有两种方法可以实现,一种方法是类实现Comparable<T>接口,然后调用Collections.sort(List)方法进行排序,另一种方法是类不实现Comparable<T>接口,而在排序时使用Collections.sort(List, Comparator<T>)方法,并实现其中的Comparator<T>接口。

二、排序实现

假设有一个学生类Student,包含两个属性:姓名name,年龄age,如下:

public class Student {

    private String name;

    private int age;

    public Student() {}

    public Student(String name, int age) {
this.name = name;
this.age = age;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
}
}

1、通过类实现Comparable<T>接口进行排序

public class Student implements Comparable<Student>{

    private String name;

    private int age;

    public Student() {}

    public Student(String name, int age) {
this.name = name;
this.age = age;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} /**
* 将对象按姓名字典序升序排序
* @param o
* @return
*/
@Override
public int compareTo(Student o) {
return this.name.compareTo(o.getName());
} @Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}

在客户端中测试

import java.util.ArrayList;
import java.util.Collections;
import java.util.List; public class Client { public static void main(String[] args){
List<Student> students = new ArrayList<>();
students.add(new Student("a", 18));
students.add(new Student("c", 19));
students.add(new Student("b", 20)); Collections.sort(students);
for(Student student:students){
System.out.println(student.toString());
}
} }

结果:

Student{name='a', age=18}
Student{name='b', age=20}
Student{name='c', age=19}

可以看到,学生按姓名的字典序升序排序。使用这用方法排序不能使用基本类型(int, float)等,而要使用包装后的类型如Integer,String等,要使用基本类型,可以使用下面的方法。

2、通过在Collections.sort()方法中实现Comparable<T>接口来实现排序

/**
* 没有实现Comparable<T>接口的学生类
*/
public class Student{ private String name; private int age; public Student() {} public Student(String name, int age) {
this.name = name;
this.age = age;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} @Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}

在客户端进行测试:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List; public class Client { public static void main(String[] args){
List<Student> students = new ArrayList<>();
students.add(new Student("a", 18));
students.add(new Student("c", 19));
students.add(new Student("b", 20)); Collections.sort(students, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.getAge()>o2.getAge()? -1:(o1.getAge()==o2.getAge()? 0:1);
}
});
for(Student student:students){
System.out.println(student.toString());
}
} }

结果:

Student{name='b', age=20}
Student{name='c', age=19}
Student{name='a', age=18}

可以看到学生按年龄从大到小排序输出。使用这种方法时要注意在比较函数compare的返回值中要包含0(年龄相等),不然可能会出现Comparison method violates its general contract!异常。

三、总结

无论使用上面的哪一种方法,对对象排序的核心是实现比较函数,其中第二种方法比第一种方法更加灵活。

java对对象排序的更多相关文章

  1. [个人原创]关于java中对象排序的一些探讨(三)

    这篇文章由十八子将原创,转载请注明,并标明博客地址:http://www.cnblogs.com/shibazijiang/ 对对象排序也可以使用Guava中的Ordering类. 构造Orderin ...

  2. java 通用对象排序

    一个排序类,一个排序util? no.no.no…… 使用反射机制,写了一个通用的对象排序util,欢迎指正. 实体类: package entity; public class BaseTypeEn ...

  3. [个人原创]关于java中对象排序的一些探讨(一)

    有的时候我们需要将自己定义的对象,有序输出.因为一般我们程序的中间结果需要存储在容器里,那么怎样对容器中的对象按照一定次序输出就是程序员经常需要考虑的问题.本片文章探讨了怎样有序化输出容器中的对象的问 ...

  4. JAVA list对象排序加去重问题

    对象类实现继承Comparable接口重写compareTo方法实现排序功能,重写equals方法实现去重功能(根据ID去重)public class TestAbilityAnalyze imple ...

  5. [个人原创]关于java中对象排序的一些探讨(二)

    2.  使用Collections.sort()方法 Collections类中提供了诸多静态方法,诸如addAll(),max()等等.当自己相对Collection接口下的类处理的时候,可以看看这 ...

  6. Java对象排序

    java实现对象比较,可以实现java.lang.Comparable或java.util.Comparator接口 //Product.java import java.util.Date; //p ...

  7. Java - 简单的对象排序 - Comparator

    注:对象排序,就是对对象中的某一字段进行比较,以正序或倒序进行排序. 例: 需要排序的对象: public class Person { public int age; public String n ...

  8. Java集合中对象排序

    集合中的对象排序需求还是比較常见的.当然我们能够重写equals方法,循环比較:同一时候Java为我们提供了更易使用的APIs.当须要排序的集合或数组不是单纯的数字型时,通常能够使用Comparato ...

  9. List对象排序的通用方法

    转自 @author chenchuang import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Me ...

随机推荐

  1. bootstrap-switch

    首先需要引入bootstrap的css和js文件,再引入bootstrap-switch.css和bootstrap-switch.js文件 <script type="text/ja ...

  2. SQL语句(十八)—— 存储过程

    存储过程 系统存储过程 自定义存储过程 扩展存储过程 一.创建存储过程 创建存储过程 --例1 USE SU GO Create Procedure SelProc AS Select * From ...

  3. A Gentle Guide to Machine Learning

    A Gentle Guide to Machine Learning Machine Learning is a subfield within Artificial Intelligence tha ...

  4. python笔记之psutil模块

    收集教程 http://www.cnblogs.com/xiao1/p/6164204.html 实战教程 安装psutil模块 pip2 install psutil 实战代码 #encoding= ...

  5. 可视化爬虫Portia安装和部署踩过的坑

    背景 Scrapy爬虫的确是好使好用,去过scrapinghub的官网浏览一下,更是赞叹可视化爬虫的犀利.scrapinghub有一系列的产品,开源了大部分项目,Portia负责可视化爬虫的编辑,Sp ...

  6. js工作常见问题收集

    1. viewport <meta name="viewport" content="width=device-width,initial-scale=1.0,mi ...

  7. spfa+floyed+最长路+差分约束系统(F - XYZZY POJ - 1932)(题目起这么长感觉有点慌--)

    题目链接:https://cn.vjudge.net/contest/276233#problem/F 题目大意:给你n个房子能到达的地方,然后每进入一个房子,会消耗一定的生命值(有可能是负),问你一 ...

  8. A - ACM Computer Factory(网络流)

    题目链接:https://cn.vjudge.net/contest/68128#problem/A 反思:注意拆点,否则的话节点就没用了,还有注意源点和汇点的赋值. AC代码: #include&l ...

  9. JS日期与字符串相互转换!!

    一 日期转字符串 dateToString: function(date){ var year = date.getFullYear(); var month =(date.getMonth() + ...

  10. int、long、long long取值范围

    unsigned   int   0-4294967295 int   -2147483648-2147483647 unsigned long 0-4294967295 long   -214748 ...