使用Comparable接口自定义排序

Employee;

package textq;
/**
 * 调用接口Comparable排序
 * @author Administrator
 *
 */
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 return -1;
}
@Override
public String toString(){
    StringBuilder sb=new StringBuilder();
    sb.append("员工编号"+id+",");
    sb.append("员工的名字"+name+",");
    sb.append("员工的年龄"+age);
    return sb.toString();
}
}
View Code

Test:

package textq;

import java.util.ArrayList;
import java.util.Collections;
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);
    for(Employee employee:list){
        System.out.println(employee);
    }
}
}
View Code
原文地址:https://www.cnblogs.com/helloworld2019/p/10628824.html