JAVA_TreeSet

1. Generic

1.1 Overview of generics [understanding]

  • Introduction to generics

    ​ Generics is a feature introduced in JDK5, which provides a compile-time type safety detection mechanism

  • Benefits of generics

    1. Advance the runtime problem to the compilation period
    2. Avoid coercion
  • Generic definition format

    • <Type>: Specify a type of format. You can write arbitrarily inside the angle brackets, generally only one letter. For example:
    • <Type 1, Type 2…>: Specify multiple types of formats, separated by commas. For example: <E,T> <K,V>

1.2 Generic class [application]

  • Define format

    修饰符 class 类名<类型> {
          
            }
    

1.3 Generic method [application]

  • Define format

    修饰符 <类型> 返回值类型 方法名(类型 变量名) {
          
            }
    
  • Sample code

1.4 Generic interface [application]

  • Define format

    修饰符 interface 接口名<类型> {
          
            }
    
  • Sample code

1.5 Type wildcard

  • Type wildcard: <?>

    • ArrayList<?>: Represents an ArrayList whose element type is unknown, and its elements can match any type
    • But you can't add elements to the ArrayList, and what you get is also the parent type.
  • Type wildcard upper limit: <? extends type>

    • ArrayListList <? extends Number>: The type it represents is Number or its subtypes
  • Type wildcard lower limit: <? super type>

    • ArrayListList <? super Number>: The type it represents is Number or its parent type
  • Use of generic wildcards

2.Set collection

2.1 Set collection overview and characteristics [application]

  • Can not store duplicate elements
  • Without index, you cannot use normal for loop to traverse

2.2 Use of Set Set 【Application】

Store string and traverse

3.TreeSet collection

3.1 Overview and characteristics of the TreeSet collection [application]

  • Can not store duplicate elements
  • No index
  • You can sort elements according to rules
    • TreeSet(): Sort according to the natural ordering of its elements
    • TreeSet(Comparator comparator): Sort according to the specified comparator

3.2 Basic use of TreeSet collection [application]

Store integers of Integer type and traverse

3.3 Use of Comparable Natural Sorting [Application]

  • Case requirements

    • Store student objects and traverse, create a TreeSet collection using no-argument construction method
    • Requirement: Sort by age from youngest to oldest. When the age is the same, sort by alphabetical order of names
  • Implementation steps

    1. Use null parameter construction to create a TreeSet collection
      • Use the TreeSet collection to store custom objects, and the parameterless construction method uses natural sorting to sort the elements
    2. The custom Student class implements the Comparable interface
      • Natural ordering means that the class to which the element belongs implements the Comparable interface and overrides the compareTo(T o) method
    3. Override the compareTo method in the interface
      • When rewriting the method, it must be noted that the sorting rules must be written in accordance with the required primary and secondary conditions

example:

public class MyTreeSet1 {
    
    
    public static void main(String[] args) {
    
    
        TreeSet<Student> ts = new TreeSet<>();

        Student s1 = new Student("小花",10);
        Student s2 = new Student("花",10);
        Student s3 = new Student("小",13);

        ts.add(s1);
        ts.add(s2);
        ts.add(s3);

        System.out.println(ts);

    }
}
public class Student implements Comparable<Student>{
    
    
    //<>为什么写student  因为要给student 排序 所以用student
    private String name;
    private int age;

    @Override
    public String toString() {
    
    
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    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 Student(String name, int age) {
    
    
        this.name = name;
        this.age = age;
    }

    public Student() {
    
    
    }

    /*
    0:只存一个
    1/正数:按照添加顺序存储
    负数:按照添加数据反向存储
     */
    @Override
    public int compareTo(Student o) {
    
    
        //按照对象的年龄排序
        //自然排序
        int result = this.age - o.age;
        //判断结果  如果相同 就开始比较姓名 是否相同
        result  = result == 0 ? this.name.compareTo(o.getName()) : result;
        return result;
    }
}

3.4 Use of Comparator Sorting [Application]

  • Case requirements

    • Store the teacher object and traverse, create the TreeSet collection using the parameterized construction method
    • Requirement: Sort by age from youngest to oldest. When the age is the same, sort by alphabetical order of names
  • Implementation steps

    • Use the TreeSet collection to store custom objects, and the parameter construction method uses the comparator sort to sort the elements
    • Comparator sorting is to allow the collection construction method to receive the implementation class object of the Comparator and override the compare(T o1, T o2) method
    • When rewriting the method, it must be noted that the sorting rules must be written in accordance with the required primary and secondary conditions

example:

public class Teacher {
    
    
    private String name;
    private int age;

    public String getName() {
    
    
        return name;
    }

    @Override
    public String toString() {
    
    
        return "Teacher{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    public int getAge() {
    
    
        return age;
    }

    public void setAge(int age) {
    
    
        this.age = age;
    }

    public Teacher(String name, int age) {
    
    
        this.name = name;
        this.age = age;
    }

