zoukankan      html  css  js  c++  java
  • 使用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
  • 相关阅读:
    javascript概述
    linux系统编程(一)概述
    软件工程
    SQL
    数据结构和算法(一)概述
    cpp标准库
    c语言标准库
    c/c++概述
    编程语言的思考
    GCD学习
  • 原文地址:https://www.cnblogs.com/helloworld2019/p/10628824.html
Copyright © 2011-2022 走看看