标签:
第一种代码示例:
public class User implements Comparable<User> { private String name; private int age; private int orderNumber; public User(String name, int age, int orderNumber) { this.name = name; this.age = age; this.orderNumber = orderNumber; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getOrderNumber() { return orderNumber; } public void setOrderNumber(int orderNumber) { this.orderNumber = orderNumber; } @Override public int compareTo(User other) { if (this.getOrderNumber() == other.getOrderNumber()) { return this.getAge() - other.getAge(); } return this.getOrderNumber() - other.getOrderNumber(); } @Override public String toString() { return "User [name=" + name + ", age=" + age + ", orderNumber=" + orderNumber + "]"; } }
第二种代码示例:
public class Student { private String name; private int score; public Student(String name, int score) { super(); this.name = name; this.score = score; } @Override public String toString() { return "Student [name=" + name + ", score=" + score + "]"; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getScore() { return score; } public void setScore(int score) { this.score = score; } } public class StudentComparator implements Comparator<Student>{ @Override public int compare(Student s1, Student s2) { return s2.getScore() - s1.getScore(); } }
测试代码(第一种和第二种写在一起了):
public class TestTreeSet { public static void main(String[] args) { TreeSet<User> set = new TreeSet<>(); User user1 = new User("Tom", 25, 3); User user2 = new User("Jack", 28, 2); User user3 = new User("Mike", 20, 3); User user4 = new User("John", 30, 1); User user5 = new User("Jill", 50, 0); set.add(user1); set.add(user2); set.add(user3); set.add(user4); set.add(user5); System.out.println(set); Set<Student> studens = new TreeSet<>(new StudentComparator()); Student s1 = new Student("Tom", 80); Student s2 = new Student("Jack", 95); Student s3 = new Student("Mike", 60); Student s4 = new Student("John", 75); Student s5 = new Student("Jill", 100); studens.add(s1); studens.add(s2); studens.add(s3); studens.add(s4); studens.add(s5); System.out.println(studens); } }
标签:
原文地址:http://my.oschina.net/u/576554/blog/509019