java TreeSet的使用
/*
?
TreeSet:它可以给Set集合中的元素进行指定方式的排序。
?? ??? ?保证元素唯一性的方式:通过比较的结果是否为0.
?? ??? ?底层数据结构是:二叉树。
*/
?
?
import java.util.*; class TreeSetDemo3 { public static void main(String[] args) { TreeSet ts = new TreeSet(new StudentComparatorByName()); ts.add(new Student("lisi0",30)); ts.add(new Student("lisixx",29)); ts.add(new Student("lisi9",29)); ts.add(new Student("lisi8",38)); ts.add(new Student("lisixx",29)); ts.add(new Student("lisi4",14)); //ts.add(new Student(39)); ts.add(new Student("lisi7",27)); System.out.println(ts); }} class StudentComparatorByName implements Comparator{ public int compare(Object o1,Object o2) { Student s1 = (Student)o1; Student s2 = (Student)o2; int num = s1.getName().compareTo(s2.getName()); return num==0?new Integer(s1.getAge()).compareTo(new Integer(s2.getAge())):num; }} //同姓名同年龄的学生视为同一个学生。按照学生的年龄排序。class Student implements Comparable{ private int age; private String name; Student(String name,int age) { this.age = age; this.name = name; } public int compareTo(Object obj) { Student stu = (Student)obj; int num = new Integer(this.age).compareTo(new Integer(stu.age)); return num==0?this.name.compareTo(stu.name):num; /* if(this.age>stu.age) return 1; if(this.age==stu.age) return this.name.compareTo(stu.name); return -1; */ /**/ } public int getAge() { return age; } public String getName() { return name; } public String toString() { return name+"::"+age; }} ?