List 简单排序

来源:互联网 发布:ios开发用什么数据库 编辑:程序博客网 时间:2024/06/03 04:28

1.Comparable接口用于在类的设计中使用;

  • Comparable接口用于在类的设计中使用;
    现有一个需要排序的类User, 去实现 Comparable接口, 按照类中的某个数值类型正序或者倒序
public class User implements Comparable<User>{    private String id;    private String name;    private int age;    public User() {    }    public User(String id, String name, int age) {        this.id = id;        this.name = name;        this.age = age;    }    //get()...set()//这种方式使用User类实现了Comparable接口,实现了compareTo方法,具体的排序规则就在这个方法中重写    @Override    public int compareTo(User u) {        //return u.getAge() - this.getAge();//倒序        return Integer.valueOf(this.getAge()).compareTo(u.getAge());//正序        //return this.getAge() - u.getAge();//正序    }}

测试类1

    List<User> users = new ArrayList<>();        for (int i = 0; i < 10; i++) {            users.add(createUser(i + "号"));        }        //这种方式使用User类实现了Comparable接口,实现了compareTo方法,具体的排序规则就在这个方法中重写        Collections.sort(users);        for (User user : users) {            System.out.println("name:" + user.getName() + "---age:" + user.getAge());        }

2.Comparator接口用于类设计已经完成,还想排序(Arrays);

  • User2类是一个没有实现Comparable的类
//没有实现Comparablepublic class User2 {    private String id;    private String name;    private int age;    public User2() {    }    public User2(String id, String name, int age) {        this.id = id;        this.name = name;        this.age = age;    }        //get()...set()

测试类2

List<User2> users2 = new ArrayList<>();        for (int i = 0; i < 10; i++) {            users2.add(createUser2(i + "号"));        }        //使用Comparator接口的compare来完成比较器,排序方法写在这里        Collections.sort(users2, new Comparator<User2>() {            @Override            public int compare(User2 o1, User2 o2) {                //1为正序,-1为倒序                return o1.getAge() > o2.getAge() ? 1 : -1;            }        });        for (User2 user2 : users2) {            System.out.println("name:" + user2.getName() + "---age:" + user2.getAge());        }

也可以再写个User2Comparator类实现Comparator
这样写法就是为
Collections.sort(users2, new User2Comparator())