实体类排序

    xiaoxiao2026-09-09  7

    实体类要实现排序,必须实现Comparable接口,并重写CompareTo()方法。

    实体类

    public class Person implements Comparable<Person>{ private String name; private Integer age; public Person() { super(); } public Person(String name, Integer age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } // 重点(按实际需求来排序) public int compareTo(Person person) { // 按age排序 if (this.age < person.getAge()) { return (this.age - person.getAge()); } if (this.age > person.getAge()) { return (this.age - person.getAge()); } // 按name排序 if (this.name.compareTo(person.getName()) > 0) { return -1; if (this.name.compareTo(person.getName()) < 0) { return 1; } return 0; } }

    测试类

    public class TestPerson { public static void main(String[] args) { Person p1 = new Person("张三", 25); Person p2 = new Person("李四", 15); Person p3 = new Person("王五", 32); Person p4 = new Person("赵六", 28); List<Person> list = new ArrayList<Person>(); list.add(p1); list.add(p2); list.add(p3); list.add(p4); // API的排序方法 Collections.sort(list); System.out.println(list.get(0).getAge()); System.out.println(list.get(0).getName()); } }

    运行结果

    转载请注明原文地址: https://ju.6miu.com/read-1311893.html
    最新回复(0)