使用元素的天然顺序对元素进行排序,或者根据建立set时提供的Comparator进行排序。java
底层数据结构是红黑树(红黑树是一种自平衡的二叉树,特色是左大右小)数据结构
有关红黑树的知识,戳:红黑树, 或者:最容易懂的红黑树ide
咱们在HashSet里写过一个Person,那咱们直接拿来存到TreeSet里吧:this
import java.util.TreeSet; public class Test { public static void main(String[] args) { TreeSet<Person> set = new TreeSet<>(); set.add(new Person(1, "辣条")); set.add(new Person(3, "冰棍")); set.add(new Person(4, "面包")); set.add(new Person(2, "薯片")); set.add(new Person(2, "薯片")); set.add(new Person(2, "薯片")); for (Person person : set) { System.out.println(person); } } } class Person { public int id; public String name; public Person(int id, String name) { this.id = id; this.name = name; } @Override public String toString() { return "Person [id=" + id + ", name=" + name + "]"; } }
运行以后报了一个错。。。spa
注意!!!.net
TreeSet存储的类型必须实现Comparable接口并重写compareTo方法,不然会抛出ClassCastException设计
那咱们让Person类实现Comparable接口,再存储到TreeSet中:code
(注意,这里只能返回-1,0,1 三个值)blog
import java.util.TreeSet; public class Test { public static void main(String[] args) { TreeSet<Person> set = new TreeSet<>(); set.add(new Person(1, "辣条")); set.add(new Person(3, "冰棍")); set.add(new Person(4, "面包")); set.add(new Person(2, "薯片")); set.add(new Person(2, "薯片")); set.add(new Person(2, "薯片")); for (Person person : set) { System.out.println(person); } } } class Person implements Comparable<Person> { public int id; public String name; public Person(int id, String name) { this.id = id; this.name = name; } @Override public String toString() { return "Person [id=" + id + ", name=" + name + "]"; } @Override public int compareTo(Person o) { if (o.id - this.id > 0) { //设计的是降序排列,大的往左靠 return 1; }else if (o.id - this.id == 0) { return 0; }else { return -1; } } }
运行结果:排序
除了让存入的类型实现Comparable接口外,还能够在初始化TreeSet时传入一个比较器
这里用到了以前在内部类里提到的一个比较经常使用的东西:匿名内部类!!
import java.util.Comparator; import java.util.TreeSet; public class Test { public static void main(String[] args) { TreeSet<Person> set = new TreeSet<>(new Comparator<Person>() { @Override public int compare(Person o1, Person o2) { if (o1.id - o2.id > 0) { // 设计的升序排列,大的往右靠 return 1; }else if (o1.id - o2.id == 0) { return 0; }else { return -1; } } }); set.add(new Person(1, "辣条")); set.add(new Person(3, "冰棍")); set.add(new Person(4, "面包")); set.add(new Person(2, "薯片")); set.add(new Person(2, "薯片")); set.add(new Person(2, "薯片")); for (Person person : set) { System.out.println(person); } } } class Person { public int id; public String name; public Person(int id, String name) { this.id = id; this.name = name; } @Override public String toString() { return "Person [id=" + id + ", name=" + name + "]"; } }
运行结果: