有关于TreeSet的自我理解

TreeSet是依靠TreeMap来实现的。


TreeSet是一个有序集合,TreeSet中的元素将按照升序排列,缺省是按照自然排序进行排列,意味着TreeSet中的元素要实现Comparable接口

或者有一个自定义的比较器。我们可以在构造TreeSet对象时,传递实现Comparator接口的比较器对象。

举例:

 1 public class TreeSetTest {
 2     public static void main(String[] args) {
 3         Set ts = new TreeSet();
 4         ts.add("abc");
 5         ts.add("xyz");
 6         ts.add("rst");
 7         Iterator it = ts.iterator();
 8         while (it.hasNext()) {
 9             System.out.println(it.next());
10         }
11     }
12 }

运行结果: abc rst xyz

结果不是和先前加入的顺序一样,它是按照一个字母的排序法进行排序的。这是因为String 类实现了Comparable接口。

如果我们自己定义的一个类的对象要加入到TreeSet当中,那么这个类必须要实现Comparable接口。

 1 public class TreeSetTest {
 2     public static void main(String[] args) {
 3         Set ts = new TreeSet();
 4         ts.add(new Teacher("zhangsan", 1));
 5         ts.add(new Teacher("lisi", 2));
 6         ts.add(new Teacher("wangmazi", 3));
 7         ts.add(new Teacher("mazi", 3));
 8         Iterator it = ts.iterator();
 9         while (it.hasNext()) {
10             System.out.println(it.next());
11         }
12     }
13 }
14 
15 
16 class Teacher implements Comparable {
17     int num;
18     String name;
19 
20     Teacher(String name, int num) {
21         this.num = num;
22         this.name = name;
23     }
24 
25     public String toString() {
26         return "学好" + num + "姓名" + name;
27     }
28 
29     public int compareTo(Object o) {
30         Teacher ss = (Teacher) o;
31         int result = num > ss.num ? 1 : (num == ss.num ? 0 : -1);
32         if (result == 0) {
33             result = name.compareTo(ss.name);
34         }
35         return result;
36     }
37 }

运行结果:学号1姓名zhangsan

     学号2姓名lisi

       学号3姓名wangmazi

     学号3姓名mazi

如果将int result = num > ss.num ? 1 : (num == ss.num ? 0 : -1);写成了int result = ss.num > num ? 1 : (ss.num == num ? 0 : -1);那么得到的结果就是倒序排列的,并不是升序的。
 
原文地址:https://www.cnblogs.com/ay-nzz/p/by_xzz.html