TreeSet
作者:互联网
public class TreeSetTest {
public static void main(String[] args) {
TreeSet<Integer> treeSet = new TreeSet<>();
treeSet.add(2);
treeSet.add(3);
treeSet.add(1);
treeSet.add(2);
treeSet.add(5);
treeSet.add(4);
System.out.println(treeSet); //按照升序遍历 去重
}
}
底层是二叉树 首先插入第一个节点 2 当插入第二个元素时判断 是否比2 小 小就放左边,大就放右边
那么3 就放2的右边
插入第三个元素 1 放在2的左边
插入第四个元素 相等 去重
插入第五个元素 5 放置 3的右边
插入第六个元素 4 放在 3 的左边
2
1 3
4 5
当前二叉树遍历是中序遍历
@AllArgsConstructor @NoArgsConstructor @Data public class Student /*implements Comparable<Student>*/{ private String name; private int age; /* @Override public int compareTo(Student student) { return this.getAge()-student.getAge(); }*/ } class Bijiaoqi implements Comparator<Student>{ @Override public int compare(Student student1, Student student2) { // return student1.getAge()-student2.getAge(); return ((String)(student1.getName())).compareTo(student2.getName()); } }
public class Test03 { public static void main(String[] args) { Bijiaoqi bijiaoqi = new Bijiaoqi(); TreeSet<Student> students = new TreeSet<>(bijiaoqi); students.add(new Student("azhansgan",21)); students.add(new Student("bzhansgan",11)); students.add(new Student("czhansgan",31)); students.add(new Student("bzhansgan",41)); System.out.println(students.size()); System.out.println(students); } }
标签:students,add,Student,new,TreeSet,public,treeSet 来源: https://www.cnblogs.com/Lcch/p/16185361.html