LinkedHashSet底层原理

TreeSet(尤其是自带的有序属性介绍)

TreeSet自定义排序规则

TreeSet自定义排序规则,关于返回值的规则

代码:掌握TreeSet集合的使用。
代码一:调用有参构造器设置comparator对象来指定比较规则
Student类(学生类)
package com.itheima.day20_Collection_set;import java.util.Objects;public class Student{private String name;private int age;private double height;@Overridepublic String toString() {return "Student{" +"name='" + name + '\'' +", age=" + age +", height=" + height +'}';}public Student() {}public Student(String name, int age, double height) {this.name = name;this.age = age;this.height = height;}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 double getHeight() {return height;}public void setHeight(double height) {this.height = height;}
}
TreeSetTest 类(主程序)
package com.itheima.day20_Collection_set;import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;
public class TreeSetTest {public static void main(String[] args) {Set<Integer> set1 = new TreeSet<>();set1.add(6);set1.add(5);set1.add(5);set1.add(7);System.out.println(set1);Set<Student> students = new TreeSet<>(new Comparator<Student>() {@Overridepublic int compare(Student o1, Student o2) {return Double.compare(o1.getHeight(),o2.getHeight());}});students.add(new Student("飞鸟马时",17,165));students.add(new Student("枣伊吕波",18,155));students.add(new Student("調月莉音",18,170));System.out.println(students);}
}

代码二:实现comparable接口,重写compareTo方法来指定比较规则
Student类(学生类)
package com.itheima.day20_Collection_set;import java.util.Objects;public class Student implements Comparable<Student>{private String name;private int age;private double height;@Overridepublic String toString() {return "Student{" +"name='" + name + '\'' +", age=" + age +", height=" + height +'}';}public Student() {}public Student(String name, int age, double height) {this.name = name;this.age = age;this.height = height;}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 double getHeight() {return height;}public void setHeight(double height) {this.height = height;}@Overridepublic int compareTo(Student o) {return this.age - o.age;}
}
TreeSetTest 类(主程序)
package com.itheima.day20_Collection_set;import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;
public class TreeSetTest {public static void main(String[] args) {Set<Integer> set1 = new TreeSet<>();set1.add(6);set1.add(5);set1.add(5);set1.add(7);System.out.println(set1);Set<Student> students = new TreeSet<>();students.add(new Student("飞鸟马时",17,165));students.add(new Student("枣伊吕波",18,155));students.add(new Student("調月莉音",18,170));System.out.println(students);}
}
