JavaSE advanced day 8
Syllabus:
- generic paradigm
- Set set
- TreeSet
- HashSet
- Data structure - binary tree
1, Generics
1. What is generics
A wide range of types, similar to decimals in mathematics x Variable can be whatever type you want it to be Generics are JDK5 New features (automatic disassembly and assembly of box, enhancement) for And generics), Generics are a security mechanism at compile time. Generics are only valid at compile time, but not after compilation(Generic erasure)
2. Benefits of generics
- Advance the run-time problem to compile time
- Casts are avoided
3. Where generics can be used
4. How to use generics
Generics are generally defined in<>In, a name (variable name) should be given. The name can be composed of one letter or multiple letters, A generic type can be one part or many parts. When a generic type is passed, only reference types can be passed <E> <T> <K> <V> <HELLO> <AB> <K,V> <X,Y,Z,...>
5. Generic format
5.1 generic classes
public class Class name<E> { } E Generic variables will be used in classes and can be used in methods (return value types, parameter types, and variable types in the method body) Or on a member variable, use it as a type. When to determine the generic concrete type: determine the generic concrete type when creating an object
//Is a generic class public class Box<E> { private E Element; public E getElement() { return Element; } public void setElement(E element) { Element = element; } }
Box<String> box = new Box<>(); box.setElement("Love for Xiao Li!"); System.out.println(box.getElement()); Box<Integer> inter = new Box<>(); inter.setElement(11); System.out.println(inter.getElement());
5.2 generic methods
Modifier <T> Return value type method name(parameter list) { } T Generic variables are sure to be used in methods. They can be used in the current generic method (return value type, parameter type, variable type in method body). However, this method cannot be used. When to determine the generic concrete type: determine the generic concrete type when calling
ArrayList<String> list = new ArrayList<>(); list.add("Love for Xiao Li"); list.add("Love for the path"); list.add("Love for flowers"); // Convert the list collection into an array and return // If it is null, the returned array type is Object Object[] objects = list.toArray(); System.out.println(Arrays.toString(objects) +"-----"+"Object type"); System.out.println("-------------------------"); // Convert the list collection into an array and return // list.toArray(T[] a) String[] strings = list.toArray(new String[list.size()]); System.out.println(Arrays.toString(strings)+"-----"+"String type");
public static void main(String[] args) { ArrayList<String> list = addElement(new ArrayList<String>(), "a", "b", "c", "d"); System.out.println(list+"-------"+"String type"); System.out.println("------------------------"); ArrayList<Integer> inter = addElement(new ArrayList<Integer>(), 1, 2, 3, 4); System.out.println(inter+"-------"+"Integer type"); } public static <T> ArrayList<T> addElement(ArrayList<T> list,T t1,T t2,T t3,T t4){ list.add(t1); list.add(t2); list.add(t3); list.add(t4); return list; }
5.3 generic interfaces
public interface Interface name<E> { } E Generic variables will certainly be used in interfaces. They can be used on methods (return value types, parameter types) or constants as types. When to determine the specific type of a generic type: 1,Determine the generic concrete type when creating the implementation class object 2,Determine the generic concrete type when defining the implementation class 3,Determine the specific type of the generic when defining the sub interface
interface Genericity<E>{ public abstract void method(E e); }
class GenericityImpl1<E> implements Genericity<E>{ @Override public void method(E e) { System.out.println(e); } }
GenericityImpl1<String> genericity = new GenericityImpl1<>(); genericity.method("Xiaoli's love for me");
Mode II
class GenericityImpl2 implements Genericity<Integer>{ @Override public void method(Integer integer) { System.out.println(integer); } } class GenericityImpl3 implements Genericity<String>{ @Override public void method(String string) { System.out.println(string); } }
GenericityImpl2 genericityImpl2 = new GenericityImpl2(); genericityImpl2.method(12); System.out.println("--------------"); GenericityImpl3 objectGenericityImpl3 = new GenericityImpl3(); objectGenericityImpl3.method("Love for Andy");
5.4 type wildcards
- Type wildcard: <? >
- ArrayList<?> : Represents an ArrayList whose element type is unknown, and its elements can match any type
- However, the element cannot be added to the ArrayList, and the parent type is also obtained
Type wildcard upper limit:<? extends type> ArrayList<? extends Number>: The type it represents is Number Or its subtypes Type wildcard lower limit:<? super type> ArrayList<? super Number>: The type it represents is Number Or its parent type
ArrayList<Integer> list1 = new ArrayList<>(); ArrayList<String> list2 = new ArrayList<>(); ArrayList<Number> list3 = new ArrayList<>(); ArrayList<Object> list4 = new ArrayList<>(); printList(list1); printList(list2);
public static void printList(ArrayList<?> list) { //Any generic type can be passed }
// Represents the type passed into the collection, which can be Number type or all subclass types of Number public static void method1(ArrayList<? extends Number> list) { } // Represents the type passed into the collection, which can be Number type or all the parent types of Number public static void method2(ArrayList<? super Number> list) {}
ArrayList<Integer> list1 = new ArrayList<>(); ArrayList<String> list2 = new ArrayList<>(); ArrayList<Number> list3 = new ArrayList<>(); ArrayList<Object> list4 = new ArrayList<>(); method1(list1); //Subclass of number method1(list3); //numberz himself // method1(list4); // An error is reported. The Object type is larger than Number // method2(list1); An error is reported. Integer type is smaller than Number method2(list4); //Parent class of number method2(list3); //number itself
Methods involving generic wildcards in 5.5 collection
boolean addAll(Collection<? extends E> c): take b Add all elements in the collection to a In collection boolean containsAll(Collection<?> c): judge a Whether the collection contains b All elements in the collection boolean removeAll(Collection<?> c): delete a The collection contains b Elements of a collection (delete intersection) boolean retainAll(Collection<?> c): retain a The collection contains b Elements of a collection (preserve intersection) To operate these methods, there must be two sets, one is the caller set, and the other is the parameter set a.addAll(b),a Is a collection of callers, b Is the parameter set
2, Set set
1. Characteristics of set
- Cannot store duplicates
- Without an index, you cannot use an ordinary for loop to traverse, nor can you get it through the index and delete the elements in the collection
- Orderly access cannot be guaranteed
Set<String> set = new TreeSet<>(); set.add("ccc"); set.add("aaa"); set.add("aaa"); set.add("bbb");
Can only be traversed with enhanced for or iterators
Iterator<String> it = set.iterator(); while (it.hasNext()) { String s = it.next(); System.out.println(s); } System.out.println("-----------------"); for (String s : set) { System.out.println(s); }
2.TreeSet
2.1 TreeSet set features
- A collection that does not contain duplicate elements
- There is no indexed method
- You can sort elements according to rules
2.2 natural sorting
2.2.1 implementation mode:
- Implement the class where the element is located into the Comparable interface
- Override the abstract method compareTo method in the class (the code in the compareTo method is used to set rules)
2.2.2 compareTo method
Two objects: this and o Are objects of the current class this:Represents the element currently to be added o:Elements already stored in the collection this before, o In ascending order after o before, this In descending order after Return value Positive number: the element is placed behind (to the right)/(below) 0: delete Negative: the element is placed in the front (left)/Above)
TreeSet<Student> ts = new TreeSet<>(); Student s1 = new Student("dahei",80,80,80); Student s2 = new Student("erhei",90,90,90); Student s4 = new Student("erhei2",95,85,90); Student s3 = new Student("xiaohei",100,100,100); ts.add(s1); ts.add(s2); ts.add(s3); ts.add(s4); for (Student t : ts) { System.out.println(t); }
public class Student implements Comparable<Student>{}
public int compareTo(Student o) { int result = o.getScore() - this.getScore(); result = result == 0 ? o.getChinese() - this.getChinese() : result; result = result == 0 ? o.getMath() - this.getMath() : result; result = result == 0 ? o.getEnglish() - this.getEnglish() : result; result = result == 0 ? o.getName().compareTo(this.getName()) : result; return result; }
2.3 comparator sequencing
2.3.1 implementation mode
- Define a class that implements the Comparator interface
- Override the abstract method compare method in the implementation class (the code in compare method is used to set rules)
- When creating a TreeSet object, the implementation class object is passed to the construction method of TreeSet
2.3.2 compare method
Two objects: o1 and o2 Represents an element object o1:Represents the element currently to be added o2:Elements already stored in the collection o1 before, o2 In ascending order after o2 before, o1 In descending order after Return value Positive number: the element is placed behind (to the right)/(below) 0: delete Negative: the element is placed in the front (left)/Above) Note: o1 Equivalent to in natural sorting this o2 Equivalent to in natural sorting o
TreeSet<Teacher> ts = new TreeSet<>(new Comparator<Teacher>() { @Override public int compare(Teacher o1, Teacher o2) { //o1 represents the element to be stored now // o2 represents the element that has been stored in the collection int result = o1.getAge() - o2.getAge(); result = result == 0 ? o1.getName().compareTo(o2.getName()) : result; return result; } }); Teacher t1 = new Teacher("zhangsan", 23); Teacher t2 = new Teacher("lisi", 22); Teacher t3 = new Teacher("wangwu", 24); Teacher t4 = new Teacher("zhaoliu", 24); ts.add(t1); ts.add(t2); ts.add(t3); System.out.println(ts);
2.4 selection of two sorting methods
- Custom class: choose one of the two methods to achieve the same purpose. Generally, there are many natural methods
- Classes provided by JDK, such as Integer and String, have default natural sorting methods. When the default method does not meet the conditions, select comparator sorting
- When two sorting methods exist at the same time, the comparator sorting method will override the natural sorting method
3, Binary tree
3.1 structure
3.1.1 node structure
3.1.2 structure of binary tree
- Height (number of floors): 4
- Top node: root node
- 4 is the left node of 7 and 10 is the right node of 7
3.1.3 binary lookup tree
characteristic: 1.There are at most two child nodes on each node 2.The left child node of each node is smaller than its own 3.The right child node of each node is larger than its own
3.2 adding nodes to binary search tree
Rules: The small one is on the left The big one is on the right The same does not exist
3.3 balanced binary tree
- The height difference between the left and right subtrees of a binary tree shall not exceed 1
- The left and right subtrees of any node are a balanced binary tree
3.4 binary lookup tree
Condition: use left-handed and right-handed mechanisms to ensure the balance of the tree
Note:
- Judge the relationship between the added element and the current node
- After successful addition, judge whether the balance of binary tree is broken
3.5 left hand rotation
- Counterclockwise rotation
- The right child node becomes the parent node (root node)
- The original root node is degraded to a left child node
- Transfer the redundant left child node to the degraded node as the right child node
3.6 right hand rotation
- Clockwise rotation
- The left child node becomes the parent node (root node)
- The original root node is degraded to a right child node
- Transfer the redundant right child node to the degraded node as the left child node
3.7 four cases of rotation
3.7.1 left
When the left subtree node of the left subtree of the root node is inserted, the binary tree is unbalanced
3.7.2 left and right
When the right subtree node of the left subtree of the root node is inserted, the binary tree is unbalanced
3.7.3 right
When a node is inserted into the right subtree of the right subtree of the root node, the binary tree is unbalanced
3.7.4 right and left
When a node is inserted into the left subtree of the right subtree of the root node, the binary tree is unbalanced
h9J-1631619754621)]
[external chain picture transferring... (img-WxvYmz0z-1631619754621)]
3.7.2 left and right
When the right subtree node of the left subtree of the root node is inserted, the binary tree is unbalanced
[external chain picture transferring... (img-g8CAtXxu-1631619754622)]
[external chain picture transferring... (img-fcdzyupa-163169754622)]
[external chain picture transferring... (img-ubdzvbv-1631619754623)]
[external chain picture transferring... (img-kNJg1gsz-1631619754623)]
3.7.3 right
When a node is inserted into the right subtree of the right subtree of the root node, the binary tree is unbalanced
[external chain picture transferring... (img-JiEO64nj-1631619754623)]
[external chain picture transferring... (img-fgkzj9ak-1631619754624)]
[external chain picture transferring... (img-4hiwodv2-163169754624)]
3.7.4 right and left
When a node is inserted into the left subtree of the right subtree of the root node, the binary tree is unbalanced
[external chain picture transferring... (img-l6LCd7az-1631619754625)]
[external chain picture transferring... (IMG uznra7vh-1631619754625)]
[external chain picture transferring... (img-amp6fgbc-163169754626)]