Classic object-oriented application using an interface custom sort Comparable (Java programming classical case)

By default, the array stored in the List collection is not sorted, but you can use a custom collation Comparable interface and automatically sorted.

Step 1 : Create a Java class that implements the interface definition Comparable the compareTo () method, the objects are arranged in ascending order by number.

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();
    }
}

Step 2 : Test

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

public class TestEmployee {
    public static void main(String[] args) {
        List<Employee> list=new ArrayList<Employee>();
        list.add(new Employee(3,"zhangsan",21));
        list.add(new Employee(2,"lisi",22));
        list.add(new Employee(1,"wangwu",23));
        System.out.println("排序前:");
        for (Employee employee : list) {
            System.out.println(employee);
        }
        System.out.println("排序后:");
        //如果保存到数组中,可以用Arrays.sort()方法进行自动排序
        Collections.sort(list);				//执行自动排序
        for (Employee employee : list) {
            System.out.println(employee);
        }
    }
}

Execution results as shown below:
Here Insert Picture Description

Guess you like

Origin blog.csdn.net/cui_yonghua/article/details/93602882