Java对象排序有两种方法
一,在对象类中实现接口 comparable
package com.m01.collections; public class User implements Comparable { private int id; private String name; private double score; public User() { super(); } public User(int id, String name, double score) { super(); this.id = id; this.name = name; this.score = score; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getScore() { return score; } public void setScore(double score) { this.score = score; } @Override public int compareTo(Object o) { User user=(User) o; if(this.score>user.score){ return 1; } else if(this.score<user.score){ return -1; }else{ if(this.id>user.id){ return 1; } else if(this.id<user.id){ return -1; }else{ return 0; } } } @Override public String toString() { return "User [id=" + id + ", name=" + name + ", score=" + score + "]"; } }
List<User> list=new ArrayList(); list.add(new User(1, "夏末", 12)); list.add(new User(2, "夏末2", 12)); list.add(new User(2, "夏末", 13)); list.add(new User(4, "夏末", 12)); list.add(new User(0, "夏末", 12)); Collections.sort(list); for(User user : list){ System.out.println(user); }
二,编写比较器 实现comparator,对象类不需要实现comparable接口
List<Person> listp=new ArrayList(); listp.add(new Person(1, "夏末", 1)); listp.add(new Person(3, "夏末", 102)); listp.add(new Person(2, "夏末", 120)); listp.add(new Person(4, "夏末", 2)); listp.add(new Person(0, "夏末", 0)); Collections.sort(listp,new Comparator<Person>() { @Override public int compare(Person o1, Person o2) { if(o1.getScore()>o2.getScore()){ return 1; }else if(o1.getScore()<o2.getScore()){ return -1; }else{ return 0; } } }); for(Person user:listp){ System.out.println(user.toString()); }