首先,TreeSet隶属collection,具备collection的方法;
特点:可排序、无索引、不重复
底层:基于红黑树实现
注意:
1.对于数值型(Integer、Double....),是按照大小排序
2.对于字符串类型,去首字母比较。
3.对于自定义类型,比如Student,treeset是无法进行排序的,如果非要排序,有两种方法;
一、实现Compareable接口重写compareTo方法
例子如:Student
public class Student implements Comparable<Student>{ private Integer id; private String name; private Integer age; private String address; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Student() { } public Student(Integer id, String name, Integer age, String address) { this.id = id; this.name = name; this.age = age; this.address = address; } @Override public String toString() { return "Student{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + ", address='" + address + '\'' + '}'; } @Override public int compareTo(Student o) { return this.getAge()-o.getAge(); }
Demo类:
public class DemoTestTreeSet { public static void main(String[] args) { TreeSet<Student> students = new TreeSet<>(); students.add(new Student(1, "张三", 18, "北京")); students.add(new Student(2, "李四", 20, "上海")); students.add(new Student(3, "王五", 19, "广州")); students.add(new Student(4, "赵六", 21, "深圳")); students.forEach(s-> System.out.println(s)); }
由于我们前面设置的是根据年龄大小排序所以结果如下
第二种:定义treeset的时候创建Comparator定义排序规则
TreeSet<Student> students2 = new TreeSet<>(new Comparator<Student>() { @Override public int compare(Student o1, Student o2) { return o1.getAge()- o2.getAge(); } }); students2.add(new Student(1, "张三", 18, "北京")); students2.add(new Student(2, "李四", 20, "上海")); students2.add(new Student(3, "王五", 19, "广州")); students2.add(new Student(4, "赵六", 21, "深圳")); students2.forEach(s-> System.out.println(s));