MENU

Java Comparable 接口自定义排序

April 19, 2019 • 默认分类阅读设置

Employee.java

package demo063;

public class Employee implements Comparable<Employee> {
    private int id;
    private String name;
    private int age;

    public Employee(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    @Override
    public int compareTo(Employee o) {
        if (id > o.id) {
            return 1;
        } else if (id < o.id) {
            return -1;
        }
        return 0;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("员工的编号: " + id + ", ");
        sb.append("员工的姓名: " + name + ", ");
        sb.append("员工的年龄: " + age);
        return sb.toString();
    }
}

Test.java

package demo063;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Test {
    public static void main(String[] args) {
        List<Employee> list = new ArrayList<Employee>();
        list.add(new Employee(3,"Java",21));
        list.add(new Employee(2,"Java",22));
        list.add(new Employee(1,"Java",23));
        System.out.println("排序前: ");
        for(Employee employee : list){
            System.out.println(employee);
        }
        System.out.println("排序后: ");
        //Collections.sort(list);
        list.sort(null);
        for(Employee employee : list){
            System.out.println(employee);
        }
    }
}

运行结果

排序前: 
员工的编号: 3, 员工的姓名: Java, 员工的年龄: 21
员工的编号: 2, 员工的姓名: Java, 员工的年龄: 22
员工的编号: 1, 员工的姓名: Java, 员工的年龄: 23
排序后: 
员工的编号: 1, 员工的姓名: Java, 员工的年龄: 23
员工的编号: 2, 员工的姓名: Java, 员工的年龄: 22
员工的编号: 3, 员工的姓名: Java, 员工的年龄: 21
Archives QR Code Tip
QR Code for this page
Tipping QR Code