Java beginners learn something (13)

Posted by Dada78 on Thu, 30 Dec 2021 05:22:46 +0100

1.TreeSet

The parent interface of TreeSet is Set. The stored values cannot be repeated. At the same time, the stored values are sorted

The principle of sorting is the principle of binary tree

6  2  8  14  16  3  4  10  5  7  19
     6
  2       8
0    3         14
   0   4     10     16
     0   5  7   0  0   19
      
It's an unbalanced tree


There is a red black tree in the data structure, which can balance the table data, so the efficiency will be very low and the tree will be rotated


If you simply search, the efficiency of binary tree is relatively high


The underlying things will not be irrelevant for the time being. You can type the code first


If you are interested, you can study data structure. Data structure is a subject with more contents.
      
      

[precautions]:

If the TreeSet set contains wrapper classes of eight basic data types, such as Integer and String, it will not be reported

Wrong, but if an object of a self-defined class is placed in the TreeSet set, an error will be reported, and an error of class conversion exception will be reported. Then some compatriots have a problem. How to put the custom object in?

For example, chestnuts:

Create a Dog class to implement the Comparable interface, assign a generic value to the class Dog, and rewrite its abstract method compareTo, You can think of a way to compare two objects: (1) compare the age of the object, (2) This is the name of the comparison object. The TreeSet set will be sorted in ascending order. How to compare the two? We can compare their ages first. If the two dogs are the same age, then compare their names. If the names are the same, it can be regarded as a Dog. The compareTo method is to compare. It returns less than a negative number, greater than a positive number, and equal Returning 0, we can add an if branch to the method body (I used a trinary operation here to save the amount of code) for comparison and sorting, then write its construction method and rewrite toString.

Next, in the main function, we will talk about the instantiation of TreeSet, and add several lovely dogs in the collection. Finally, we will traverse and print by strengthening the for loop (we can also print it directly from sout h, after all, we have rewritten the toString method). The code and results are as follows:

import java.util.TreeSet;

class Dog implements Comparable<Dog>{
private String name;
private int age;

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

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

    @Override
    public int compareTo(Dog o) {
        int num = this.age-o.age;
        return num ==0 ? this.name.compareTo(o.name):num;
    }
}
public class Demo1 {
    public static void main(String[] args) {
        TreeSet<Dog> dogs = new TreeSet<>();
        dogs.add(new Dog("Xiaobai",12));
        dogs.add(new Dog("Xiao Huang",10));
        dogs.add(new Dog("Xiao Hei",10));
        dogs.add(new Dog("Xiaobai",12));
        dogs.add(new Dog("Blue ",9));
        for (Dog dog:dogs
             ) {
            System.out.println(dog);
        }
    }
}

2. Anonymous internal class [ key ]

2.1 anonymous inner class based on abstract class

As we all know, to call abstract methods in abstract classes and interfaces, there must be an implementation class rewriting abstraction party

Method, and then instantiate the implementation class in the main function, and then call the abstract method. Because programmers are lazy, so

An anonymous inner class appears. You can call the abstract method directly in the main function. Let's give you an example:

abstract class Test{
    abstract void test1();
}
interface MyTest{
    void test2();
}
public class Dome1 {
    public static void main(String[] args) {
        new Test() {
            @Override
            void test1() {
                System.out.println("I am an anonymous Abstract inner class!!!");
            }
        }.test1();
        new MyTest() {
            @Override
            public void test2() {
                System.out.println("I am an abstract method in the interface!!");
            }
        }.test2();
    }
}

Summary:

In real development, the parameter of a method may be an interface or abstract class. What should I do? There are two solutions

1. Honestly write a class to inherit or implement the parameters passed to the method

2. Directly use anonymous internal classes, directly instantiate interfaces or abstract classes, but implement methods.

3.Map set

3.1Map set

Collection: a collection of data

Bilateral queue

Map<K, V>

K: Key key

5: V alue value

0 ===> dog egg 1 ====== rhubarb 2 ======= Wangcai 3 ======= Xiaohei

Value can be obtained through key

The ID number corresponds to us.

The ID number is equivalent to the key. I am worth the value.

1101111111 = = "Zhang San himself"

Key value pair

Public interface map < K, V > the data stored in the map set is in the form of key value pairs

Map is an interface

The bottom layer of the implementation class HashMap < K, V > is the hash table, which is particularly similar to HashSet

When saving data, it is stored based on the key. If the key is the same, it cannot be saved again

The bottom layer of the implementation class treemap < K, V > is a binary tree, which can sort the keys we store

3.2Map interface following common methods

Add:

put(K key, V value); What is passed in is the corresponding k and v data types, with a generic constraint.

putAll(Key k,Value v); Delete a map set in another map set:

remove(K key) ; Delete the value through the key and return the deleted value

Change:

put(K key, V value); When the key exists, it is modified. When the key does not exist, it is added

Check: [important and many methods]

int size(); Number of valid key value pairs

boolean isEmpty(); Judge whether the map combination is empty

Set keySet(); The key in the map set is converted to the set set [difficult, a little difficult to understand]

Collection values(); Convert the value in the map collection to a collection object

boolean containsKey(Object key); Returns true if the map collection contains the entered key

boolean containsValue(Object value); Returns true if the map collection contains the entered value

import java.util.*;

class Dog{
    private String name;
    private int age;
    private double price;

    public Dog(String name, int age, double price) {
        this.name = name;
        this.age = age;
        this.price = price;
    }

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

public class Demo1 {
    public static void main(String[] args) {
        Map<Integer, String> map = new HashMap<>();
        //HashMap is the implementation class of Map collection. It is instantiated by polymorphic parent class references pointing to child class objects
        map.put(2,"Zhang San");
        map.put(1,"Li Si");
        map.put(5,"Wang Wu");
        map.put(12,"Xiaobai");
        map.put(78,"Pineapple Bun");
        //The put method in the map set is to add key value pairs to the map set
        System.out.println("put Value transfer function of:"+map);
        Map<Integer, String> map1 = new HashMap<>();
        map1.put(45,"Satan");
        map1.put(21,"lord");
        map.putAll(map1);//Let's put the map1 set into the map. Note that the data types of the two sets must be the same
        System.out.println("putAll Merge two sets into one:"+map);
        map.put(2,"Li Hei");
        System.out.println(""+map);
        map.remove(1);
        System.out.println(""+map);
        map.clear();
        System.out.println(""+map);
        Map<Integer, Dog> dog = new HashMap<>();//map sets pass values to set sets and collection sets
        Dog dog1 = new Dog("chinese rhubarb", 2, 100.00);
        dog.put(1,dog1);
        dog.put(2,new Dog("Big black",4,200.00));
        dog.put(3,new Dog("Big white",6,300.00));
        System.out.println(dog);
        Set<Integer> keys = dog.keySet();//The key value of the map set cannot be repeated, so it is converted with the set set
        System.out.println(keys);
        Collection<Dog> dogs = dog.values();//The values of the map set can be repeated, so use the collection set to convert,
        //Here is the class object to be passed. You can pass whatever you want. For example, if you want to pass String, you can change it to String in the generic type
        System.out.println(dogs);
        System.out.println(dog.containsKey(1));//Query for this key
        System.out.println(dog.containsValue(dog1));//Query whether there is this value (object). Note that if you want to query, the object should be instantiated!
    }
}

 

Topics: Java