2. 为了使用不同的排序标准做准备,比如:升序、降序或其他什么序。
下面通过两个例子分别用Comparable和Comparator实现对User对象中年龄排序。
1.通过实现Comparable接口,根据User的年龄进行排序。
import java.util.Arrays; /** * @author Young * */ public class User implements Comparable<User> { private String id; private int age; public User(String id, int age) { this.id = id; this.age = age; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getId() { return id; } public void setId(String id) { this.id = id; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; User other = (User) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } @Override public String toString() { return "User [id=" + id + ", age=" + age + "]"; } @Override public int compareTo(User o) { return this.age - ((User) o).getAge(); } /** * 测试方法 */ public static void main(String[] args) { User[] users = new User[] { new User("100", 25), new User("101", 20), new User("102", 21) }; Arrays.sort(users); for (User user : users) { System.out.println(user.getId() + " " + user.getAge()); } } }2. 通过实现Comparator接口,根据User的年龄进行排序。
/** * @author Young * */ public class User{ private String id; private int age; public User(String id, int age) { this.id = id; this.age = age; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getId() { return id; } public void setId(String id) { this.id = id; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; User other = (User) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } @Override public String toString() { return "User [id=" + id + ", age=" + age + "]"; } }
import java.util.Arrays; import java.util.Comparator; /** * @author Young * */ public class UserComparator implements Comparator<User> { @Override public int compare(User o1, User o2) { return ((User) o1).getAge() - ((User) o2).getAge(); } /** * 测试方法 */ public static void main(String[] args) { User[] users = new User[] { new User("100", 25), new User("101", 20), new User("102", 21) }; Arrays.sort(users,UserComparator); for (User user:users) { System.out.println(user.getId() + " " + user.getAge()); } } }