    public Teacher() {
    
    
    }
}
public class MyTreeSet4 {
    
    
    public static void main(String[] args) {
    
    
        TreeSet<Teacher> ts = new TreeSet<>(new Comparator<Teacher>() {
    
    
            @Override
            public int compare(Teacher o1, Teacher o2) {
    
    
                //比较器排序
                //o1表示现在要存入的那个元素
                //o2表示已经存入到集合中的元素

                //主要条件
                int result = o1.getAge() - o2.getAge();
                //次要条件
                result = result == 0 ? o1.getName().compareTo(o2.getName()) : result;
                return result;
            }
        });

        Teacher t1 = new Teacher("张三",22);
        Teacher t2 = new Teacher("李四",23);
        Teacher t3 = new Teacher("王五",23);

        ts.add(t1);
        ts.add(t2);
        ts.add(t3);

        System.out.println(ts);
    }
}

3.5 Summary of two comparison methods [understanding]

  • Summary of the two comparison methods
    • Natural sorting: The custom class implements the Comparable interface, overrides the compareTo method, and sorts according to the return value
    • Comparator sorting: Pass the implementation class object of Comparator when creating the TreeSet object, override the compare method, and sort according to the return value
    • When in use, natural sorting is used by default. When natural sorting does not meet the current needs, comparator sorting must be used
  • Rules about return values ​​in two ways
    • If the return value is negative, it means that the currently stored element is a smaller value, and it is stored on the left
    • If the return value is 0, it means that the currently stored element is duplicated with the element in the collection, and it is not stored
    • If the return value is positive, it means that the currently stored element is a larger value, and it is stored on the right

4. Data structure

4.1 Binary Tree [Understanding]

  • Features of Binary Tree

    • In the binary tree, the degree of any node must be less than or equal to 2
      • Node: In the tree structure, each element is called a node
      • Degree: The number of child nodes of each node is called degree
  • Binary tree structure diagram

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-RlLZSwOS-1598791097928) (E:\CSDN\javaSEAdvanced\img\01_binary tree structure diagram.png) ]

4.2 Binary Search Tree [Understanding]

  • Features of binary search tree

    • Binary search tree, also known as binary sort tree or binary search tree
    • There are at most two child nodes on each node
    • The values ​​of all nodes on the left subtree are less than the value of the root node
    • The value of all nodes on the right subtree is greater than the value of the root node
  • Binary search tree structure diagram

Comparison structure diagram of binary search tree and binary tree

Binary search tree add node rules

  • Save the small one on the left
  • Big save right
  • The same does not exist

4.3 Balanced Binary Tree [Understanding]

  • Features of balanced binary tree

    • The height difference between the left and right subtrees of the binary tree does not exceed 1
    • The left and right subtrees of any node are a balanced binary tree
  • Balanced binary tree rotation

    • Rotation trigger timing

      • After adding a node, the tree is no longer a balanced binary tree
    • Left hand

      • It is to pull the right side of the root node to the left, the original right child node becomes the new parent node, and the excess left child node is transferred, and the degraded root node becomes the right child node

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-YSQ7T8Ni-1598791097932) (E:\CSDN\javaSE advanced\img\05_balanced binary tree left-rotation 02.png )]

Right hand

  • It is to pull the left side of the root node to the right, the left child node becomes the new parent node, and the excess right child node is transferred, and the degraded root node becomes the left child node

[External link image transfer failed. The source site may have an anti-hotlinking mechanism. It is recommended to save the image and upload it directly (img-femcyxAX-1598791097940) (E:\CSDN\javaSEAdvanced\img\06_balanced binary tree right rotation 02. png)]

Comparison structure diagram of balanced binary tree and binary search tree

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-6qBiWDYm-1598791097944) (E:\CSDN\javaSEAdvanced\img\07_balanced binary tree and binary search Tree comparison structure diagram.png)]

Four cases of balanced binary tree rotation

  • Left left

    • Left left: When the left subtree of the left subtree of the root node has a node inserted, the binary tree is unbalanced
    • How to rotate: directly rotate the whole to the right

about

  • Left and right: When the right subtree of the left subtree of the root node has a node inserted, the binary tree is unbalanced

  • How to rotate: first rotate left at the position of the node corresponding to the left subtree, and rotate the whole to the right

Right right

  • Right: When the right subtree of the right subtree of the root node has a node inserted, the binary tree is unbalanced

  • How to rotate: directly rotate the whole to the left

Right left

  • Right left: When the left subtree of the right subtree of the root node has a node inserted, the binary tree is unbalanced

  • How to rotate: first rotate the node position corresponding to the right subtree to the right, and rotate the whole to the left

style=“zoom:50%;” />

about

  • Left and right: When the right subtree of the left subtree of the root node has a node inserted, the binary tree is unbalanced

  • How to rotate: first rotate left at the position of the node corresponding to the left subtree, and rotate the whole to the right

Right right

  • Right: When the right subtree of the right subtree of the root node has a node inserted, the binary tree is unbalanced

  • How to rotate: directly rotate the whole to the left

Right left

  • Right left: When the left subtree of the right subtree of the root node has a node inserted, the binary tree is unbalanced

  • How to rotate: first rotate the node position corresponding to the right subtree to the right, and rotate the whole to the left

Guess you like

Origin blog.csdn.net/qq_42073385/article/details/108310639