(super detailed notes sorting) power node_ Lao Du | JavaSE advanced [after P486]

Advanced Java se

final keyword

1. final is a keyword in the Java language

2. final means final and immutable

3. final can modify variables, methods and classes

4. final modified variable

5. The local variable modified by final cannot be re assigned, and the variable modified by final can only be assigned a value once

6. final modification method

final decorated methods cannot be overridden

7. final modified class

final decorated classes cannot inherit

package Final;
/*
 final
    1. final Is a keyword in the Java language
    2. final Means final and immutable
    3. final You can modify variables, methods, classes, etc
    4. final Modified variable
        final Modified local variables cannot be re assigned, and final modified variables can only be assigned a value once
    5. final Modification method
        final Decorated methods cannot be overwritten
    6. final Modified class
        final Decorated classes cannot inherit

 */
public class Test01 {
    public static void main(String[] args){
        //local variable
        int i = 100;
        i = 200;
        /*
        final int k = 100;
        k = 0;
        */
    }
}
//inherit
//If you don't want others to extend class A, you can add final to class A
final class A{

}
/*
final Decorated classes cannot inherit
class B extends A{

}*/
//Method coverage
class C{
    public final void doSome(){
        System.out.println("C");
    }
}
class D extends C{
    //Cannot be overwritten
    /*public void doSome(){
        System.out.println("D");
    }*/
}

8. Reference of final modification

The reference can only point to one object, and it can only point to that object forever. Cannot point to another object. During the execution of the method, after the reference points to the object, the object will not be received by the garbage collector until the end of the current method. Although the reference of final points to object A and cannot point to object B again, the value inside the object can be modified

package Final;
/*
 final Modified variable. What if fianl modified variable is a "reference"?
 final Modified References:
    The reference can only point to one object, and it can only point to that object forever. It can no longer point to other objects.
    And during the execution of the method, after the reference points to the object, the object will not be received by the garbage collector
    Space will not be released until the end of the current method

    Although the reference of final points to object A and cannot point to object B again, the value inside the object can be modified

 */
public class Test02 {
    public static void main(String[] args){
        P p = new P(20);

        System.out.println(p.age);
        //-------------------------------------
        final P p1 = new P(30);
        System.out.println(p.age);
        p.age = 60;
        System.out.println(p.age);

        //p1 = new P(); cannot re new

    }
}
class P{
    int age;

    public P() {
    }

    public P(int age) {
        this.age = age;
    }
}

9. Instance variable modified by final

The variable decorated with final can only be assigned once
The instance variable modified by fianl, regardless of the default value assigned by the system, requires the programmer to assign a value manually. This manual copy can also assign a value directly after the variable or in the construction method.

When is the instance variable assigned?
Assign values during the execution of the construction method (when new)

package Final;
/*
final Modified instance variable
    final Decorated variables can only be assigned once
    fianl Modified instance variables, regardless of the default value assigned by the system, require the programmer to assign values manually
    This manual copy can be assigned directly after the variable or in the constructor.

    When is the instance variable assigned?
        Assign values during the execution of the construction method (when new)
 */
public class Test03 {
    public static void main(String[] args){

    }
}
class User{
    //The variable final int i cannot be modified like this;
    //Manual assignment can
    final  int age = 1;
    //The following codes need to be used in combination, and weight is assigned only once
    final double weight;
    /*public User(){
        weight = 80;//Just assign the value before the system assigns the default value
    }*/
    //That's OK
    public User(double D){
        this.weight = D;
    }
}

10. Variable constant modified by final and static (each word is capitalized)

Conclusion:

The variable jointly modified by static final is called "constant".
It is recommended to use uppercase for each word and underline links between each word
In fact, the difference between constants and static variables is that constant values cannot be changed
Constants and static variables are stored in the method area and are initialized when the class is loaded.

Constants are generally public because they cannot be changed

package Final;
/*
final The modified variable is added to the static modifier

Conclusion:
    static final Variables that are jointly modified are called "constants".
    It is recommended to use uppercase for each word and underline links between each word
    In fact, the difference between constants and static variables is that constant values cannot be changed
    Constants and static variables are stored in the method area and are initialized when the class is loaded.
 */
public class Test04 {
    public static void main(String[] args){
        System.out.println(Chiness.COUNTRY);

    }
}
class Chiness{
    String idCard;
    String name;
    String birth;
    //Instance variables, in the heap,
    //The instance variable is modified by final, indicating that the value of the instance variable will not change with the object variable
    //The instance variable modified by final is usually modified by static.
    //Even if it will not change, it is best to declare it static to save memory space
    final static String COUNTRY = "China"; //Class level
}
class MyMath{
    //Constants are generally public
    public static final double PI = 3.1415926;

}

summary

1.1. The class modified by final cannot inherit.
1.2. The method of final modification cannot be overwritten.
1.3. The variable modified by final can only be assigned a value once.
1.4 once a reference modified by final points to an object, it can no longer point to other objects, but the internal data of the object pointed to by the reference can be modified.
1.5. The instance variable modified by final must be initialized manually, and the system default value cannot be used.
1.6. Instance variables modified by final are generally used in conjunction with static and are called constants.
public static final double PI = 3.1415926;

Abstract classes and interfaces and the difference between abstract classes and interfaces

Understanding of abstract classes

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-yvk85nkx-163404133675) (C: / users / 77 / downloads / documents / 09-javase advanced class drawing in each chapter / 01-object-oriented / 001-understanding of abstract classes. png)]

1. What is an abstract class?

Classes and classes have common features. The common features of these classes are extracted to form abstract classes
Class itself does not exist, so an abstract class cannot create an object

2. What kind of abstract class does it belong to?

Abstract classes are also reference data types

3. How to define abstract classes?

​    Syntax:
​	    [Modifier list] abstract class Class name{
​	    	    Class body;
​	    }

4. Abstract classes cannot be instantiated and cannot create objects, so abstract classes are used to be inherited by subclasses

5. final and abstract cannot be used together

These two keywords are opposite

6. Subclasses of abstract classes can also be abstract classes

7. Although an abstract class cannot be instantiated, it has a construction method, which is used by subclasses.

8. Abstract classes are associated with a concept, the concept of abstract methods

Abstract methods represent methods without implementation and methods without method body.
​ pubilic abstract void doSome();
Characteristics of abstract methods:
1. No method body, ending with semicolon;
2. There is an abstract keyword in the previous modifier list

9. Abstract methods do not necessarily exist in abstract classes. Abstract methods must be in abstract classes

package Abstract;
/*
Abstract class:
    1.What is an abstract class?
        Classes and classes have common features. The common features of these classes are extracted to form abstract classes
        Class itself does not exist, so an abstract class cannot create an object
    2.What is the type of abstract class?
        Abstract classes are also reference data types
    3.How are abstract classes defined?
        Syntax:
        [Modifier list] abstract class name{
            Class body;
        }
    4.Abstract classes cannot be instantiated and cannot create objects, so abstract classes are used to be inherited by subclasses
    5.final And abstract cannot be used together
    6.Subclasses of abstract classes can also be abstract classes
    7.Although an abstract class cannot be instantiated, it has a constructor, which is used by subclasses.
    8.Abstract classes are associated with a concept, the concept of abstract methods
        Abstract methods represent methods without implementation and methods without method body
        pubilic abstract void doSome();
        Characteristics of abstract methods:
            1.No method body, ending with a semicolon;
            2.There is an abstract keyword in the previous modifier list
    9.Abstract methods do not necessarily exist in abstract classes. Abstract methods must be in abstract classes
 */
public class Test01 {
    public static void main(String[] args){
        //Cannot instantiate, cannot create object
        //Account account = new Account();
    }
}
//final and abstract cannot be used together
/*final abstract class Account{

}*/
abstract class Account{
    public Account(String s){

    }
    //No, No
    public Account(){
    }
    abstract public void A();

    
}
//Subclasses inherit abstract classes, and subclasses can instantiate objects
/*class CreditAccount extends Account{

}*/
//Subclasses of abstract classes can be abstract classes
//There is a parameterless construct in the constructor by default
//The first behavior of parameterless construction is super, which calls the parameterless construction of the parent class. If the parent class has no parameterless construction (a parameterless construction is directly provided, and there is no parameterless construction by default), an error will be reported
abstract class CreditAccount extends Account{

}
//Abstract methods must be in abstract methods
/*

class B{
    abstract public void A();
}*/

10. How to define abstract methods?

​ public abstract void doSome();

11. (five stars): a non abstract class that inherits an abstract class must override / rewrite / implement the abstract methods in the abstract class.

package Abstract;
/*
 Abstract class:
    1.Abstract classes do not necessarily have abstract methods. Abstract methods must appear in abstract classes
    2.Important conclusion: a non abstract class inherits an abstract class and must implement the abstract methods in the abstract class

    Coverage or rewriting here can also be called implementation
 */
public class Test02 {
    //The parent type is an abstract class and the child type is a non abstract class. Can polymorphism be used here
    //Abstract oriented programming
    //The type of a is Animal, Animal is abstract, and A. is called later. ××
    // Abstract oriented programming, not concrete oriented programming, reduces the coupling degree of the program and improves the expansion ability of the program
    //This programming idea conforms to the OCP principle
    public static void main(String[] args){//When you don't understand the code very well, you can use polymorphism
        Animal a = new Brid(); //Downward transformation
        a.move();
    }
}
//abstract class
abstract class Animal{
    public abstract void move();//Abstract method

}
//Subclass non abstract class
//The subclass inherits from the parent class. If there are abstract methods in the parent class, the subclass must be an abstract class
class Brid extends Animal{
    //The method inherited from the parent class needs to be overridden / overridden, or it can also be called "implementation"
    //The abstract method is implemented
    public void move(){
        System.out.println("move");
    };

}

Face test question (judgment question): all methods without method body in java language are abstract methods.
No, wrong.
Many methods in the Object class have no method body and end with ";, but they
Are not abstract methods, for example:
​ public native int hashCode();
This method calls the dynamic link library program written in C + + at the bottom.
There is no: abstract in the previous modifier list. There is a native. It means to call the JVM local program.

Interface

Basic syntax of interface

1. An interface is a reference data type.

2. Interfaces are completely abstract.

3. How to define an interface: [modifier list] interface interface name {}

4. The interface supports multiple inheritance.

5. There are only constants + abstract methods in the interface.

6. All elements in the interface are public decorated

7. The public abstract of the abstract method in the interface can be omitted.

8. public static final of constants in the interface can be omitted.

9. A method in an interface cannot have a method body.

package Interface;
/*
Interface:
    1.It is also a reference data type. After compilation, it is also a class bytecode file
    2.Interfaces are completely abstract (abstract classes are semi Abstract), or interfaces can be said to be special abstract classes
    3.How is the interface defined and what is the syntax?
    [Modifier list] interface interface name(
    )
    Define class [modifier list] class class name {}
    Define abstract class [modifier list] abstract class class name {}
    4.Interfaces support multiple inheritance. One interface can inherit multiple interfaces
    5.The interface contains only two parts, one is constant and the other is abstract method. There is nothing else in the interface
    6.All elements in the interface are public decorated, and everything in the interface is public
    7.Public abstract is an abstract method in an interface that can be omitted
    8.All methods in the interface are abstract methods. Methods in the interface cannot have method bodies.
    10.public static final of constants in the interface can be omitted
 */
public class Test01 {
    public static void main(String[] args){
        // Any variable written in the interface is a constant
        System.out.println( MyMath.PI);

    }
}
interface A {

}
interface B{

}
//The interface supports multiple inheritance
interface C extends A,B{

}
interface MyMath{
    //constant
    public static final double PI = 3.14;
    //public static final can be omitted
    double K = 3.1;

    // public abstract int sum(int a, int b); / / abstract method

    //Interfaces are abstract. Can 'public static' be omitted when writing code?
    int sum(int a, int b);

    //Can a method in an interface have a method body?
    //Error: an abstract method cannot have a body
    /*void doSome(){

    }*/
    //sub method
    int sub(int a,int b);

}

10. Class to class is called inheritance, and class to interface is called implementation. Implementation can still be regarded as inheritance. Extensions is used for inheritance and implements are used for implementation

11. When a non abstract class implements an interface, all abstract methods in the interface must be implemented.

package Interface;
/*
Interface:
    1.Class to class is called inheritance, and class to interface is called implementation. Implementation can still be regarded as inheritance. Extensions is used for inheritance and implements are used for implementation
    2.When a non abstract class implements an interface, all abstract methods in the interface must be implemented.
 */
public class Test02 {
    public static void main(String[] args){
        //Interface use polymorphism
        MyMath2 mm = new Ab();
        System.out.println(mm.PI);
        int re = mm.sub(4,3);
        System.out.println(re);

    }
}
interface MyMath2{

    public static final double PI = 3.14;

    int sum(int a, int b);

    int sub(int a,int b);

}
//Write a class (this class is a non abstract class)
//The method needs to be overridden because Ab is not an abstract class
class Ab implements MyMath2{
    //Implementing methods in interfaces
    public int sum(int a, int b){

        return a+b;
    };
    public int sub(int a, int b){
        return a-b;
    };

}
//Abstract class implementation, which can be compiled through
abstract class Ac implements MyMath2{

}

12. A class can implement multiple interfaces

Although there is no inheritance relationship between interfaces, they can be forcibly converted, but ClassCastException exceptions may occur at runtime. It needs to be the same as the forced conversion between classes, plus instanceof judgment.

package Interface;
/*
    A class can implement multiple interfaces at the same time
        java Only single inheritance is allowed between classes in. In fact, single inheritance is for simplicity
        In many cases, there will be multiple inheritance, and the interface makes up for this defect

        Although interface A and interface B have no inheritance relationship, they can be forced to convert each other, but ClassCastException exceptions may occur at runtime

        Whether it is downward transformation or upward transformation, there must be inheritance
        If there is no inheritance relationship, the compiler will report an error (the interface will not)
        You need to add instanceof for judgment, and judge before transformation.
 */
public class Test03 {
    public static void main(String[] args){
        //polymorphic
        AA a = new D();
        BB b = new D();
        //Downward transformation
        BB b1 = (BB)a;
        b1.m2();
        //Transition down directly to D
        D d = (D) a;
        d.m2();

        M m = new E();

        //After testing, the interface and interface Zheng Yijian have no inheritance relationship during forced type conversion, and can also be forced
        //However, ClassCastException may occur during runtime. There is no problem with compilation and operation
        if(m instanceof K)
        {
            K k = (K)m;
        }

    }
}
interface M{

}
interface K{

}
class E implements M,K{

}
interface AA{
    void m1();
}
interface BB{
    void m2();
}
interface CC{
    void m3();
}
//Multiple implementations can be made between classes and interfaces
//Classes in the interface need to be overridden
//Similar to multiple inheritance
class D implements AA,BB,CC{
    //m1 for A interface
    public void m1(){};
    public void m2(){};
    public void m3(){};
}

13. If both inheritance and implementation exist: the extends keyword comes first and the implements keyword comes last.

package Interface;
/*
If both inheritance and implementation exist: the extends keyword comes first and the implements keyword comes last.
 */
public class Test04 {
    public static void main(String[] args){
        //create object
        Flyable f = new Cats();//polymorphic
        f.fly();
        Flyable f1 = new fish();
        f1.fly();

    }
}
class Animal{

}
interface Flyable{
    void fly();
}
class Cats extends Animal implements Flyable{
    @Override
    //Abstract method of rewriting interface
    public void fly() {
        System.out.println("Flying cat");
    }
}
//No interface implemented
class Snake extends Animal{

}
class fish extends Animal implements Flyable{
    public void fly() {
        System.out.println("fly🐟");
    }
}

14. When using the interface and writing code, polymorphism can be used (the parent type reference points to the child type object).

The role of interface in development

The role of interface in development is similar to that of polymorphism in development.

Polymorphism: oriented to abstract programming, not specific programming, improve the expansion of the program and reduce the coupling degree of the program.

/*
			public class Master{
				public void feed(Dog d){}
				public void feed(Cat c){}
				//If you want to keep other pets, you need to add another method at this time. (the code needs to be modified)
				//This expansion force is too poor and violates the OCP principle (open to expansion and closed to modification.)
			}
	*/
		public class Master{
			public void feed(Animal a){
				// For Animal parent class programming, the parent class is more abstract than the child class.
				//So we call it abstract oriented programming, not concrete oriented programming.
				//In this way, the expansion of the program is strong.
			}
		}

Role of interface in development:

Interface is completely abstract. Later, abstract oriented programming can be changed to interface oriented programming

With an interface, it means that the expansion is strong, which is high scalability and low coupling.

Are interfaces everywhere in the real world?
There is an interface between bolt and nut
There is an interface between the bulb and the lamp port
There is an interface between laptop and keyboard (usb interface. Is usb interface a protocol / specification formulated by a computer association)
What's the use of interfaces? Good scalability. Pluggable.
Interface is an abstract concept.

Conclusion: interface oriented programming can reduce the coupling degree of the program and improve the expansion force of the program. Comply with OCP development principles.
The use of interface is inseparable from polymorphism mechanism. (interface + polymorphism can reduce coupling.)

The interface can be decoupled. Who and who are decoupled!!!
Any interface has callers and implementers.
Interfaces can decouple callers and implementers.
The caller faces the interface call.
The implementer writes the implementation for the interface.

For the development of large projects in the future, the project is generally separated into one module and one module,
Interface connection is adopted between modules. Reduce coupling.

is a ,has a,like a

is a:

​ Cat is a animal

Anything that satisfies is a means "inheritance relationship"

has a:

​ Student has a pen

Anything that can satisfy has a means "association relationship", which usually exists in the form of "attribute"

​A{
​	B b;
​}

like a:

​ Cooker like a menu

If like a is satisfied, it means "implementation relationship". The implementation relationship is usually: class implementation interface

​ A implements B

What is the difference between abstract classes and interfaces?

Abstract classes are semi abstract and interfaces are completely abstract;

The abstract class has a constructor, but there is no constructor in the interface;

Interfaces and interfaces support multiple inheritance, and only single inheritance can be performed between abstract classes;

A class can implement interfaces at the same time, and an abstract class can only inherit one class;

Only constants and abstract methods are allowed in the interface;

In the future, more interfaces are used than abstract classes. Generally, less abstract classes are used.
Interfaces are generally abstractions of "behavior".

package and import

package

1. package is a package mechanism in Java. The function of package mechanism is to facilitate the relationship between programs

Classes with different functions are stored in different packages. (according to the division of functions, different software packages have different functions.)

2. package is a keyword. For example:

Package demo.src.packageandinport; package statements are only allowed on the first line of source code

3. Naming standard of package name: generally, the company's domain name is in reverse order (the company's domain name is globally unique)

Naming conventions for package names:
Company domain name in reverse order + project name + module name + function name

4. How to compile with package name?

javac -d . xxx.java

5. How does it work?

java full class name

Add: when you say the class name later, if you bring the package name description, it means the complete class name.
If there is no package description, it represents the simple class name.
java.util.Scanner full class name.
Scanner simple class name

import

1. When is import unnecessary?

Not required for java.lang.
Not required under the same package.
Everything else is needed.

2. How to use it?

import full class name;
import package name. *;

import java.util.Scanner; / / full class name.

/ / students' question: is this inefficient.
/ / this is not inefficient because the compiler will automatically change * into a specific class name when compiling.
​ import java.util. * ;

/ / if you want to save energy, you can't save too much.
import java. *; this is not allowed because it is stipulated in the java language that * here only represents the names of some classes.

Access control rights

Types of access control permissions

Private private can only be accessed in this class

public can be accessed from any location

protected representations can only be accessed in this class, the same package, and subclasses

The default representation can only be accessed under this class and the same package

Modifier list this class is the same as any position of the package subclass

public can

protected yes

Yes by default

private can

Sort from large to small: public > protected > Default > private

What can an access control permission modifier modify?

All four properties can be used

All four methods can be used

Classes public and default

Interface public and default

Root class of JDK class library: Object

1. Methods in object class

The methods in this class are common to all subclasses. Any class inherits Object by default. Even if there is no direct inheritance, it will eventually inherit indirectly

Common methods in Object class

The first method: go to the source code. (more troublesome)

The second method: consult the Java help documentation

What is API?

API is an application programming interface. The entire JDK class library is a javase API. Each API will be configured with a set of API help documents. The class library written in advance by SUN company is called API

So far, all we need to know is:

protected Object clone()

//Responsible for object cloning

int hashcode()

//A method to get the hash value of an object

Source code of hashcode method in Object
public native int hashcode();
This method is not an abstract method. It has a native keyword and calls the c + + program at the bottom

Hashmethod () returns the hash value, which is actually the memory address of a Java object. It is a value obtained through the hash algorithm
Therefore, the execution result of the hashcode() method can be regarded as the memory address of a Java object.

package ObjectJDK;
/*
hashcode method
    1. Source code of hashcode method in Object
        public native int hashcode();
        This method is not an abstract method. It has a native keyword and calls the c + + program at the bottom

        hashchode()The returned hash value is actually the memory address of a Java object and a value obtained through the hash algorithm
        Therefore, the execution result of the hashcode() method can be regarded as the memory address of a Java object.

 */
public class Test07 {
    public static void main(String[] args){
        Object o = new Object();
        int hashCodeValue = o.hashCode();

        System.out.println(hashCodeValue);//295530567

        Myclass myclass = new Myclass();
        int hashCodeValue2 = myclass.hashCode();
        System.out.println(hashCodeValue2);//1324119927

    }
}
class Myclass{

}

boolean euqals(Object obj)

//Judge whether objects are equal

In the future, the equals method of all classes also needs to be rewritten, because the equals method in Object compares the memory addresses of the two objects. We should compare the contents, so we need to rewrite it.

Rewriting rules: set by yourself. It mainly depends on what is equal to what. When it is equal, it means that two objects are equal.

Basic data types are practical:==
Object and object comparison: calling the equals method

The String class is written by SUN, so the equals method of the String class is overridden.
In the future, it is better not to use = =, but to call the equals method of the string object.

Note: override the equals method thoroughly.

Summary:
1. The string class has overridden the equals method;
2. The string class has overridden the toString method;

Whether the comparison of basic data types in java is equal or not "==“

java references data types and uses the equals method to determine equality

package ObjectJDK;
/*
 On euqals method
 1.source code
    public boolean equals(Object obj) {
        return (this == obj);
    }
    The above method is the default implementation of the Object class
    In the equals method in Object, the default is = = "to judge whether two objects are equal, while" = = "to judge the memory addresses of two Java objects. We should judge whether the contents of two Java objects are equal
2.SUN The company designed the equals method for:
    In the later programming process, we should use the equals method to judge whether the two objects are equal.
3."= =" cannot be used to judge two Java objects, and "= =" judges the memory addresses of the two objects

 */
public class Test02 {
    public static void main(String[] args){
        //To judge whether the data of two basic data types are equal, you can directly use "= ="
        // ==Is to judge whether 100 in a and 100 in b are equal, and save the variables in a and b
        int a = 100;
        int b = 100;
        System.out.println(a == b); //true
        //To determine whether two java objects are equal, use equals
        MyTime t1 = new MyTime(2008,8,8);//Memory address 1
        MyTime t2 = new MyTime(2008,8,8);//Memory address 2
        //Test whether the equality of two objects can use the double equal sign
        //The double equal sign here determines whether the object memory address saved in t1 is equal to the object memory address saved in t2
        //System.out.println(t1 == t2);
        boolean B = t1.equals(t2);
        System.out.println(B);

        MyTime t3 = new MyTime(2008,8,9);
        System.out.println(t1.equals(t3));

        MyTime t4 = null;
        System.out.println(t1.equals(t4));
    }
}
class MyTime{
    private int year;
    private int month;
    private int day;

    public MyTime() {
    }

    public MyTime(int year, int month, int day) {

        this.year = year;
        this.month = month;
        this.day = day;
    }

    public int getYear() {
        return year;
    }

    public int getMonth() {
        return month;
    }

    public int getDay() {
        return day;
    }

    public void setYear(int year) {
        this.year = year;
    }

    public void setMonth(int month) {
        this.month = month;
    }

    public void setDay(int day) {
        this.day = day;
    }
    /*
        To rewrite the toString method, the more concise and readable the better
        Develop to concise, detailed and easy to read methods
     */
   /* public String toString(){
        return  year + ""+ month +" month "+ day +" day ";

    }*/

    /*
    Default equals
    public boolean equals(Object obj) {
        return (this == obj);
    }
     */
    //Override the equals method
    /*public boolean equals(Object obj) {
        if (obj instanceof MyTime) {
            MyTime mt = (MyTime) obj;
            if (this.year == mt.year && this.month == mt.month && this.day == mt.day) {
                return true;
            }
        }
        return false;
    }*/
    //Improved equals method
    /*public boolean equals(Object obj){
        //If empty
        if(obj == null){
            return false;
        }//If not MyTime
        if(!(obj instanceof MyTime)){
            return false;
        }//If the memory addresses are the same, such as t1.equals(t1)
        if (this == obj){
            return true;
        }
        MyTime mt = (MyTime) obj;
        if (this.year == mt.year && this.month == mt.month && this.day == mt.day) {
            return true;
        }
        //This indicates that obj is not null and obj is MyTime
        return false;
    }*/
    //Improve again
    public boolean equals(Object obj){
        //If empty
        if(obj == null || !(obj instanceof MyTime)){
            return false;
        }//If not MyTime
        //If the memory addresses are the same, such as t1.equals(t1)
        if (this == obj){
            return true;
        }
        MyTime mt = (MyTime) obj;
        return this.year == mt.year && this.month == mt.month && this.day == mt.day;
    }
package ObjectJDK;
/*
    java Overriding toString and equals methods

    Summary:
        1.String Class has overridden the equals method;
        2.String Class has overridden the toString method;

      java "Whether the basic data type comparison is equal in use"==“
      java The data types referenced in use the equals method to determine equality
 */
public class Test03 {
    public static void main(String[] args){
        //In most cases, we create string objects in this way
        String s1 = "Hello";
        String s2 = "ABC";
        //In fact, String belongs to a class, not a basic data type
        //Since String is a class, there is a basic constructor
        String s3 = new String("test1");//Memory addresses are different
        String s4 = new String("test1");

        //The String class has overridden the equals method
        System.out.println(s3.equals(s4));
        //String has overridden the toString method
        String x = new String("xx");
        System.out.println(x.toString());
    }
}
package ObjectJDK;

public class Test05 {
    public static void main(String[] args){
        Address a1 = new Address("1","2","3");
        User u1 = new User("yx",a1);
        User u2 = new User("yx",a1);
        User u3 = new User("yy",new Address("1","2","1"));
        System.out.println(u1.addr);
        boolean flag =  u1.equals(u2);
        System.out.println(flag);
        System.out.println(u1.equals(u3));
    }
}
class User{
    String name;
    Address addr;

    public User() {
    }

    public User(String name, Address addr) {
        this.name = name;
        this.addr = addr;
    }

    public boolean equals(Object obj){
        if(obj == null || !(obj instanceof User)){
            return false;
        }
        if (this == obj){
            return true;
        }
        User u = (User)obj;
        if(this.addr.equals(u.addr) && this.name.equals(u.name)){
            return true;
        }
        return false;
    }

}
class Address{
    String city;
    String street;
    String zipcode;

    public Address() {
    }

    public Address(String city, String street, String zipcode) {
        this.city = city;
        this.street = street;
        this.zipcode = zipcode;
    }
    public String toString(){
        return "CITY:" + city + ",STREET:" + street + ",ZIPCODE:" + zipcode;
    }
    public boolean equals(Object obj){
        if(obj == null || !(obj instanceof Address)){
            return false;
        }
        if (this == obj){
            return true;
        }
        Address A = (Address) obj;
        if(this.city.equals(A.city) && this.street.equals(A.street) && this.zipcode.equals(A.zipcode)){
            return true;
        }
        return false;
    }
}

String toString()

The toString() method of all classes in the future needs to be overridden.
Rewrite the rules, the simpler and clearer it is.

System. Out. Println (Reference); the toString() method of "reference" will be called automatically here.

The String class is written by SUN, and the toString method has been overridden.

package ObjectJDK;
/*
About the toSting () method in the Object class
    1. Source code
     public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }
    The default implementation of toString method in the source code is that the memory address of class name @ object is converted to hexadecimal form
    2.SUN The role of toString method in company design
        toString Method is designed to convert Java objects into string expressions by calling this method
    3.In fact, when SUN develops the java language, it is recommended that all subclasses rewrite the toString method
        toString The method should be simple, detailed and easy to read
 */
public class Test01 {
    public static void main(String[] args){
        MyTime t = new MyTime(1970,1,1);
        String s = t.toString();
        //Note that the toString method will be called automatically when the reference is output
        System.out.println(s);//ObjectJDK. MyTime@776ec8df //January 1, 1970

    }
2

}
class MyTime{
    int year;
    int month;
    int day;

    public MyTime() {
    }

    public MyTime(int year, int month, int day) {

        this.year = year;
        this.month = month;
        this.day = day;
    }
    /*
        To rewrite the toString method, the more concise and readable the better
        Develop to concise, detailed and easy to read methods
     */
    public String toString(){
        return  year + "year" + month + "month" + day + "day";

    }
}

protected void finalize()

//The method that the garbage collector is responsible for calling

finalize method

  1. Source code
    protected void finalize() throws Throwable { }
  2. The finalize method has only one method body without code, and this method is protected
  3. This method does not need to be called manually by the programmer. The garbage collector of the JVM is responsible for calling this method (GC), and the equals toString method is called manually
  4. The Transformation Opportunity of finalize method:
    When a Java object is about to be collected by the garbage collector, the garbage collector is responsible for calling the finalize() method
  5. The finalize method is actually an opportunity prepared by SUN for Java programmers, garbage destruction. If you want to execute a piece of code at the time of object destruction,
    This code needs to be written to finalize
    6. Function of static code block
    static{
    ...
    }
    The static code block is executed when the class is loaded and executed once
    This is the time for SUN to prepare for class loading
    The finalize() method is also an opportunity for SUN to prepare for programmers. This opportunity is the garbage collection opportunity.
    7. The garbage collector in Java will not start easily.
    There is too little garbage or the time is not up. Under various conditions, it may or may not be started.
package ObjectJDK;
/*
 finalize method
    1. Source code
    protected void finalize() throws Throwable { }
    2. finalize Method has only one method body, there is no code in it, and this method is protected
    3. This method does not need to be called manually by the programmer. The garbage collector of the JVM is responsible for calling this method (GC), and the equals toString method is called manually
    4. finalize Timing of method transformation:
        When a Java object is about to be collected by the garbage collector, the garbage collector is responsible for calling the finalize() method
    5. finalize Method is actually an opportunity prepared by SUN company for Java programmers, garbage destruction opportunity. If you want to execute a piece of code at the time of object destruction,
       This code needs to be written to finalize
    6.Role of static code blocks
        static{
         ....
        }
        The static code block is executed when the class is loaded and executed once
        This is the time for SUN to prepare for class loading
        finalize()Method is also an opportunity for SUN to prepare for programmers. This opportunity is the garbage collection opportunity.
    7. Java The garbage collector in does not start easily.
        There is too little garbage or the time is not up. Under various conditions, it may or may not be started.
 */
public class Test06 {
    public static void main(String[] args){
        Person p = new Person();
        //Become rubbish
        p = null;
        
        //There is a piece of code to suggest that the garbage collector start
        System.gc();
    }
}
//There is a business requirement in project development: when all objects are released in the JVM, please record the release time
//The point in time code at which the record object is released is written to the finalize method.
class Person{
    protected void finalize() throws Throwable {
        System.out.println("About to be destroyed");
    }

}

Inner class

Anonymous Inner Class

1. Internal class

Inner class: a new class is defined inside the class, which is called inner class

2. Classification of internal classes:

Static inner class: similar to static variables
Instance inner class: similar to instance variable
Local inner class: similar to local variables

3. The code written using internal classes has poor readability and can be avoided as far as possible

4. Anonymous inner class is a kind of local inner class. Because this class has no name, it is called anonymous inner class

5. The main purpose of learning anonymous inner classes is to make it understandable when you read the code in the future.

Two disadvantages of not recommended:
Too complex, poor readability
Class has no name and can only be used once

package neibulei;
/*
Anonymous inner class:
    1. Inner class
        Inner class: a new class is defined inside the class, which is called inner class
    2. Classification of internal classes:
        Static inner class: similar to static variables
        Instance inner class: similar to instance variable
        Local inner class: similar to local variables

    3. The code written using internal classes has poor readability and can be avoided as much as possible
    4. Anonymous inner class is a kind of local inner class. Because this class has no name, it is called anonymous inner class
    5. The main purpose of learning anonymous inner classes is to make it understandable when you read the code in the future.
        Two disadvantages of not recommended:
            Too complex, poor readability
            Class has no name and can only be used once
 */
public class Test01 {
    public static void main(String[] args){
        //Call the sum method in MyMath
        MyMath mm = new MyMath();
        // Compute c = new ComputeIm();  Downward transformation
        //mm.sum(new ComputeIm(),100,200);
        mm.sum(new Compute(){
            //Anonymous inner classes are not recommended. The code readability is too poor and can only be used once.
            public int sum(int a, int b) {
                return a + b;
            }//Represents the implementation of the interface

        },100,200);
    }
    static String country;
    //This class is inside the class, so it is called an inner class
    //Because there is static in front, it is called static inner class
    static class Inner1{

    }
    //Instance inner class
    class Inner2{

    }
    public void doSome(){
        //local variable
        int n = 100;
        //Local inner class
        class Inner3{

        }
    }
    public void doOther(){
        //The local inner class in dosome cannot be used in a local region
    }
}
//Implementation class of interface
//The interface is completely abstract, and the method is also an abstract method. Here, we need to rewrite the method
/*Using an anonymous inner class, this implementation class can be left blank
class ComputeIm implements Compute{

    @Override
    public int sum(int a, int b) {
        return a + b;
    }
}*/
//Computing interface
interface Compute {
    int sum(int a, int b);
}
class MyMath{
    public void sum(Compute c,int x, int y){
        int revalue = c.sum(x,y);
        System.out.println(x + " + " + y + " = " + revalue);
    }
}

array

One dimensional array

1. The array in Java is a reference data type, which is not a basic data type. The parent class of the array is Object
2. An array is actually a container that can hold multiple elements. Array literally: a set of data
3. The array can store data of basic data type or data of reference data type
4. Because the array is a reference type, the array object is stored in heap memory
Person p1 = new Person();
Person p2 = new Person();
5. Array in memory: if the "java object" is stored in the array, the "reference" of the object (memory address) is actually stored“
6. Once the array is created, the length specified in java is immutable

7. Classification of arrays: one-dimensional, two-dimensional, three-dimensional, multi-dimensional
8. All array objects have a length attribute, which is used to obtain the number of elements in the array
9. Arrays in Java require uniform element types. For example, int type arrays can only store int and person type arrays can only store person
10. When the array is stored in memory, the memory addresses of the elements in the array are continuous (each element stored is regularly arranged next to each other), and the memory addresses are continuous
This is the storage characteristic of array. In fact, array is a simple data structure
11. All arrays take "the memory address of the first small square" as the first memory address (the memory address of the first element in the array is used as the memory address of the array)

12. Each element of the array has a subscript, starting from 0, and the last subscript is: length-1
13. Advantages and disadvantages of array as this data structure:
Advantages: it is very efficient when querying / retrieving elements on a subscript. It can be said that it is a data structure with the highest query efficiency
First: the memory address of each element is continuous in spatial storage
Second: each element type wants to be the same, so the occupied space is the same
Third: know the memory address of the first element, the space occupied by each element, and the subscript, so through a mathematical expression
The memory address on a subscript can be calculated, so the retrieval efficiency of the array is the highest

When storing 100 elements or 100w elements in the array, the efficiency is the same when querying elements, because when searching elements in the array
It won't be found one by one. It is calculated through mathematical expression (direct positioning)

Disadvantages:
First: in order to ensure the memory address continuity of each element in the array, it is inefficient to randomly delete or add elements to the array because random addition and deletion
The element will involve the forward or backward displacement operation of the following elements.
Second: arrays cannot store large amounts of data, because it is difficult to find a particularly large continuous memory space in the memory space.
14. Declare / define a one-dimensional array
Syntax format:
​ int[] array1;
​ double[] array2;
​ boolean[] array3;
15. Initialize one-dimensional array
There are two ways: static initialization of one-dimensional array and dynamic initialization of one-dimensional array.
Static initialization syntax format:
​ int[] array = {100,200,300};
Dynamic initialization syntax format:
int[] array = new int[5]; / / here, 5 represents the number of elements in the array, and the default value of each element is 0
String[] names = new String[6]; / / initialize an array of string type with a length of 6. The default value of each element is null

package array;
/*
Array
    1.Java The array in is a reference data type and does not belong to the basic data type. The parent class of the array is Object
    2.An array is actually a container that can hold multiple elements
    3.The array can store data of basic data type or data of reference data type
    4.Because the array is a reference type, the array object is stored in the heap memory, and the array is stored in the heap
        Person p1 = new Person();
        Person p2 = new Person();
    5.Array in memory:
        If the "java object" is stored in the array, the "reference (memory address)" of the object is actually stored. java objects cannot be directly stored in the array
    6.Once the array is created, the length specified in java is immutable
    7.Array classification: one-dimensional, two-dimensional, three-dimensional, multi-dimensional
    8.All array objects have a length attribute, which is used to get the number of elements in the array
    9.java Arrays in require uniform element types in the array. For example, int type array can only store int and person type can only store person
    10.When the array is stored in memory, the memory addresses of the elements in the array are continuous (each element stored is regularly arranged next to each other), and the memory addresses are continuous
        This is the storage characteristic of array. In fact, array is a simple data structure
    11.All arrays take "the memory address of the first small square" as the first memory address (the memory address of the first element in the array is used as the memory address of the array)
    12.Each element of the array has a subscript, starting from 0, and the last subscript is: length-1
    13.Advantages and disadvantages of array as this data structure:
        Advantages: very efficient when querying / retrieving elements on a subscript. It can be said that it is a data structure with the highest query efficiency
            First: the memory address of each element is continuous in spatial storage
            Second: each element type wants to be the same, so the occupied space is the same
            Third: know the memory address of the first element, the space occupied by each element, and the subscript, so through a mathematical expression
                    The memory address on a subscript can be calculated, so the retrieval efficiency of the array is the highest

            When storing 100 elements or 100w elements in the array, the efficiency is the same when querying elements, because when searching elements in the array
            It won't be found one by one. It is calculated through mathematical expression (direct positioning)

        Disadvantages:
            First: in order to ensure the memory address continuity of each element in the array, it is inefficient to randomly delete or add elements to the array because random addition and deletion
        The element will involve the forward or backward displacement operation of the following elements.
            Second: arrays cannot store large amounts of data, because it is difficult to find a particularly large continuous memory space in the memory space.
    14.Declare / define a one-dimensional array
        Syntax format:
            int[] array1;
            double[] array2;
            boolean[] array3;
    15.Initialize a one-dimensional array
        There are two ways: static initialization of one-dimensional array and dynamic initialization of one-dimensional array.
        Static initialization syntax format:
        int[] array = {100,200,300};
        Dynamic initialization syntax format:
        int[] array = new int[5];//Here, 5 represents the number of elements of the array, and the default value of each element is 0
        String[] names = new String[6];//Initialize an array of String type with a length of 6. The default value of each element is null

 */
public class Test01 {
    public static void main(String[] agrs){
        //Use static initialization, type int
        int[] a1 = {1,2,3,4};
        //Subscript of element in array
        //All array objects have a length attribute
        System.out.println(a1.length);
        System.out.println("First element:" + a1[0]);
        System.out.println("Last element:" + a1[a1.length - 1]);
        System.out.println("------------------------");

        a1[0] = 11;
        a1[a1.length - 1] = 0;
        System.out.println("First element:" + a1[0]);
        System.out.println("Last element:" + a1[a1.length - 1]);
        System.out.println("------------------------");

        for(int i = 0;i<a1.length;i++){
            System.out.println(a1[i]);
        }
        System.out.println("------------------------");
        //System.out.println(a1[5]);//ArrayIndexOutOfBoundsException exception exception

        for(int i = a1.length - 1; i >= 0; i--){
            System.out.println(a1[i]);
        }
    }
}

16. Static initialization mode and dynamic initialization mode are adopted

Static initialization: when you create an array and determine which specific elements are stored in the array, you can use static initialization
Use dynamic initialization: when you create an array and are not sure what specific elements are stored in the array, you can use dynamic initialization

package array;
/*
Default values for each type:
    Data type defaults
    ----------------------------
    byte                    0
    short                   0
    int                     0
    long                    0l
    double                  0.0
    float                   0.0F
    boolean                 false
    char                    \u0000
    Reference data type null

    Static initialization: when you create an array and determine which specific elements are stored in the array, you can use static initialization
    Use dynamic initialization: when you create an array and are not sure what specific elements are stored in the array, you can use dynamic initialization
 */
public class Test02 {
    public static void main(String[] args){
        int[] a = new int[4];//The default value is 0
        for (int i = 0;i< a.length; i++){
            System.out.println(a[i]);
        }
        a[0] = 1;
        a[1] = 2;
        a[2] = 3;
        a[3] = 4;
        //Initializes an array of Object type. The dynamic initialization method is adopted. The default values are null
        System.out.println("-------------");
        Object[] objs = new Object[3];
        for(int i = 0; i<objs.length; i++){
            System.out.println(objs[i]);
        }
        System.out.println("-------------");
        String[] strs = new String[3];
        for(int i = 0; i< strs.length; i++){
            System.out.println(strs[i]);
        }
        System.out.println("-------------");
        String[] strs2 = {"abc","def","ghi"};
        for (int i = 0; i< strs2.length; i++){
            System.out.println(strs2[i]);
        }
        System.out.println("-------------");
        //Store Object
        Object o1 = new Object();
        Object o2 = new Object();
        Object o3 = new Object();
        Object[] objects = {o1,o2,o3};
        for (int i = 0; i< objects.length; i++){
            System.out.println(objects[i]);
        }

    }
}

17. When the parameter type of a method is an array, the parameter transfer method of the method

package array;
//When the type of a method on a parameter is an array.
public class Test03 {
    public static void main(String[] args){
        System.out.println("hello word");
        //Call method to pass array
        int[] x = {1,2,3,4};
        printArray(x);
        System.out.println("-----------------");
        String[] strs = {"abc","def","ghi"};
        printArray(strs);
        System.out.println("-----------------");
        String[] strs2 = new String[6];
        printArray(strs2);

    }
    public static void printArray(int[] array){
        for(int i = 0; i< array.length; i++){
            System.out.println(array[i]);
        }
    }
    public static void printArray(String[] args){
        for(int i = 0; i< args.length; i++){
            System.out.println(args[i]);
        }
    }
}

package array;
/*
When the parameter of a method is an array, it can also be used
 */
public class Test04 {
    public  static  void main(String[] args){
        //initiate static
        int[] a = {1,2,3};
        printArray(a);
        System.out.println("------------------");
        //If you pass a static array directly, the syntax is as follows.
        printArray(new  int[]{1,2,3,});
        //Dynamic initialization of one-dimensional array\
        System.out.println("------------------");
        int[] a2 = new int[4];
        printArray(a2);
        System.out.println("------------------");
        printArray(new int[3]);
    }
    public static void printArray(int[] array){
        for(int i = 0; i< array.length; i++){
            System.out.println(array[i]);
        }
    }
}

18. What is the function of "String[] args" in the main method
When the JVM calls the main method, it will automatically pass a String array.

package array;
/*
1.main What is the role of "String[] args" in the method
    JVM When calling the main method, it will automatically pass a String array.
 */
public class Test05 {
    //When the JVM calls, it must pass a String array
    public static void main(String[] args){
        //The length of the array passed by the JVM by default is 0
        //The test shows that args is not null. Is not an empty reference
        System.out.println("JVM Passed to String Array parameter, the length of this array" + args.length);
        //When will there be values in this array? In fact, this array is reserved for users. Users can enter parameters on the console, and this parameter will be changed
        //Automatically convert to String array
        //For example: java Test02 abc def xyz
        //At this time, the JVM will automatically separate abc def xyz through spaces. After separation, it will be automatically placed in the array String[] args
        //Therefore, the String array above the main method is mainly used to receive user input parameters

        //The array object is created, but there is nothing in the array
        /*String[] strs = new String[0];
        printArray(strs);*/

        for(int i = 0;i < args.length;i++) {
            System.out.println(args[i]);
        }
    }
    public static void printArray(String[] args){
        System.out.println(args.length);
    }

}

19. Simulate a system. If the system is to be used, the user name and password must be entered

package array;
/*
Simulate a system. If the system is to be used, you must enter a user name and password

 */
public class Test06 {
    /*
    User name and password are entered in args
     */
    public static void main(String[] args){
        System.out.println("Please enter your user name and password");
        //When the program runs to this point, the user does provide a user name and password
        //Next, judge whether it is correct

        String username = args[0];
        String password = args[1];

        //Determine whether the strings are equal
        if("admin".equals(username)&&"123".equals(password)){//This writing prevents null pointer exceptions
        //if(username.equals("admin")&&password.equals("123")){
            System.out.println("Login successful");
        }else {
            System.out.println("Login successful");
        }
    }


}

20. Depth of one-dimensional array

Depth of one-dimensional array. The type stored in the array is: reference data type
For arrays, you can only store the memory address of Java objects, and each element stored in the array is a "reference"

package array;
/*
Depth of one-dimensional array. The type stored in the array is: reference data type
 For arrays, you can only store the memory address of Java objects, and each element stored in the array is a "reference"
 */
public class Test07 {
    public static void main(String[] args){
        //Create an array of type Animal
        Animal a1 = new Animal();
        Animal a2 = new Animal();
        Animal[] animals = {a1,a2};
        for(int i = 0; i<animals.length; i++){
            animals[i].move();

        }
        System.out.println("---------------");
        Animal[] ans = new Animal[2];
        ans[0] = new Animal();//Create an Animal object and put it in the first position
        //The Animal array can only store the type of the Animal array, not other types
        //Animal can store Cat type data because Cat is a subclass of animal
        ans[1] = new Cat();

        Animal[] anis = {new Cat(),new Brid()};//The array stores the memory addresses of the two objects
        for(int i = 0; i< anis.length; i++){
            //This may be taken out by Cat or Brid, whether it must be Animal
            //If the method to be called is a method existing in the parent type, it does not need to be transformed downward and can be called directly by the parent type.
            anis[i].move();
            //When calling methods specific to child objects, you need to judge the type
            if (anis[i] instanceof Cat){
                ((Cat) anis[i]).catchMouse();//The parent type needs to be converted to a child type
            }
            if(anis[i] instanceof Brid){
                ((Brid) anis[i]).Sing();
            }
        }
    }
}
class Animal{
    public void move(){
        System.out.println("Animal move");
    }
}

class product{

}
class Cat extends Animal{
    public void move(){
        System.out.println("Cat move");
    }
    public void catchMouse(){
        System.out.println("catch mouse");
    }
}
class Brid extends Animal{
    public void move(){
        System.out.println("Brid move");
    }
    public void Sing(){
        System.out.println("sing");
    }
}

21. Expansion of one-dimensional array

In Java, once the array length is determined to be immutable, the array is full and needs to be expanded.
The expansion of arrays in Java is:
First create a large capacity array, and then copy the elements in the small capacity array to the large array one by one
Conclusion: the efficiency of array expansion is relatively low. Because it involves copying, it is necessary to copy as few arrays as possible in future development,
It is best to accurately estimate the length of the array, which can reduce the number of array expansion and improve efficiency

package array;
/*
On the expansion of one-dimensional array
    In Java, once the array length is determined to be immutable, the array is full and needs to be expanded.
    Java The expansion of the array in is:
        First create a large capacity array, and then copy the elements in the small capacity array to the large array one by one
    Conclusion: the efficiency of array expansion is relatively low. Because it involves copying, it is necessary to copy as few arrays as possible in future development,
    It is best to accurately estimate the length of the array, which can reduce the number of array expansion and improve efficiency
 */

public class Test08 {
    public static void main(String[] args) {
        //How to copy arrays in java?
        //System.arraycopy();5 parameters
        int[] src = {1, 11, 2, 3, 4};
        int[] dest = new int[20];

        //Use the arraycopy method in JDK System class to copy the array
        /*System.arraycopy(src,1,dest,3,2);
        for(int i = 0; i< dest.length;i++){
            System.out.println(dest[i]);
        }*/

        System.arraycopy(src, 0, dest, 0, src.length);
        for (int i = 0; i < dest.length; i++) {
            System.out.println(dest[i]);
        }
        System.out.println("------------");
        String [] strs = new String[5];
        String[] S = {"11","22","33"};
        System.arraycopy(S,0,strs,0,S.length);
        for (int i = 0; i< strs.length;i++){
            System.out.println(strs[i]);
        }

        System.out.println("---------------");
        Object[] objs = {new Object(),new Object(),new Object()};
        Object[] Nobjs = new Object[5];
        System.arraycopy(objs,0,Nobjs,0,objs.length);//Copy memory address
        for (int i = 0; i< objs.length;i++){
            System.out.println(Nobjs[i]);
        }

    }
}

1
11
2
3
4
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
------------
11
22
33
null
null
---------------
java.lang.Object@119d7047
java.lang.Object@776ec8df
java.lang.Object@4eec7777

Process finished with exit code 0

Two dimensional array

1. A two-dimensional array is actually a special one-dimensional array. Each element in this one-dimensional array is a one-dimensional array
2. 3D array is a special 2D array
In the actual development, one-dimensional arrays are used most
3. Static initialization of two-dimensional array
int[][] a = {{},{}};

package array;
/*
About the two-dimensional array in Java, the two-dimensional array is actually a special one-dimensional array
    1.A two-dimensional array is actually a special one-dimensional array. Each element in this one-dimensional array is a one-dimensional array
    2.A 3D array is a special 2D array
        In the actual development, one-dimensional arrays are used most
    3.Static initialization of two-dimensional array
    int[][] a = {{},{}};
 */
public class Test09 {
    public static void main(String[] args){
        //One dimensional array
        int[] array = {100,200,300};
        System.out.println(array.length);
        //Two dimensional array
        int[][] a = {{2,3},
                {4,5,6},
                {7,8,9}};
        System.out.println(a.length);
        System.out.println(a[0].length);

    }
}

4. About reading and changing in two-dimensional array:
a [subscript of one-dimensional array in two-dimensional array] [subscript of one-dimensional array]
a[0] [0]: indicates the first subscript of the first one-dimensional array

package array;
/*
About reading and changing in two-dimensional array:
    a[Subscript of one-dimensional array in two-dimensional array] [subscript of one-dimensional array]
    a[0][0]: Represents the first subscript of the first one-dimensional array
 */
public class Test10 {
    public static void main(String[] args){
        int[][] a={{1,2,3},
                {4,5,6},
                {7,8,9,10}};

        //Take out the first one-dimensional array
        /*int[] aa1 = a[0];
        int aaa1 = aa1[0];
        System.out.println("I am the first element of the first one-dimensional array "+ aaa1);*/

        int aaa1 = a[0][0];
        System.out.println("I am the first element of the first one-dimensional array" + aaa1);

        a[1][1] = 11;
        System.out.println(a[1][1]);
    }
}

5. About reading and changing in two-dimensional array:
a [subscript of one-dimensional array in two-dimensional array] [subscript of one-dimensional array]
a[0] [0]: indicates the first subscript of the first one-dimensional array

package array;
/*
About reading and changing in two-dimensional array:
    a[Subscript of one-dimensional array in two-dimensional array] [subscript of one-dimensional array]
    a[0][0]: Represents the first subscript of the first one-dimensional array
 */
public class Test10 {
    public static void main(String[] args){
        int[][] a={{1,2,3},
                {4,5,6},
                {7,8,9,10}};

        //Take out the first one-dimensional array
        /*int[] aa1 = a[0];
        int aaa1 = aa1[0];
        System.out.println("I am the first element of the first one-dimensional array "+ aaa1);*/

        int aaa1 = a[0][0];
        System.out.println("I am the first element of the first one-dimensional array" + aaa1);

        a[1][1] = 11;
        System.out.println(a[1][1]);
    }
}

6. Traversal of two-dimensional array

package array;
/*
Traversal of two-dimensional array

 */
public class Test11 {
    public static void main(String[] args){
        String[][] a = {
            {"123","456"},
            {"123","456","789"},
            {"123","456","789","1111"}
        };
        for (int i = 0; i< a.length; i++){
            System.out.println();
            for (int j = 0; j< a[i].length; j++){
                System.out.print(a[i][j] + " ");
            }
        }
    }
}

7. Dynamically initialize the two-dimensional array

package array;
/*
Dynamic initialization of two-dimensional array
 */
public class Test12 {
    public static void main(String[] args){
        int[][] a = new int[3][4];
        printArray(a);
        printArray(new int[][]{{1,2,3},
                {4,5,6},
                {7,8,9,10}});
    }
    public static void printArray(int[][] a){
        for (int i = 0; i< a.length; i++){
            System.out.println();
            for (int j = 0; j< a[i].length; j++){
                System.out.print(a[i][j] + " ");
            }
        }
    }
}

Summary:

1.1. Advantages and disadvantages of arrays, and understand why.

First: in spatial storage, memory addresses are continuous.
Second: each element occupies the same size of space.
Third: know the memory address of the first element.
Fourth: the offset can be calculated by subscript.
Through a mathematical expression, the memory address of an element at a subscript position can be quickly calculated,
It is very efficient to locate directly through the memory address.

Advantages: high retrieval efficiency.
Disadvantages: the efficiency of random addition and deletion is low, and the array cannot store a large amount of data.
Note: the addition and deletion efficiency of the last element of the array is not affected.

1.2 static initialization and dynamic initialization of one-dimensional array

Static initialization:
​ int[] arr = {1,2,3,4};
​ Object[] objs = {new Object(), new Object(), new Object()};
Dynamic initialization:
​ int[] arr = new int[4]; // 4 lengths, each element has a default value of 0
​ Object[] objs = new Object[4]; // 4 lengths, and the default value of each element is null

1.3 traversal of one-dimensional array

​ for(int i = 0; i < arr.length; i++){
​ System.out.println(arr[i]);
​ }

1.4 static initialization and dynamic initialization of two-dimensional array

Static initialization:
​ int[][] arr = {
​ {1,2,34},
​ {54,4,34,3},
​ {2,34,4,5}
​ };

​ Object[][] arr = {
​ {new Object(),new Object()},
​ {new Object(),new Object()},
​ {new Object(),new Object(),new Object()}
​ };
Dynamic initialization:
​ int[][] arr = new int[3] [4];
​ Object[][] arr = new Object[4] [4];
​ Animal[][] arr = new Animal[3] [4];
/ / Person type array, which can store Person type objects and subtypes of Person type.
​ Person[][] arr = new Person[2] [2];
​ ...

1.5 traversal of two-dimensional array

For (int i = 0; I < arr.length; I + +) {/ / the outer for loop is responsible for traversing the outer one-dimensional array.
/ / the for loop is responsible for traversing the one-dimensional array in the two-dimensional array.
​ for(int j = 0; j < arr[i].length; j++){
​ System.out.print(arr[i][j]);
​ }
/ / line feed.
​ System.out.println();
​ }

1.6. Use of the "String[] args" parameter on the main method (it's not important to know. Generally, there is an interface in the future. Users can enter parameter information such as user name and password on the interface.)

1.7. Copy of array: use of System.arraycopy() method

An array has one feature: once the length is determined, it is immutable.
Therefore, when the array length is not enough, it needs to be expanded. The expansion mechanism is to create a large array,
Copy the data in the small array to the large array, and then the small array object is garbage collected.

1.8. Be able to draw the memory structure diagram of the reference data type stored in the array.

Array utility class

In fact, algorithms do not need to be proficient in java, because they are already encapsulated in java. To sort, just call methods. For example, java provides an array tool class:
java.util.Arrays
Arrays is a tool class.
There is a sort() method, which can sort static methods. Just call it directly with the class name.

Common data algorithms

Sorting algorithm:
Bubble sort algorithm
Select Sorting Algorithm

Search algorithm:
Dichotomy search

We don't need to use the above algorithms in the actual development of java in the future.
Because java has been encapsulated, just call it directly.
It's just that I may have a chance to meet you during the interview in the future.

Bubble sorting

Data involved in the comparison: 9 8 10 7 6 0 11
1st cycle:

8 9 10 7 6 0 11 (comparison 1: Exchange)
8 9 10 7 6 0 11 (second comparison: no exchange)
8 9 7 10 6 0 11 (3rd comparison: Exchange)
8 9 7 6 10 0 11 (4th comparison: Exchange)
8 9 7 6 0 10 11 (5th comparison: Exchange)
8 9 7 6 0 10 11 (6th comparison: no exchange)

The maximum data that finally pops up is on the right: 11

Data involved in the comparison: 8 9 7 6 0 10
2nd cycle:
8 9 7 6 0 10 (1st comparison: no exchange)
8 7 9 6 0 10 (2nd comparison: Exchange)
8 7 6 9 0 10 (3rd comparison: Exchange)
8 7 6 0 9 10 (4th comparison: Exchange)
8 7 6 0 9 10 (5th comparison: no exchange)

Data involved in the comparison: 8 7 6 0 9
Cycle 3:
7 8 6 0 9 (comparison 1: Exchange)
7 6 8 0 9 (2nd comparison: Exchange)
7 6 0 8 9 (3rd comparison: Exchange)
7 6 0 8 9 (4th comparison: no exchange)

Data involved in the comparison: 7 6 0 8
Cycle 4:
6 7 0 8 (comparison 1: Exchange)
6 0 7 8 (2nd comparison: Exchange)
6 0 7 8 (3rd comparison: no exchange)

Data involved in the comparison: 6 0 7
Cycle 5:
0 6 7 (comparison 1: Exchange)
0 6 7 (2nd comparison: no exchange)

Data involved in comparison: 0 6
Cycle 6:
0 6 (1st comparison: no exchange)

for (int i = 0;i<arr.length-1;i++){
    for (int j = 0;j<arr.length-1-i;j++){
    }
}
package array;
/*
Bubbling algorithm
 Original: 3 2 7 6 8
 Compare 3 with 2 on the right. If left > right, swap positions
 First time: 2 3 7 6 8
 Take the larger data on the right after the last comparison result and continue to compare with the subsequent data
 Second time: 2 3 7 6 8
 Third time: 2 3 6 7 8
 Fourth: 2 3 6 7 8


 */
public class BubbleSort {
    public static void main(String[] args){
        int[] arr = {9,8,10,7,6,0,11};
        int temp;
        //After bubble sorting algorithm, sort
        for (int i = 0;i<arr.length-1;i++){
            for (int j = 0;j<arr.length-1-i;j++){
                if (arr[j]>arr[j+1]) {
                    temp = arr[j + 1];
                    arr[j + 1] = arr[j];
                    arr[j] = temp;
                }
            }
        }
        for (int i = 0;i<arr.length;i++){
            System.out.print(arr[i]);
        }

    }
}

Select sort

Selective sorting is more efficient than bubble sorting.
High in the number of switching positions.
It makes sense to choose the swap location for sorting.

Loop once, then find the smallest of the pile of data participating in the comparison, and take the sum of the smallest value
The first data "exchange location".

Data involved in the comparison: 3 1 6 2 5 (the index of the leftmost element in this pile of data involved in the comparison is 0)
The result after the first cycle is:
1 3 6 2 5

Data involved in the comparison: 3 6 2 5 (the index of the leftmost element in this pile of data involved in the comparison is 1)
The result after the second cycle is:
2 6 3 5

Data involved in the comparison: 6 3 5 (the index of the leftmost element in this pile of data involved in the comparison is 2)
The result after the third cycle is:
3 6 5

Data participating in the comparison: 6 5 (the index of the leftmost element in this pile of data participating in the comparison is 3)
The result after the 4th cycle is:
5 6

Note: 5 pieces of data, 4 cycles.

binary search

First: dichotomy search is based on sorting.
Second: the efficiency of binary search is higher than that of "one by one".
Third: dichotomy search principle?
10 (0 subscript) 23 56 89 100 111 222 235 500 600 (subscript 9) arr array

Objective: find the subscript of 600
(0 + 9) / 2 -- > 4 (subscript of intermediate element)

The element arr[4] is the intermediate element: arr[4] is 100
​ 100 < 600
Indicates that the element to be found is on the right of 100.
Then the subscript becomes: 4 + 1

(5 + 9) / 2 -- > 7 (subscript of intermediate element)
arr[7] corresponds to: 235
​ 235 < 600
Indicates that the element to be searched is on the right of 235.

At the beginning, the subscript has changed again: 7 + 1
​ (8 + 9) / 2 --> 8
​ arr[8] --> 500
​ 500 < 600
The subscript of the start element has changed again: 8 + 1
​ (9 + 9) / 2 --> 9
arr[9] is 600, which is exactly equal to 600. At this time, it is found.

package array;


/*
binary search 
10 11 12 13 14 15 16 17 18 19
 Find the subscript of 18 this element by dichotomy:
    (0+10)/5------> Subscript of intermediate element

    Compare the middle element with the target element:
    The intermediate elements are: arr [5] - > 15
    15 < 18 The element to be found is to the right of the middle element
    So the subscript of the starting element changes from 0 to 5 + 1

   In recalculating intermediate element subscripts:
    5+1+10 / 2 = 8
    8 The element corresponding to the subscript is 18. It is found that the intermediate element is equal to the found element, and the subscript is 8

    The binary search element algorithm is based on sorting, and the data without sorting cannot be found
 */
public class TwoSaerch {

    public static void main(String[] args){
        int[] arr = {100,200,300,235,600,1000,2000,9999};
        //Dichotomy search 200
        int index = binarySearch1(arr,2000);
        System.out.println(index == -1? "The element does not exist":"This element is shown in the following table:" + index);
    }

    private static int binarySearch1(int[] arr, int n) {
        boolean flag = false;
        int start = 0;
        int end = arr.length - 1;
        while(start <= end){
            int mid = (start + end) / 2;
            if(arr[mid] == n){
                return mid;
            }else if(arr[mid] < n){
                start = mid +1;
            }else if (arr[mid] > n){
                end = mid -1;
            }
        }
        return -1;
    }

}

Introduce the java.util.Arrays tool class

All methods are static and are called directly with the class name
Two methods are mainly used:
Dichotomy, find, sort
In the future, you should read the documents and don't memorize them by rote.

package array;

import java.lang.reflect.Array;
import java.util.Arrays;

/**
 * SUN The company has written an array tool class for us
 * java.util.Array
 *
 */
public class ArrayTest02 {
    public static void main(String[] args){
        int arr[] = {1,5,7,4,3,4};
        Arrays.sort(arr);
        for (int i = 0; i< arr.length ; i++){
            System.out.print(arr[i] + " ");

        }
        System.out.println("----------------");
        //binary search 
        int index = Arrays.binarySearch(arr,4);
        System.out.println(index == -1? "The element does not exist":"The subscript of this element is:" + index);

    }
}

Common class

String class

Why is String immutable?

There is a byte [] array in the String class. This byte [] array is decorated with final. Once the array is created, the length is immutable, and the reference decorated with final points to an object, it can no longer point to other objects. Therefore, String is immutable!

Understanding of String in memory

1.String indicates string type, which belongs to reference data type, not basic data type
2. In Java, String objects are casually enclosed in double quotation marks. For example, "abc", "def" and "hello world" are three String objects
3.Java stipulates that strings enclosed in double quotation marks are immutable, that is, "abc" cannot become "abcd" from the beginning to the end“
4. In JDK, strings enclosed in double quotation marks are directly stored in the "string constant pool" in the "method area"
Why does sun Store strings in a "string constant pool"? Because strings are used too often in actual development, they are put into a "string constant pool" for execution efficiency
The string constant pool in the method area.

package javaseString;
/*
About String
    1.String Represents a string type, which belongs to the reference data type and does not belong to the basic data class
    2.In Java, String objects are casually enclosed in double quotation marks. For example, "abc", "def","hello world", these three String objects
    3.Java It is stipulated that the string enclosed in double quotation marks is immutable, that is to say, "abc" cannot become "abcd" from the beginning to the end“
    4.In JDK, strings enclosed in double quotation marks are directly stored in the "string constant pool" in the "method area"
     Why does sun Store strings in a "string constant pool"? Because strings are used too often in actual development, they are put into a "string constant pool" for execution efficiency
     The string constant pool in the method area.
 */
public class Test01 {
    public static void main(){
        String s1 = "abcd";
        String s2 = "abcd"  +"xy";
        //Use the new method to build a string object
        //All objects enclosed in double quotation marks have a copy in the string constant pool, and all new objects open up space in heap memory
        String s3 = new String("xy");
        
    }
}

package javaseString;

public class UserTest {
    public static void main(String[] args){
        User user = new User(110,"x");
        
    }
}
class User{
    private int id;
    private String name;
    public User(){

    }

    public User(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public void setId(int id) {
        this.id = id;
    }

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

package javaseString;

public class Test02 {
    public static void main(String[] args){
        String s1 = "hello";
        //"hello" is a string constant pool stored in the method area
        //So this "hello" will not be rebuilt
        String s2 = "hello";
        System.out.println(s1 == s2);//true

        String x = new String("xy");
        String y = new String("xy");
        System.out.println(x==y);//false
        //The String class has overridden the equals method
        System.out.println(x.equals(y));//true

        String k = new String("Test");
        //"Test" is a String object. Any object can call a method
        System.out.println("Test".equals(k));//This is recommended to avoid null pointer exceptions
        System.out.println(k.equals("Test"));
    }
}

package javaseString;
/*
Analyze how many objects the program created
 */
public class Test03 {
    public static void main(String[] args){
        /*
        There are three objects:
            The string constant pool has an object
            There are two String objects in heap memory
         */
        String s1 = new String("hello");
        String s2 = new String("hello");
    }
}

On the construction method in String class

  • String s = new String("");
  • String s = ''; most commonly used
  • String s = new String(char array);
  • String s = new String(char array, starting subscript, length)
  • String s = new String(byte array);
  • String s = new String(byte array, starting subscript, length)
package javaseString;

/**
 * On the construction method in String class
 * String s = new String("");
 * String s = ""; Most commonly used
 * String s = new String(char Array);
 * String s = new String(char Array, starting subscript, length)
 * String s = new String(byte Array);
 * String s = new String(byte Array, starting subscript, length)
 */
public class Test04 {
    public static void main(String[] args){
        //The most common way to create strings
        //Only the common construction methods are mastered here
        String s1 = "hello world";
        //The String class has overridden the toString method
        System.out.println(s1);
        byte[] bytes = {97,98,99};//97a 98b 99c
        String s2 = new String(bytes);//Support passing in byte array
        //When outputting a reference, the toString method will be automatically. By default, the memory address of the Object will be automatically output
        System.out.println(s2);//abc
        //From the output results, we can draw a conclusion that the String class has overridden the toString method.
        //When outputting a string object, the output is not the memory address of the object, but the string itself.

        //String (byte array, starting position, length)
        //Convert a part of the bytes array
        String s3 = new String(bytes,1,2);//1 is the starting subscript and 2 is the length
        System.out.println(s3);

        //Convert all char arrays to strings
        char[] chars = {'1','2','3','4'};
        String s5 = new String(chars);
        System.out.println(s5);
        String s4 = new String(chars,1,2);
        System.out.println(s4);

    }
}

21 common methods of String class

1.char charAt(int index)

2.compareT(String aontherString) returns an int

3.boolean contains(CharSequence s)

/ / judge whether the preceding string contains the following substring

4.boolean endsWith(String suffix)

/ / judge whether the current string ends with a string

5.boolean equals(String anotherString)

//Whether the equals method calls CompareTo. The compareTo() method is not called in the new version of JDK

6.boolean equalsIgnoreCase(String anotherString)

//Judge whether two strings are equal, ignoring case

7.btye[] getBytes()

/ / convert string object to byte array

8.int indexOf(String str)

//Determines the index of the first occurrence of a substring in the current string

9.boolean isEmpty()

//Determine whether a string is empty
//The underlying source code calls the length method of the character

10.int length()

/ / interview question: judge whether the length of array is different from that of string
/ / judge whether the array length is the length attribute and the string length is the length method

11.lastIndexOf(int ch)

/ / the last index position of the character

12.String replace(CharSequence traget,CharSequence replacement)

/ / replace the specified string
/ / the parent interface of String is CharSequence

13.String[] split(String regex)

/ / split string

14.boolean startsWith(String perfix)

/ / judge whether a string starts with a substring

15.String substring(int beginIndex)

/ / intercept string

16.String substring(int beginIndex, int endIndex) / / left closed right open

17.char[] toCharArray()

/ / convert string to char array

18.String toLowerCase()

Convert to lowercase

19.String toUpperCase()

20.String trim()

Remove whitespace before and after string

21. Only one method in string is static and does not need a new object

package javaseString;

import javax.crypto.spec.PSource;
import java.nio.charset.StandardCharsets;
import java.util.Locale;

public class Test05 {
    public static void main(String[] args){
        //Common methods in String class
        //1.char charAt(int index)
        char c= "Chinese".charAt(1);
        System.out.println(c);//an exporter

        //2.compareT(String aontherString) returns an int
        System.out.println("abc".compareTo("abc"));//0 equal
        System.out.println("abcd".compareTo("abce"));//-1 front small rear large
        System.out.println("abce".compareTo("abcd"));//1 large front and small rear
        System.out.println("xyz".compareTo("yxz"));//-1

        //3.boolean contains(CharSequence s)
        //Judge whether the preceding string contains the following substring
        System.out.println("HelloWorld.java".contains(".java"));//true
        System.out.println("1111111".contains("2"));//false

        //4.boolean endsWith(String suffix)
        //Determines whether the current string ends with a string
        System.out.println("test.txt".endsWith(".txt"));//true
        System.out.println("test.txt".endsWith(".java"));//false

        //5.boolean equals(String anotherString)
        System.out.println("11".equals("11"));//true
        //Whether the equals method calls CompareTo. The compareTo() method is not called in the new version of JDK

        //6.boolean equalsIgnoreCase(String anotherString)
        //Judge whether two strings are equal, ignoring case
        System.out.println("abc".equalsIgnoreCase("ABC"));//true

        //7.btye[] getBytes()
        //Converts a string object to a byte array
        byte[] b = "abcdf".getBytes(StandardCharsets.UTF_8);
        for (int i = 0;i<b.length;i++){
            System.out.print(b[i] +" ");
        }
        System.out.println();

        //8.int indexOf(String str)
        //Determines the index of the first occurrence of a substring in the current string
        System.out.println("abcd".indexOf("b"));

        //9.boolean isEmpty()
        //Determine whether a string is empty
        //The underlying source code calls the length method of the character
        System.out.println("11".isEmpty());//false
        System.out.println("".isEmpty());//true

        //10.int length()
        //Interview question: the length of judgment array is different from that of judgment string
        //The length attribute is used to determine the length of the array, and the length method is used to determine the length of the string
        String s = "a";
        System.out.println(s.length());//String. length() method

        //11.lastIndexOf(int ch)
        //Index position of the last occurrence of the character
        System.out.println("12345996789".lastIndexOf("9"));

        //12.String replace(CharSequence traget,CharSequence replacement)
        //Replace the specified string
        //The parent interface of String is CharSequence
        String newString = "11112222".replace("1111","2222");
        System.out.println(newString);//22222222

        //13.String[] split(String regex)
        //Split string
        String[] s1 = "1998-1-0".split("-");//Split 1998-1-0 with -
        for (int i =0;i<s1.length;i++){
            System.out.print(s1[i] + " ");//1998 1 0
        }
        System.out.println();

        //14.boolean startsWith(String perfix)
        //Determines whether a string starts with a substring
        System.out.println("111111223334456".startsWith("11"));//true
        System.out.println("45678911".startsWith("11"));//flase

        //15.String substring(int beginIndex)
        //Intercept string
        System.out.println("123456789987".substring(7));//The parameter is the starting subscript

        //16.String substring(int beginIndex,int endIndex)
        System.out.println("123456789987456".substring(7,10));//Left closed right open 7 not 10

        //17.char[] toCharArray()
        //Convert string to char array
        char[] chars = "I am Chinese,".toCharArray();
            for (int i =0;i<chars.length;i++){
                System.out.print(chars[i] + " ");//I am Chinese,
            }
        System.out.println();


        //18.String toLowerCase()
        //Convert to lowercase
        System.out.println("ABCDEF".toLowerCase(Locale.ROOT));//abcdef

        //19.String toUpperCase()
        System.out.println("abcdfe".toUpperCase(Locale.ROOT));//ABCDFE

        //20.String trim()
        //Remove whitespace before and after string
        System.out.println("  123 456 789  ".trim());//123 456 789

        //21. Only one method in string is static and does not need a new object
        //valueOf
        //Convert non string to string
        String s2 = String.valueOf(true);//true string
        System.out.println(s2);
        String s3 = String.valueOf(100);//100 string
        System.out.println(s3);

        String s4 = String.valueOf(new C());
        System.out.println(s4);//obj.toString does not override the memory address of the object before the toString method

        //println source code
        //The underlying called the toString method
        Object obj = new Object();
        System.out.println(obj);
        /*
        String s = String.valueOf(x);

        public static String valueOf(Object obj) {
        return (obj == null) ? "null" : obj.toString();
        }
         */

        //In essence, System.out.println(), when outputting any data, this method converts it into a string and outputs it
        System.out.println();

    }
}
class C{

    //Override toString
    public String toString(){
        return "vip";
    }

}

StringBuffer and StringBuilder

Why are StringBuffer and StringBuilder mutable?

The inside of StringBuffer and StringBuffer is actually a byte [] array. This byte [] array is not modified by final. The initialization capacity of StringBuilder and StringBuffer is 16. When they are full, they will be expanded. The bottom layer calls the array copy method System.arrarycopy(). Therefore, StringBuilder/StringBuffer is suitable for frequent string splicing.

In the actual development, what problems will occur in frequent string splicing?
* java The string of is immutable. Each splicing will produce a new string, which will occupy a lot of methods to memory, resulting in a waste of memory space
*  String s = "abc";
*  s += "hello"
*  The above two lines of code result in the creation of three string objects in the string constant pool in the method area

1.StringBuffer/StringBuilder can be regarded as a variable length string.
2.StringBuffer/StringBuilder initialization capacity 16
3.StringBuffer/StringBuilder is used to complete string splicing. Method name: append
4.StringBuffer is thread safe. StringBuilder is non thread safe.
5. It is not recommended to use "+" for frequent string splicing

package StringBuffer;
/**
 * In the actual development, what problems will occur in frequent string splicing?
 * java The string of is immutable. Each splicing will produce a new string, which will occupy a lot of methods to memory, resulting in a waste of memory space
 *  String s = "abc";
 *  s += "hello"
 *  The above two lines of code result in the creation of three string objects in the string constant pool in the method area
 */

/**
 * If you want to splice strings in the future, it is recommended to use the built-in in JDK:
 *      java.lang.StringBuffer/StringBuilder
 * Optimize StringBuffer performance
 *      When creating a StringBuffer, try to give an initialization capacity
 *       It's best to reduce the expansion times of the underlying array and pre estimate it
 *       Key point: given an appropriate initialization capacity, the efficiency of the program can be improved
 *
 */
public class Test01 {
    public static void main(String[] args) {
        //The direct use of + = will put a lot of pressure on the string constant pool in the method area
        //Create an array with an initialization capacity of 16 byte s []
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("a");
        stringBuffer.append("b");
        stringBuffer.append("c");
        System.out.println(stringBuffer);
        //The StringBuffer will be automatically expanded

        //Initializes the StringBuffer of the specified capacity

        StringBuffer stringBuffer1 = new StringBuffer(100);
        stringBuffer1.append("1");
        stringBuffer1.append("2");
        stringBuffer1.append("3");
        stringBuffer1.append("4");
        System.out.println(stringBuffer1);


    }
}

package StringBuffer;

/**

 * StringBuilder
 * StringBuffer Difference between and StringBuilder
 * StringBuffer The methods in are decorated with the keyword synchronized, which means that StringBuffer is safe to run in a multithreaded environment
 * StringBuilder None of the methods in have the keyword synchronized modifier, indicating that StringBuilder is unsafe to run in a multithreaded environment.
   *
 * StringBuffer Is thread safe
 * StringBuilder Is non thread safe
   */
   public class Test02 {
   public static void main(String[] args) {
       //The less expansion times, the higher the efficiency
       StringBuilder stringBuilder = new StringBuilder();
       stringBuilder.append("1");
       stringBuilder.append("2");
       stringBuilder.append("3");
       stringBuilder.append("4");
       System.out.println(stringBuilder);



    }
}

Packaging classes corresponding to eight basic data types

1. In Java, 8 packing types are prepared for 8 basic data types.

The wrapper class in 8 belongs to the reference data type, and the parent class is Object

2. Why do you provide 8 kinds of packaging?

Because the eight basic data types are not enough

3. Correspondence between basic data type and packaging class

Basic data types: byte, short, int, long, float, double, boolean, char
8 packing types: Byte, Short, Integer, Long, plot, double (the parent class is Number), Boolean, Character (the parent class is Object)

6 of the packaging classes in 4.8 are corresponding to numbers, and their parent class is Number. You can first study the public methods in Number:

Number is an abstract class and cannot instantiate an object
There are such methods in the Number class:
byte byteValue() returns the specified value in byte.
abstract double doubleValue() returns the specified value as a double.
abstract float floatValue() returns the specified value as float.
abstract int intValue() returns the specified value as int.
abstract long longValue() returns the specified value as a long.
Short shortvalue() returns the specified value in the form of short.
These methods are responsible for unpacking [converting reference data types to basic data types]

5. Packing and unpacking

package Integer;
/*
There are two construction methods for Integer class:
    Integer(int)
    Integer(String)

 */
public class Test02 {
    public static void main(String[] args) {
        //Converts the number 100 to the Integer type
        Integer x = new Integer(100);
        System.out.println(x);
        //Convert string 123 to Integer type
        Integer y = new Integer("123");
        System.out.println(y);

        Double d = new Double(1.23);
        System.out.println(d);
        Double e = new Double(1);
        System.out.println(e);
    }
package Integer;
/*
After JDK1.5, it supports automatic unpacking and automatic packing
 */
public class Test04 {
    public static void main(String[] args) {
       Integer x = 100;//Auto boxing int type is automatically converted to Integer
       int y = x;//Automatic unpacking Integer is automatically converted to int
    }
}

Integer constant pool

In java, in order to improve the efficiency of program execution, all wrapper objects between - 128-127 are created in advance
Put it into the integer constant pool in the method area. The purpose is to directly get the data from the integer constant pool as long as you use this interval, and you don't need to be in new

Summary of exceptions encountered

Null pointer exception: NullPointerException
Type conversion exception: ClassCastException
Array index out of bounds exception: ArraryIndexOutOfBoundsException
Array formatting exception: NumberFormatException

package Integer;
/*
Summarize the exceptions encountered:
    Null pointer exception: NullPointerException
    Type conversion exception: ClassCastException
    Array index out of bounds exception: ArraryIndexOutOfBoundsException
    Array formatting exception: NumberFormatException
 */
public class Test05 {
    public static void main(String[] args) {
        Integer x = 100;
        int y = x;
        System.out.println(y);
        Integer z = new Integer("123");//The string must be a string of numbers, otherwise an array formatting exception will occur: NumberFormatException
        System.out.println(z);

        //Key methods
        //static int parseInt(String s)
        //Static method, pass parameter String and return int
        int retValue = Integer.parseInt("123");//String ---> int
        System.out.println(retValue);

        double retValue2 = Double.parseDouble("3.14");
        System.out.println(retValue2);

        float retValue3 = Float.parseFloat("1.0");
        System.out.println(retValue3);
    }
}

String int Integer type conversion

package Integer;

import java.io.StringWriter;

public class Test08 {
    public static void main(String[] args) {

        String s1 = "100";
        int i1 = Integer.parseInt(s1);//String --> int
        System.out.println(i1);
        String s2 = i1 + ""; //int --> String
        System.out.println(s2 +1);

        Integer x = 1000;
        int y = x; //Automatic packing and unpacking

        String s3 = "123";
        Integer k = Integer.valueOf(s3); //Integer ---> String

        Integer l = 123;
        String s4 = String.valueOf(l);//String --> Integer

    }
}

Date class

1. How to obtain the current system time

2.Date --> String

3.String --> Date

package Data;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/*
java Processing of dates in
    1.How to get the current system time
    2.Date  -->  String
    3.String -->  Date
 */
public class Test01 {
    public static void main(String[] args) throws ParseException {
        //Gets the time of the current system
        Date nowTime = new Date();
        System.out.println(nowTime); //Mon Aug 09 09:44:49 CST 2021

        //Date format: convert the date according to the specified format
        //Convert the date in the specified format: date -- > string
        //SimpleDateFormat is dedicated to date formatting
        /**
         * yyyy year
         * MM   month
         * dd   day
         * HH   Time
         * mm   branch
         * ss   second
         * SSS  millisecond
         * Note: in the date format, except for Y M D H M s, the rest of the symbol formats can be organized at will
         */
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss-SSS");
        String nowTimeStr = sdf.format(nowTime);
        System.out.println(nowTimeStr);

        //How to convert a Date String to a Date String
        String time = "2020-01-01 00:08:08:888";
        //Note: the date format of the string should be the same as that specified by the SimpleDateFormat object, otherwise an exception PareException will occur
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
        Date dateTime = sdf2.parse(time);
        System.out.println(dateTime);

    }
}

Execution time of statistical method

package Data;
/*
The total number of milliseconds from 00:00:000 on January 1, 1970 to the current system time
 Briefly summarize the related properties and methods of the System class:
    System.out out Is a static variable of System
    System.out.println() println()Method is not of System class, but of PrintStream class
    System.gc() It is recommended to start the garbage collector
    System.currentTimeMillis() The total number of milliseconds from 00:00:000 on January 1, 1970 to the current system time
    System.exit(0)  Exit JVM
 */
public class Test02 {
    public static void main(String[] args) {
        long nowTimeMillis = System.currentTimeMillis();
        System.out.println(nowTimeMillis);

        //Time consuming statistics of a method
        //Record a number of milliseconds before calling the target method
        long begin = System.currentTimeMillis();
        System.out.println(begin);
        print();
        //The number of milliseconds after executing the call
        long end = System.currentTimeMillis();
        System.out.println(end - begin);
    }

    //Requirement: count the time spent in the execution of a method
    public static void print(){
        for (int i = 0; i < 1000; i++){
            System.out.println("i = " + i);
        }

    }
}

package Data;
import java.text.SimpleDateFormat;
import java.util.Date;
/*

 */
public class Test04 {
    public static void main(String[] args) {
        //This time is: 1970-01-01 00:00:00:001
        Date time = new Date(1);//Note that the parameter is 1 millisecond 4
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
        String strTime = sdf.format(time);
        System.out.println(strTime);

        //Get the time of yesterday at this time
        Date time1 = new Date(System.currentTimeMillis() - (1000 * 60 *60 *24));
        String strTime2 = sdf.format(time1);
        System.out.println(strTime2);

    }
}

Digital class

DecimalFormat number formatting

package Numbers;
import java.text.DecimalFormat;
public class DecimalFormatTest01 {
    public static void main(String[] args) {
        //Responsible for digital formatting
        //DecimalFormat df = new DecimalFormat("number format");
        /**
         * What are the number formats
         * #Represents any number
         * ,Represents the thousandth
         * .Represents decimal
         *
         * ###,###,##
         *      Means: add the thousandth place and keep 2 decimals
         */
        DecimalFormat df = new DecimalFormat("###,###.##");
        String s = df.format(1234.56);
        System.out.println(s);
        DecimalFormat df2 = new DecimalFormat("###,###. 0000 "); / / keep 4 decimals, not enough to make up 0
        String s2  =df2.format(1234.56);
        System.out.println(s2);

    }
}

BigDecimal is big data with high precision

BigDecimal with high precision is used in the design of financial software

package Numbers;

import java.math.BigDecimal;

/*
1.BigDecimal It belongs to big data with high precision. It is not a basic data type, but a java object (reference data)
This is a class provided by SUN. It is specially used in financial software
2.Note: Double is not enough in financial software
    The financial data is java.math.BigDecimal
 */
public class BigDecimalTest01 {
    public static void main(String[] args) {
        //This 100 is not an ordinary 100, but a 100 with high precision
        BigDecimal v1 = new BigDecimal(100);
        BigDecimal v2 = new BigDecimal(200);
        //Sum
        //v1 + v2 are all reference data types. This syntax cannot be used
        //Call method summation
        BigDecimal v3 =v1.add(v2);
        System.out.println(v3);

        BigDecimal v4 = v2.divide(v1);
        System.out.println(v4);
    }
}

Random generates random numbers

How to generate random numbers of type int.

​ Random r = new Random();
​ int i = r.nextInt();

How to generate random numbers of type int within a certain range.

​ Random r = new Random();
int i = r.nextInt(101); / / generate a random number of [0-100].

package Numbers;

import java.util.Random;
import java.util.Arrays;

/*
Write a program to generate 5 non repeated random numbers. If repeated, regenerate
 Finally, the five random numbers generated are put into the array. It is required that these five random numbers are not repeated
 */
public class RandomTest02 {
    public static void main(String[] args) {
        //Prepare a one-dimensional array with a length of 5
        int[] arr = new int[5];
        for (int i =0; i< 5 ; i++){
            arr[i] = -1;
        }
        int index = 0;
        //loop
        Random random = new Random();
        while(index < arr.length){
            int res = random.nextInt(101);
            boolean flag = flag(arr,res);
            if (!flag){
                arr[index++] = res;


            }
        }
        for (int i =0;i<arr.length;i++){
            System.out.println(arr[i]);
        }
    }
    public static  boolean flag(int[] arr,int res) {
        /*
        There is a bug in this method. Half of the data can't be used
        //sort
        Arrays.sort(arr);
        //Dichotomy finds the subscript of the element
        int index = Arrays.binarySearch(arr, res);

        return index >0 ;//Prove existence
        */

        for (int i = 0;i<arr.length;i++){
            if (arr[i] ==res){
                return true;
            }
            return false;
        }
        return false;
    }

}

Enum enumeration type

Enumeration is a reference data type.
Enumeration is also a class file after compilation.
How are enumeration types defined?

enum enumeration type name{

Enumeration value, enumeration value 2, enumeration value 3
​ }

Enumeration usage

When a method has more than two execution results and can be enumerated one by one, it is recommended that the return value type be designed as enumeration type.

package enumlei;//Keywords cannot be used as identifiers
/*
Analyze the defect of the following program without using enumeration type
    The following program can be compiled and run. There is no problem with the program itself
    Design defect: the return value type of this method is inappropriate. This method only returns success and failure. It is best to return Boolean type. The return value has deviated from the requirements.


 */
public class Test01 {
    public static void main(String[] args) {
        boolean res = divide(10,2);
        System.out.println(res);

       boolean res2 = divide(10,0);
       System.out.println(res2);
    }

    /**
     * The following program calculates the quotient of two int types. If the calculation succeeds, it returns 1 and if the calculation fails, it returns 0
     * @param a
     * @param b
     * @return 1 means success and 0 means failure
     */
    /*
    public static int divide(int a,int b){
        try{
            int c= a/b;
            return 1;//Indicates successful execution
        }catch (Exception e){
            return 0;//Indicates execution failure
        }
    }*/
    public static boolean divide(int a,int b) {
        try {
            int c = a / b;
            return true;//Indicates successful execution
        } catch (Exception e) {
            return false;//Indicates execution failure
        }
    }
    /*
    Thinking: there is nothing wrong with the above method design, but in the future development process, there may be a method execution result, which may include several situations
    At this time, Boolean types cannot meet the requirements, which requires the use of enumeration types in java
     */
}

package enumlei;
/*
Enumeration:
1.Enumeration is a reference data type
2.How are enumerations defined
    enum Enumeration type name{
        Enumeration value 1, enumeration value 2
    }
3.Boolean types are recommended for only two types and enumeration types are recommended for more than two types
 */
public class Test02 {
    public static void main(String[] args) {
        Result r = divide(10,2);
        System.out.println(r == Result.SUCCESS? "Sucess":"Fail");

    }

    /**
     *
     * @param a
     * @param b
     * @return Returns the enumeration type. SUCCESS indicates SUCCESS and FAIL indicates failure
     */
    public static Result divide(int a,int b ){
        try{
            int c = a/b;
            return Result.SUCCESS;
        }catch(Exception e){
            return Result.FAIL;
        }
    }
}
//enumeration
enum Result{
    //After the enumeration is compiled successfully, the class file is also generated
    //Enumeration is also a reference data type
    //Each value in the enumeration can be regarded as a constant
    //SUCCESS is a value in the enumeration class
    //FAIL is also a value in the enumeration
    SUCCESS,FAIL
}

Exception class

Exception handling mechanism

0.1. The function of exceptions in java is to enhance program robustness.
0.2. Exceptions in java exist in the form of classes and objects.

1. What is an exception? What is the use of the exception handling mechanism provided by java?

Abnormal conditions occur during the execution of the following programs, which are called exceptions
The java language is very perfect and provides an exception handling method. If the following program is abnormal, java prints the exception information,
After the programmer sees the exception information, he can modify the program to make the program more robust

2. The following program execution console appears:

​ Exception in thread "main" java.lang.ArithmeticException: / by zero
at exception.Test01.main(Test01.java:7)
This information is called exception information, which is printed by the JVM

package exception;
/*
1.What is an exception? What is the use of the exception handling mechanism provided by java?
    Abnormal conditions occur during the execution of the following programs, which are called exceptions
    java The language is very perfect and provides an exception handling method. If the following program is abnormal, java prints the exception information,
    After the programmer sees the exception information, he can modify the program to make the program more robust
2.The following program execution console appears:
    Exception in thread "main" java.lang.ArithmeticException: / by zero
	at exception.Test01.main(Test01.java:7)
	This information is called exception information, which is printed by the JVM
 */
public class Test01 {
    public static void main(String[] args) {
       /* int a =10;
        int b =0;
        int c= a/b; // In fact, when the JVM executes here, it will new an exception object
        System.out.println(c);*/

    }
}

3. What forms do exceptions exist in the Java language

Exceptions exist in the form of classes in Java. Each exception class can create an exception object

package exception;

import lei.NullPointerTest;

/*
Java What forms do exceptions exist in language
    Exceptions exist in the form of classes in Java. Each exception class can create an exception object
    
 */
public class Test02 {
    public static void main(String[] args) {
        NumberFormatException nfe = new NumberFormatException("Number format exception");
        //toString is also called
        System.out.println(nfe);
        //Create an exception object through the exception class
        NullPointerException npe = new NullPointerException("Null pointer exception");
        System.out.println(npe);
    }
}

4.java exception inheritance structure

Exceptions exist as classes and objects in java. So what is the inheritance structure of exceptions?
We can use UML diagrams to describe the inheritance structure.
There are many tools for drawing UML diagrams, such as Rational Rose (paid), starUML, etc
Object
Throwable under Object
There are two branches under Throwable: Error (unprocessable, exit JVM directly) and Exception (treatable)
There are two branches under Exception:
The direct subclass of Exception: compile time exceptions (programmers are required to handle these exceptions in advance at the programming stage. If they do not handle compiler errors, they are named compile time exceptions).
RuntimeException: runtime exception. (in the programming stage, the programmer can process it in advance or ignore it.)

5. Compile time exception and runtime exception

Both compile time exceptions and run-time exceptions occur in the run-time phase. Compile time exceptions do not occur.

What is the name of compile time exception?

Because compile time exceptions must be handled in advance at the compilation (writing) stage, they are named if compiler errors are not handled. All exceptions occur during the run phase. Because only the program running stage can new objects. Because the occurrence of an exception is the new exception object.

The difference between compile time exceptions and runtime exceptions

Compile time exceptions generally have a high probability of occurrence. Some exceptions with high probability need to be preprocessed before running.

The probability of runtime exceptions is generally low.

Assuming that java does not divide exceptions into compile time exceptions and run-time exceptions, what effect will it have if all exceptions need to be preprocessed at the programming stage?
First of all, if so, the program must be absolutely safe. But programmers are too tired to write programs, and the code is full of exception handling code.

Compile time exception has other names: checked exception: CheckedException controlled exception
Runtime exception has other names: unchecked exception: UnCheckedException uncontrolled exception

6. Two methods of exception handling in Java

The first method: use the throws keyword to throw it to the upper level at the position of the method declaration.
I'll throw it to whoever calls me. Throw it to the next level.

The second way: use the try... Catch statement to catch exceptions. No one knows what happened because I caught it.

for instance:
I am a salesman of a group. My mistake caused the company to lose 1000 yuan,
"Loss of 1000 yuan" can be regarded as an exception. I have two ways to deal with it,
The first way: I told my leader about it [abnormal throwing up]
The second way: I make up the money out of my own pocket. [exception capture]

reflection:
After the exception occurs, if I choose to throw it up and give it to my caller, and the caller needs to continue processing the exception, the caller can handle the exception in the same two ways.

Note: after an exception occurs in Java, if it is thrown up, it is finally thrown to the main method. The main method continues to throw up and is thrown to the caller JVM. The JVM knows that the exception occurs and has only one result. Terminate the execution of a java program.

package exception;

public class Test03 {
    public static void main(String[] args) {
        System.out.println(100/0);
        /*
        When the program is executed here, an ArithmeticException exception occurs, and an ArithmeticException exception object is new at the bottom, and then thrown. Because the main method calls 100 / 0,
        Therefore, this exception ArithmeticException is thrown to the main method, which is not handled, and is directly thrown to the JVM, which finally terminates the execution of the program.

        ArithmeticException It inherits the RuntimeException and belongs to the runtime exception. There is no need to pre process the exception in the writing stage
         */
        System.out.println("Hello Word");
    }
}

Compile time exception error
package exception;
/*
What is the reason for the error in the following code?
doSome The method declaration position uses: throws classnotfoundexception. Classnotfoundexception is a compile time exception. Exception handling must be carried out when writing code, otherwise an error will be reported.
 */
public class Test04 {
    public static void main(String[] args) throws ClassNotFoundException {
        //The doSome method is called directly in the main method
        //Because the doSome method declaration location has: throws classnotfoundexception
        //When we call the doSome method, we must handle this exception in advance. If we don't handle it, the compiler will report an error
        doSome();
    }

    /**
     * doSome Method uses: throws classnotfoundexception at the location of the method declaration
     * This code indicates that classnotfoundexception may occur during the execution of doSome() method
     * @throws ClassNotFoundException Class did not find an Exception. The parent class is Exception, so the Exception belongs to compile time Exception
     */
    public static void doSome() throws ClassNotFoundException{
        System.out.println("doSome");
    }
}

Two treatment methods
package exception;

public class Test05 {
    //The first processing method: continue to use: throws at the position of the method declaration to complete the throwing up of exceptions. Throw to caller
    /*public static void main(String[] args) throws ClassNotFoundException {

        doSome();
    }*/
    //The second processing method: try catch
    //Capturing means stopping the exception and really solving the exception
    public static void main(String[] args) {
        try {
            doSome();
        }catch (ClassNotFoundException e){
            e.printStackTrace();
        }
    }


    public static void doSome() throws ClassNotFoundException{
        System.out.println("doSome");
    }
}
package exception;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/*
The first way to handle exceptions is to use the throw keyword at the position of the method declaration. I will throw it to whoever calls the method
 */
public class Test06 {
    /*
    It is generally not recommended to use throws on the main method, because if this exception occurs, it will be thrown to the JVM, and the JVM will terminate the execution of the program
    The function of exception handling mechanism is to enhance the robustness of the program, and the exception will not affect the execution of the program. Therefore, it is recommended to use try catch for exceptions in the main method
    main Will not continue to throw up
     */
    public static void main(String[] args) {
        System.out.println("main begin");
        try {
            m1();
            //If there is an exception, it will not be executed here
            System.out.println("Hello Word");
        } catch (FileNotFoundException e) {
            System.out.println(e);
            System.out.println("file does not exist");
        }
        System.out.println("main end");
    }
    public static void m1() throws FileNotFoundException{
        System.out.println("m1 begin");
        m2();
        //If there is an exception, it will not be executed here
        System.out.println("m2 end");
    }
    //Throw IOException, the parent class of FileNotFoundException, which is OK because IOException includes FileNotFoundException.
    //throws can throw multiple exceptions, separated by commas
    public static void m2() throws FileNotFoundException{
        System.out.println("m2 begin");
        m3();
        //The second method is to capture
        /*try {
            m3();
        } catch (FileNotFoundException e) {
            System.out.println("The file does not exist ');
        }*/

        //If there is an exception, it will not be executed here
        System.out.println("m2 end");

    }
    //The first method continues to throw up
    public static void m3() throws FileNotFoundException {
        System.out.println("m3 begin");
        /*
        What are the reasons for compilation errors?
            First: a construction method is called here: FileInputStream
            Second: the declaration position of this constructor has: throws FileNotFoundException
            Third: through the inheritance structure of the class, we can see that the parent class of FileNotFoundException is IOException, and the parent class of IOException is Exception. Finally, we know,
            FileNotFoundException Is a compile time exception

            Compile time exceptions require the programmer to handle them during compilation.
         */
        //FileInputStream FileInputStream = new FileInputStream ("C: \ \ users \ \ 77 \ \ downloads \ \ documents \ \ 07 javase advanced daily review and notes \ \ 11.txt");
        FileInputStream fileInputStream = new FileInputStream("C:\\Users\\77\\Downloads\\Documents\\07-JavaSE Advanced daily review and notes\\1.txt");
        //If an exception occurs, it will not be executed here
        System.out.println("m3 end");
    }
}
try catch

1. After the catch statement block (), you can write its own type or its parent type
2. Multiple catches can be written. It is recommended to handle catch exactly one by one
3. When writing more than one catch, you must follow from top to bottom and from small to large
4. Catch (FileNotFoundException | arithmetexception E) new features of jdk8

package exception;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/*
try catch
    1.catch After the statement block (), you can write its own type or its parent type
    2.catch You can write more than one. It is recommended to handle catch accurately one by one
    3.catch When writing multiple, you must follow from top to bottom and from small to large
    4.catch (FileNotFoundException | ArithmeticException e)  JDK8 New features of
 */
public class Test07 {
    public static void main(String[] args) {
        try {
            FileInputStream fileInputStream = new FileInputStream("C:\\Users\\77\\Downloads\\Documents\\07-JavaSE Advanced daily review and notes\\11.txt");
            fileInputStream.read();//Need to handle IO exception
            System.out.println(100/0);//Runtime exception, which can be handled at compile time or not
        } catch (FileNotFoundException | ArithmeticException e) {
            e.printStackTrace();
            System.out.println("file does not exist");
        }catch (IOException e){
            e.printStackTrace();
        }
        /*try {
            FileInputStream fileInputStream = new FileInputStream("C:\\Users\\77\\Downloads\\Documents\\07-JavaSE Advanced daily review and notes \ \ 11.txt ");
        } catch (IOException e) {//polymorphic
            e.printStackTrace();
            System.out.println("File does not exist ');
        }*/
        System.out.println("Subsequent code can be executed");
    }
}

Two methods of exception
package exception;
/*
Exception objects have two very important methods:
    Get unusually simple description information:
        String msg = exception.getMessage();

    Print stack information of exception trace:
        exception.printStackTrace();

 */
public class Test08 {
    public static void main(String[] args) {
        //Here, the exception object is just new, and the exception object is not thrown. The JVM thinks it is just an ordinary Java object
        NullPointerException e = new NullPointerException("Null pointer exception");
        //Get exception information, which is actually the construction method
        System.out.println(e.getMessage());

        //Print exception stack information
        //Two threads to execute the following two instructions respectively
        e.printStackTrace();
        System.out.println("It can be executed normally");
    }
}

finally statement block

About the finally clause in try catch:
1. The code in the finally clause is executed last and will be executed. Even if there are exceptions in the code in the try statement block, the finally statement must appear together with the try and cannot be written separately

2. Under what circumstances are finally statements usually used?
Release / close the resource in the finally statement block
Because the code in finally is more secure.
Even if the code in the try statement block is abnormal, the code block in finally will execute normally

package exception;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/*
About the finally clause in try catch:
    1.The code in the finally clause is executed last and will be executed, even if there is an exception in the code in the try statement block
        finally The statement must appear with try and cannot be written separately
    2.finally Under what circumstances are statements usually used?
        finally Complete the release / close of resources in the statement block
        Because the code in finally is more secure.
        Even if the code in the try statement block is abnormal, the code block in finally will execute normally
 */
public class Test10 {
    public static void main(String[] args) throws IOException {
        //Set as global variable
        FileInputStream fileInputStream = null;
        try {
            //Create an input stream object
            //fileInputStream here is a local variable
            fileInputStream = new FileInputStream("C:\\Users\\77\\Downloads\\Documents\\07-JavaSE Advanced daily review and notes\\11.txt");
            String s= null;
            s.toString(); //A null pointer exception occurs
            System.out.println("3");
            //Even if the above program is abnormal, the flow must be closed. It may not be closed at the current position
            //fileInputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }catch (NullPointerException e){
            e.printStackTrace();
        }finally {
            System.out.println("1");
            //It's safer to close the flow here
            if (fileInputStream != null){
                //The close method has exceptions, which are captured
                try {
                    fileInputStream.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
                System.out.println("2");
            }
        }

    }
}

return, and finally will be executed later

package exception;

public class Test11 {
    public static void main(String[] args) {
        /*
        try And finally, no catch
            try Cannot be used alone
            try finally Can be used in combination
         */
        try{
            System.out.println("try");
            return;
        }finally {
            //If there is a return, finally will execute it
            System.out.println("finally");
        }

        //If there is a return
        //You can't write statements here. This code can't be executed
        //System.out.println("1");
    }
}

After exit ing, finally does not execute

package exception;

public class Test12 {
    public static void main(String[] args) {
        try{
            System.out.println("try");
            System.exit(0);
            //Exit JVM finally do not execute
        }finally{
            System.out.println("finally");
        }
    }
}

Interview questions finally
package exception;
/*
finally Interview questions
 */
public class Test13 {
    public static void main(String[] args) {
        int res = m();
        System.out.println(res);//100
    }
    /*
    java Grammar rules (some rules cannot be broken)
    java There is a rule in the:
        The code in the method body must be executed line by line from top to bottom
     */
    public static int m(){
        int i = 100;
        try{
            //This line of code appears in int i = 100; So the final result must return 100
            // The return statement must also be guaranteed to be executed last. Once executed, the whole method ends
           return i;
        }finally {
            i++;
        }
    }
}
/*
Effect after Decompilation
public static int m(){
    int i = 100;
    int j = i;
    i ++;
    return j;
    Exceptrion exception;
    exception;
    i++;
    throw exception;
}
 */

finally final finalize
final keyword

final decorated classes cannot inherit
final decorated variables cannot be modified
final decorated methods cannot be overridden

finally keyword

finally with try
The code in the finally statement block must be executed

finalize method

Is a method name in the Object class
This method is called by the garbage collector GC

package exception;
/*
final keyword
    final Decorated classes cannot inherit
    final Modified variables cannot be modified
    final Decorated methods cannot be overwritten
finally keyword
    finally Use with try
    finally The code in the statement block must be executed
finalize method
    Is a method name in the Object class
    This method is called by the garbage collector GC
 */
public class Test14 {
    public static void main(String[] args) {
        //Final is a keyword that represents the final invariant
        final int i =100;

        //finally is also a keyword, which is used in conjunction with try in the exception handling mechanism
        //The code in the finally statement block is bound to execute
        try{

        }finally {
            System.out.println("finally");
        }

        //finalize() is a method in the Object class. Appears as a method name
        //So finalize is an identifier

    }
}

Custom exception class

1. You can customize exceptions
2. Steps to customize exceptions:
Step 1: write a class to inherit exception or RuntimeException
Step 2: provide two construction methods, one without parameters and one with String parameters

package exception;
/*
1.You can customize exceptions
2.To customize exceptions:
    Step 1: write a class to inherit exception or RuntimeException
    Step 2: provide two construction methods, one without parameters and one with String parameters
 */
public class Test15 {
    public static void main(String[] args) {
        //Create exception object (no manual exception thrown)
        MyException myException = new MyException("no");
        //Print exception information
        myException.printStackTrace();
        String msg  = myException.getMessage();
        System.out.println(msg);
    }
}
class MyException extends Exception{
    public MyException() {
    }

    public MyException(String message) {
        super(message);
    }
}

Application of exception in practical development

package exception;
//Test the improved stack
public class Test16 {
    public static void main(String[] args) {
        Mystack mystack = new Mystack();
        //Stack pressing
        try {
            mystack.push(new Object());
            mystack.push(new Object());
            mystack.push(new Object());
            mystack.push(new Object());
            mystack.push(new Object());
            mystack.push(new Object());
            mystack.push(new Object());
            mystack.push(new Object());
            mystack.push(new Object());
            mystack.push(new Object());
            mystack.push(new Object());
        } catch (MyStackOperationException e) {
            System.out.println(e.getMessage());
        }
        //Bomb stack
        try {
            mystack.pop();
            mystack.pop();
            mystack.pop();
            mystack.pop();
            mystack.pop();
            mystack.pop();
            mystack.pop();
            mystack.pop();
            mystack.pop();
            mystack.pop();
            mystack.pop();
        } catch (MyStackOperationException e) {
            e.printStackTrace();
        }

    }
}
package exception;
//Test the improved stack
public class Test16 {
    public static void main(String[] args) {
        Mystack mystack = new Mystack();
        //Stack pressing
        try {
            mystack.push(new Object());
            mystack.push(new Object());
            mystack.push(new Object());
            mystack.push(new Object());
            mystack.push(new Object());
            mystack.push(new Object());
            mystack.push(new Object());
            mystack.push(new Object());
            mystack.push(new Object());
            mystack.push(new Object());
            mystack.push(new Object());
        } catch (MyStackOperationException e) {
            System.out.println(e.getMessage());
        }
        //Bomb stack
        try {
            mystack.pop();
            mystack.pop();
            mystack.pop();
            mystack.pop();
            mystack.pop();
            mystack.pop();
            mystack.pop();
            mystack.pop();
            mystack.pop();
            mystack.pop();
            mystack.pop();
        } catch (MyStackOperationException e) {
            e.printStackTrace();
        }

    }
}

Exception handling when method overrides

package exception;
/*
There was a problem left when explaining method coverage
    The method after rewriting cannot throw more exceptions than the method before writing, and can throw fewer exceptions
 */
public class Test17 {
}
class A{
    public void doSome(){}
    public void doOtger() throws Exception{}
}
class B extends A{
    /*public void doSome() throws Exception{ //The parent class does not throw an exception, and the child class cannot throw an exception
    }*/

    /*Normal compilation
    public void doOther(){ //No exception is thrown and no error is reported

    }*/

    /*Normal compilation
    public void doOther() throws  Exception{

    }*/

    /*Normal compilation
    public void doOther() throws NullPointerException{

    }
    */

}

Summarize exception keywords

Keywords summarizing exceptions:
Exception capture:
try
catch
finally
throws is used at the method declaration position to report exception information to the caller
Throw manual throw exception

aggregate

The type conversion can be completed through the collection construction method

Overview of collections

1. What is a collection? What's the usage?

An array starts with a collection, which is actually a container that can be used to hold other types of data

Why are collections used more in development?

A collection is a container and a carrier that can hold multiple objects at a time. In the actual development, if you connect to the database and there are ten records in the database, if you query these 10 records, you will package 10 data into 10 Java objects in the Java program, then put the 10 Java objects into a collection, transfer the collection to the front end, and then traverse to display the data one by one

2. The data stored in the collection is of reference data type

Collection cannot store basic data directly. In addition, the collection cannot store Java objects directly. The memory address of Java objects is stored in the collection (or the collection stores references)

Note: the collection itself is a container in Java and refers to objects

[the external link picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-1dyns7od-163401323688) (C: / users / 77 / downloads / documents / 09-javase advanced classroom drawing in each chapter / 05-set / 001-the memory address of the object is stored in the set. png)]

3. Different sets have different data structures

In Java, for each different set, the bottom layer will correspond to different data structures. Storing elements in different sets is equivalent to putting data into different data structures. What is a data structure? The structure of data storage is data structure. Different data structures have different data storage methods. For example: array, binary tree, linked list, hash table, the above are common data structures.

You put data into the set c1, maybe on the array.

If you put data into the set c2, it may be on the binary tree.
...

Using different sets is equivalent to using different data structures

In the chapter of java collections, you don't need to be proficient in data structures. The data structure has been implemented in java, and these common collection classes have been written. You only need to master how to use them? Under what circumstances, you can choose which appropriate set to use.

new ArrayList(); Create a collection with an array at the bottom.
new LinkedList(); Create a collection object, and the underlying is a linked list.
new TreeSet(); Create a collection object with a binary tree at the bottom.
...

4. Under which package is the collection in the java JDK?

java.util.*; All collection classes and collection interfaces are under Java. Util

5. Inheritance structure diagram of collection

One is to store elements in a single way:
Store elements in a single way. The super parent interface in this kind of collection: java.util.Collection;

One is to store elements in key value pairs
Elements are stored in the form of key value pairs. The super parent interface in this kind of collection: java.util.Map;

Map interface

Summary:

ArrayList: the bottom layer is an array

LinkedList: the bottom layer is a two-way linked list

Vector: the bottom layer is an array, which is thread safe, inefficient and less used

HashSet: the bottom layer is HashMap. The elements put into the HashSet set are the same as the Key part of the HashMap set

TreeSet: the bottom layer is TreeMap. The elements put into the TreeMap combination are equivalent to the key part of the TreeMap set

HashMap: the bottom layer is the hash table data structure

HashTable: the bottom layer is also a hash table, but it is inefficient and less used

Properties: is thread safe, and key and value can only store strings

TreeMap: the bottom layer is a binary tree. The key s of the TreeMap set can be automatically sorted in size order

The characteristics of the storage elements of the List collection: ordered and repeatable

Order: the order of saving is the same as that of taking out. Each element has a subscript

Repeatable: save in 1, you can also save in 1

Characteristics of Set storage elements: unordered and non repeatable

Unordered: the order of saving is not necessarily the same as that of taking out. In addition, the elements in the Set set do not have subscripts

Non repeatable

SortedSet (SortedMap): unordered and non repeatable, but the elements in SortedSet are sortable

The key in the Map Set is a Set set

To put data into the Set is to put it into the key part of the Map Set

Common methods in Collection interface

1. What elements can be stored in the collection?

Before using generics, all subtypes of Object can be stored in the Collection
After using generic, only a specific type can be stored in the Collection
In the later stage of the Collection, we will learn "generics". Everything in the Collection can be saved as long as the Object subtype is OK
(neither basic data types nor Java objects can be stored directly in the collection, but only the memory address of Java objects)

2. Common methods in collection

boolean add (Object e) add method to add elements to the collection
int size() gets the number of elements in the collection
void clear() clears the collection
boolean contains(Object o) determines whether the current collection contains element o, returns true if it contains element o, and returns false if it does not
boolean remove(Object o) deletes an element in the collection
boolean isEmpty() determines whether the number of elements in the collection is 0
Object[] toArray() calls this method to convert a collection into an array
Iterator iterator() returns the iterator that iterates over the elements of this collection.

package collection;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

/*
About common methods in the collection interface
    1.Collection What elements can be stored in?
        Before using generics, all subtypes of Object can be stored in the Collection
        After using generic, only a specific type can be stored in the Collection
        In the later stage of the Collection, we will learn "generics". Everything in the Collection can be saved as long as the Object subtype is OK
        (Neither basic data types nor Java objects can be stored directly in the collection (only the memory address of the Java object is stored)
    2.Collection Common methods in
       boolean add(Object e)  add Method to add elements to the collection
       int size()  Gets the number of elements in the collection
       void clear() Empty collection
       boolean contains(Object o) Judge whether the current collection contains elements o, return true if it contains elements, and return false if it does not
       boolean remove(Object o) Delete an element in the collection
       boolean isEmpty() Judge whether the number of elements in the collection is 0
       Object[] toArray() Call this method to convert a collection into an array
       Iterator<E>	iterator()  Returns the iterator that iterates over the elements of this collection.

 */
public class Test01 {
    public static void main(String[] args) {
        //Create a collection object
        //Collection c = new Collection();  The interface is abstract and cannot be instantiated
        Collection c = new ArrayList();//polymorphic
        //Add method to add elements to the collection
        c.add(1200);//Automatic boxing actually puts in the memory address of an object. Integer x = new Integer(1200);
        c.add(3.14);
        c.add(new Object());
        c.add(true);

        System.out.println(c.size());

        System.out.println("------------");
        //Empty collection
        c.clear();
        System.out.println(c.size());

        c.add("hell0"); //The memory address of the hello object is put into the collection
        c.add("world");
        c.add("h");
        c.add("lv");
        c.add(1);

        //Determine whether the set contains
        boolean flag = c.contains("h");
        System.out.println(flag);

        boolean flag2 = c.contains("1h");
        System.out.println(flag);

        System.out.println("------------");
        System.out.println(c.size());

        System.out.println("------------");
        c.remove(1);
        System.out.println(c.size());

        System.out.println("------------");
        //Determine whether the collection is empty
        System.out.println(c.isEmpty());
        c.clear();
        System.out.println(c.isEmpty());

        System.out.println("------------");
        c.add("abc");
        c.add(1);
        c.add(2);
        c.add("world");
        Object[] objs = c.toArray(); //Convert a collection to an array
        for (int i = 0; i<objs.length;i++){
            System.out.println(objs[i]);
        }


    }
}

3. About set traversal / iterator

Step 1: get the Iterator object Iterator of the collection

Step 2: start iterating / traversing the collection through the iterator object above

package collection;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;

/**
 * About collection traversal / iterators
 *
 */
public class Test02 {
    public static void main(String[] args) {
        //The following traversal / iteration methods are common to all collections
        //It cannot be used in the Map Collection. It can be used in all collections and subclasses
        //Create collection object
        Collection c = new ArrayList();
        //Add element
        c.add("abc");
        c.add(10);
        c.add(2);
        c.add("world");
        //Traversal / iteration
        //Step 1: get the Iterator object Iterator of the collection
        Iterator iterator = c.iterator();
        //Step 2: start iterating / traversing the collection through the iterator object above
        /*
         The following methods are in the Iterator iterator
         boolean   hasNext()
          Returns true if there are still elements to iterate over.
         E next()
          Returns the next element of the iteration.
         */
        while(iterator.hasNext()){
            Object obj = iterator.next();
            System.out.println(obj);
        }
    }
}

4.contains method

boolean contains(Object o)
Determine whether the collection contains an object o
Returns true if included and false if not included

package collection;

import java.util.ArrayList;
import java.util.Collection;

/*
Delve into the contains method of the Collection
    boolean contains(Object o)
        Determine whether the collection contains an object o
        Returns true if included and false if not included
 */
public class Test04 {
    public static void main(String[] args) {
        //Create collection
        Collection c = new ArrayList();
        //Storing elements into a collection
        String s1 = new String("abc");
        String s2 = new String("def");
        c.add(s1);
        c.add(s2);

        System.out.println(c.size());
        //The String class has overridden equals
        String x= new String("abc");
        System.out.println(c.contains(x));
        //The equals method is called at the bottom of contains, and the equals method of String has been overridden



    }
}

4. The class placed in the collection needs to override the equals method

contains also overrides the equals method
package collection;

import java.util.ArrayList;
import java.util.Collection;

/*
Test contains method
 */
public class Test05 {
    public static void main(String[] args) {
        //Create collection object
        Collection c = new ArrayList();
        User u1 = new User("j");
        User u2 = new User("h");
        c.add(u1);
        c.add(u2);
        //The class class here does not override the equals method
        //So the contains method is false
        //After overriding the equals method, return true
        User u3 = new User("j");
        boolean flag = c.contains(u3);
        System.out.println(flag);
    }
}
class User{
    private String name;

    public User() {
    }

    public User(String name) {
        this.name = name;
    }

    //Override the equals method
    //The comparison principle of equals is that String name is the same
    @Override
    public boolean equals(Object o) {
        if (o == null || ! (o instanceof User))return false;
        if (o == this) return true;
        User user = (User) o;
        return  user.name == this.name;

    }

}
The equals method is also overridden in remove
package collection;

import java.util.ArrayList;
import java.util.Collection;

/*
Test contains method
 Test remove method
 */
public class Test05 {
    public static void main(String[] args) {
        //Create collection object
        Collection c = new ArrayList();
        User u1 = new User("j");
        User u2 = new User("h");
        c.add(u1);
        c.add(u2);
        //The class class here does not override the equals method
        //So the contains method is false
        //After overriding the equals method, return true
        User u3 = new User("j");
        boolean flag = c.contains(u3);
        System.out.println(flag);

        Collection collection = new ArrayList();
        String s1 = new String("C");
        String s2 = new String("C");
        collection.add(s1);
        //The remove underlying layer also calls the equals method
        //s1 and s2 are the same
        collection.remove(s2);
        System.out.println(collection.size());

    }
}
class User{
    private String name;

    public User() {
    }

    public User(String name) {
        this.name = name;
    }

    //Override the equals method
    //The comparison principle of equals is that String name is the same
    @Override
    public boolean equals(Object o) {
        if (o == null || ! (o instanceof User))return false;
        if (o == this) return true;
        User user = (User) o;
        return  user.name == this.name;
    }
}

5. Iterator in remove method

Important: when the structure of the collection changes, the iterator must be retrieved. If the iterator is not retrieved, an exception ConcurrentModificationException will occur.

Collection c = new ArrayList();
        //The iterator obtained at this time points to the iterator in the state of no element in the collection
        //It is important to note that as soon as the collection structure changes, the iterator must retrieve it
        //Iterator iterator = c.iterator();
        c.add(1);
        c.add(2);
        c.add(3);
        //If the iterator is not retrieved, a concurrent modificationexception will occur

Important: during the iteration of collection elements, you cannot call the remove method of collection objects to delete elements; A ConcurrentModificationException appears.

 Iterator iterator1 = c2.iterator();
        while(iterator1.hasNext()){
            Object o = iterator1.next();
            //c2.remove(o);  Delete elements directly through the collection without notifying the iterator (resulting in different snapshot states of the iterator and the original collection)
            //After deleting the element, the structure of the collection has changed. You should get the iterator again,
            //However, the next time the loop does not retrieve the iterator, an exception occurs
            //Use iterator to delete without exception
            //When an iterator is deleted, the iterator is automatically updated and the collection is updated (the elements in the collection are deleted)
            iterator1.remove();//What is deleted must be the element currently pointed to by the iterator
            System.out.println(o);
        }
package collection;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

/*
About remove of collection
    Important: when the structure of the collection changes, the iterator must be retrieved. If not, the iterator must be retrieved
         Then the exception ConcurrentModificationException will appear.
    Important: during the iteration of collection elements, you cannot call the remove method of collection objects to delete elements;
        A ConcurrentModificationException appears.
 */
public class Test06 {
    public static void main(String[] args) {
        Collection c = new ArrayList();
        //The iterator obtained at this time points to the iterator in the state of no element in the collection
        //It is important to note that as soon as the collection structure changes, the iterator must retrieve it
        //Iterator iterator = c.iterator();
        c.add(1);
        c.add(2);
        c.add(3);
        //If the iterator is not retrieved, a concurrent modificationexception will occur

        Iterator iterator = c.iterator();
        while(iterator.hasNext()){
            //When writing code, the next method must return Object
            Object i = iterator.next();
            System.out.println(i);
        }
        System.out.println("-----");
        Collection c2 = new ArrayList();
        c2.add("a");
        c2.add("b");
        c2.add("c");

        Iterator iterator1 = c2.iterator();
        while(iterator1.hasNext()){
            Object o = iterator1.next();
            //c2.remove(o);  Delete elements directly through the collection without notifying the iterator (resulting in different snapshot states of the iterator and the original collection)
            //After deleting the element, the structure of the collection has changed. You should get the iterator again,
            //However, the next time the loop does not retrieve the iterator, an exception occurs
            //Use iterator to delete without exception
            //When an iterator is deleted, the iterator is automatically updated and the collection is updated (the elements in the collection are deleted)
            iterator1.remove();//What is deleted must be the element currently pointed to by the iterator
            System.out.println(o);
        }
        System.out.println(c2.size());
    }


}

Important: in the process of iterating elements, you must use iterators to delete elements, iterator1.remove();

Common methods in List interface

1.list set storage element features: ordered and repeatable
Orderly: there is the following table
2. Since list is a sub interface of the Collection interface, it must have its own unique method:
Only common methods specific to the list interface are listed below:
void add(int index, E element)
Inserts the specified element at the specified position in the list (optional operation).
E get(int index)
Returns the element at the specified location in the list.
int indexOf(Object o)
Returns the index of the specified element that appears for the first time in this list; If this list does not contain this element, - 1 is returned.
int lastIndexOf(Object o)
Returns the index of the last specified element in the list; If the list does not contain this element, - 1 is returned.
E remove(int index)
Optionally, remove the element at the specified location in the list.
E set(int index, E element)
Optionally, replace the element at the specified position in the list with the specified element.

package collection;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/*
List Common methods in interfaces
    1.list Characteristics of collection storage elements: ordered and repeatable
        Orderly: there is the following table
    2.list Since it is a sub interface of the Collection interface, it must have its own unique methods:
      Only common methods specific to the list interface are listed below:
       void	add(int index, E element)
          Inserts the specified element at the specified position in the list (optional operation).
       E	get(int index)
          Returns the element at the specified location in the list.
       int	indexOf(Object o)
          Returns the index of the specified element that appears for the first time in this list; If this list does not contain this element, - 1 is returned.
       int	lastIndexOf(Object o)
          Returns the index of the last specified element in the list; If the list does not contain this element, - 1 is returned.
       E    remove(int index)
          Optionally, remove the element at the specified location in the list.
       E	set(int index, E element)
          Optionally, replace the element at the specified position in the list with the specified element.
 */
public class ListTest01 {
    public static void main(String[] args) {
        //Create a collection of type list
        List l1 = new ArrayList<>();

        l1.add("A");//The default is to add elements to the end of the collection
        l1.add("b");
        l1.add("c");
        l1.add("d");
        l1.add("A");
        l1.add("A");
        //This method is not used much because it is inefficient for Arraylist sets
        l1.add(1,"king");//index is a subscript to add an element to the specified location

        Iterator iterator = l1.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }

        //Get element from element subscript
        System.out.println(l1.get(0));
        System.out.println("-------list Collections have their own special traversal methods--------");
        //The list collection has its own special traversal method
        for (int i =0;i<l1.size();i++){
            System.out.println(l1.get(i));
        }

        System.out.println("-------Gets the index of the first occurrence of the specified object--------");
        //Gets the index of the first occurrence of the specified object
        System.out.println(l1.indexOf("king"));

        System.out.println("-------Gets the index of the last occurrence of the specified object--------");
        //Gets the index of the last occurrence of the specified object
        System.out.println(l1.lastIndexOf("A"));

        System.out.println("-------Deletes the specified subscript element--------");
        //Deletes the specified subscript element
        l1.remove(0);
        System.out.println(l1.size());

        System.out.println("-------Modify the element at the specified location--------");
        //Modify the element at the specified location
        l1.set(2,"s2");
        for (int i =0;i<l1.size();i++){
            System.out.println(l1.get(i));
        }
    }
}

ArrayList collection

Common methods

1. The default initialization capacity is 10. (an array with length 0 is created at the bottom layer. When an element is added, the initialization capacity is 10)
2. The bottom layer of the collection is an Object [] array
3. Construction method:
new ArrayList();
new ArrayList(20);
4. Set expansion of ArrayList:
1.5 times the original capacity
The array is at the bottom of the ArrayList set to minimize the expansion. Because the expansion efficiency of the array is relatively low, it is recommended to pre estimate the initialization capacity when using ArrayList.
5. Advantages of array: high retrieval efficiency
6. Disadvantages of array: the efficiency of random addition and deletion is relatively low, and the array cannot store a large amount of data (it is difficult to find a very large continuous space)
7. The efficiency of adding elements at the end of the array is very high and will not be affected
8. Among so many collections, which one is the most used?
ArrayList, because the element is added to the end, the efficiency is not affected. In addition, we have many operations to retrieve / find an element

9.Arraylist is not thread safe

package collection;

import java.util.ArrayList;
import java.util.List;

/*
ArrayList Set:
    1.The default initialization capacity is 10. (an array with a length of 0 is created at the bottom. When an element is added, the initialization capacity is 10)
    2.At the bottom of the collection is an Object [] array
    3.Construction method:
        new ArrayList();
        new ArrayList(20);
    4.ArrayList Set expansion of:
        1.5 times the original capacity
        ArrayList The bottom layer of the collection is the array, and the expansion shall be reduced as much as possible. Because the expansion efficiency of the array is relatively low, it is recommended to pre estimate the initialization capacity when using ArrayList.
    5.Advantages of array: high retrieval efficiency
    6.Disadvantages of array: the efficiency of random addition and deletion is relatively low, and the array cannot store a large amount of data (it is difficult to find a very large continuous space)
    7.The efficiency of adding elements at the end of the array is very high and is not affected
    8.Among so many collections, which one is the most used?
        ArrayList,Efficiency is not affected by adding elements to the end. In addition, we have more operations to retrieve / find an element
 */
public class ArrayListTest01 {
    public static void main(String[] args) {
        //The default initial capacity is 10
        List list1 = new ArrayList();
        System.out.println(list1.size());
        //Specify an initial capacity of 20
        List list2 = new ArrayList(20);
        System.out.println(list2.size());
        //The size method gets the number of elements in the current collection, not the capacity of the collection

        list1.add(1);
        list1.add(2);
        list1.add(3);
        list1.add(4);
        list1.add(5);
        list1.add(6);
        list1.add(7);
        list1.add(8);
        list1.add(9);
        list1.add(10);
        System.out.println(list1.size());

        list1.add(11);
        System.out.println();
    }
}

Construction method

1. Default initialization

List mylist1 = new ArrayList();

2. Given initialization capacity

List myList2 = new ArrayList(100);

3. The initialization capacity can be other sets

Collection c = new HashSet();
List mylist3 = new ArrayList(c);

Linked list

When Linkedlist is created, the underlying layer is bidirectional

Single linked list

Nodes in a single linked list

Nodes are the basic cells in a single linked list.
Each Node has two attributes:
One attribute is to store data
An attribute: is the memory address of the next node

Add node

Delete node

Advantages of linked list:
Because the memory addresses of the elements on the linked list are not continuous in spatial storage, there will be no displacement of a large number of elements when randomly adding and deleting elements, so the random addition and deletion efficiency is high
In future development, it is recommended to use linkedlist if there are many businesses of adding and deleting elements in the set immediately

Disadvantages of linked list:
The memory address of the element to be searched cannot be calculated by mathematical expression. Each search is traversed from the beginning of the node until it is found. Therefore, the efficiency of linkedlist set retrieval / search is relatively low

Arraylits: bring retrieval to the extreme
linkedlist: make full use of immediate additions and deletions
Adding elements often starts from the end, so the efficiency of adding at the end of Arraylist is relatively high

The Linkedlist set also has subscripts at the bottom
Note: Arraylist has high retrieval efficiency, not simply because of the subscript, but because of the role played by the underlying array
The linkedlist set still has subscripts, but it is inefficient to retrieve / find an element because it can only be traversed one by one from the beginning

Bidirectional linked list

Source code
private void linkFirst(E e) {
    final Node<E> f = first;
    final Node<E> newNode = new Node<>(null, e, f);
    first = newNode;
    if (f == null)
        last = newNode;
    else
        f.prev = newNode;
    size++;
    modCount++;
}

/**
 * Links e as last element.
 */
void linkLast(E e) {
    final Node<E> l = last;
    final Node<E> newNode = new Node<>(l, e, null);
    last = newNode;
    if (l == null)
        first = newNode;
    else
        l.next = newNode;
    size++;
    modCount++;
}

The linkedlist collection has no initialization capacity

At first, there are no elements in the linked list, and the references of first and last are null. No matter linkedlist or Arraylist, we don't need to care about which set it is when writing code in the future, because we have to write it facing the interface, and the called methods are the methods in the interface

Vector

1. The bottom layer is an array

2. Initialization capacity: 10

3. After capacity expansion, it is twice the original capacity. 10->20->40

4. The capacity expansion of ArrayList is 1.5 times 10 - > 15 - > 22.5

5. All methods in vector are thread synchronous, thread safe, inefficient and less used

6. How to convert Arraylist into thread safe Vector
Use the collection tool class:
java.util
Collections.synchronizedList becomes thread safe

Generic mechanism

introduce

1. The syntax mechanism of generics only works in the program compilation stage and is only used as a reference for the compiler (generics in the run-time stage are useless)

2. Benefits of using generics:
First: the element types stored in the collection are unified
Second: the elements taken from the collection are of the type specified by the generic type. There is no need for a large number of "down" type conversions“

3. Disadvantages of using generics:
This leads to a lack of diversity of elements stored in the combination
In most businesses, the types of elements in the collection are unified, and this mechanism is recognized

Using generics and not using generics

package collection;


import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/*
1.The syntax mechanism of generics only works in the program compilation stage and is only used as a reference for the compiler (run-time generics are useless)
2.Benefits of using generics:
    First: the element types stored in the collection are unified
    Second: the elements taken from the collection are of the type specified by the generic type. There is no need for a large number of "down type conversions"“
3.Disadvantages of using generics:
    This leads to a lack of diversity of elements stored in the combination
    In most businesses, the types of elements in the collection are unified, and this mechanism is recognized
 */
public class GenericTest01 {
    public static void main(String[] args) {
        //Disadvantages of not applicable generic mechanism analyzer
        /*List mylist= new ArrayList();
        C c = new C();
        B b = new B();
        mylist.add(c);
        mylist.add(b);*/

        //ergodic
        //iterator 
        /*Iterator iterator = mylist.iterator();
        while(iterator.hasNext()){
            A obj = (A) iterator.next();
            if (obj instanceof C){
                C x = (C) obj;
                x.move();
                x.catchM();
            }else if (obj instanceof B){
                B x = (B) obj;
                x.move();
                x.fiy();
            }
        }*/
        //Using generics
        //After using the generic list < a >, it means that the list collection is only allowed to store data of Animal type
        //Use generics to specify data types in a collection
        //If the specified class is A, other types will compile and report errors
        //In this way, after using generics, the data types of elements in the collection are more uniform
        List<A> mylist = new ArrayList<A>();
        C c = new C();
        B b = new B();
        mylist.add(c);
        mylist.add(b);
        ///Indicates that the iterator iteration is of type A
        Iterator<A> iterator = mylist.iterator();
        while(iterator.hasNext()){
            //Using the data of generic iteration, the data type returned each time is A
            //There is no need to cast types here
            A a = iterator.next();
            a.move();
            //You still need to cast a subtype specific method
            if (a instanceof C){
                C C = (C)a;
                C.catchM();
            }else {
                B B = (B)a;
                B.fiy();
            }
        }

    }
}

class A{
    public void move(){
        System.out.println("move");
    }

}
class C extends A{
    public void catchM(){
        System.out.println("catch");
    }

}
class B extends A{
    public void fiy(){
        System.out.println("fly");
    }

}

Automatic type inference mechanism

package collection;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/*
JDK8 Then, automatic type inference mechanism is introduced
 */
public class GenericTest02 {
    public static void main(String[] args) {
        //ArrayList < the type here will be automatically inferred > ()
        //Automatic type inference
        List<A> mylist = new ArrayList<>();
        mylist.add(new A());
        mylist.add(new C());
        mylist.add(new B());

        //ergodic
        Iterator<A> iterator = mylist.iterator();
        while(iterator.hasNext()){
            iterator.next().move();
        }
        List<String> strlits = new ArrayList<>();
        strlits.add("abc");
        strlits.add("def");

        Iterator<String> iterator1 = strlits.iterator();
        while(iterator1.hasNext()){
            System.out.println(iterator1.next());
        }
    }
}

Custom generics

When customizing a generic type, < > in angle brackets is an identifier, which can be written casually
< E > and < T > often appear in java source code
E: Is the initial of element
T: Is the initial of Type

package collection;
/*
Custom generics:
    When customizing a generic type, < > in angle brackets is an identifier, which can be written casually
    java < E > and < T > often appear in the source code
    E: Is the initial of element
    T: Is the initial of Type
 */
public class GenericTest03<AA>/*Just an identifier*/ {
    public void doSome(AA o){
        System.out.println(o);
    }
    public static void main(String[] args) {
        GenericTest03<String> gt = new GenericTest03<>();
        gt.doSome("abc");

        GenericTest03<Integer> gt2 = new GenericTest03<>();
        gt2.doSome(1);

        MyIterator<String> mi = new MyIterator<>();
        String s = mi.get();//The type is returned as String

        MyIterator<A> mi2 = new MyIterator<>();
        A a = mi2.get();
    }
}
class MyIterator<T>{
    public T get(){
        return null;
    }
}

Enhanced for loop

package collection;
/*
Enhanced for loop
 */
public class ForEachTest01 {
    public static void main(String[] args) {
        int[] arr = {1,55,4,7,3,14};
        for (int i = 0; i< arr.length ; i++){
            System.out.println(arr[i]);
        }
        System.out.println("-------------");
        //Enhanced for
        //Disadvantages: there is no subscript. It is not recommended to use subscript in the loop that needs to use subscript
        for(int e: arr){
            System.out.println(e);
        }
    }
}

package collection;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/*
Collection use enhanced foreach
 */
public class ForEachTest02 {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("1");
        list.add("2");
        list.add("3");
        //Traverses the way iterators are used
        Iterator<String> it= list.iterator();
        while(it.hasNext()){
            System.out.println(it.next());
        }
        System.out.println("----------");
        //The subscript method is used only for subscript sets
        for (int i = 0; i< list.size(); i++){
            System.out.println(list.get(i));
        }
        System.out.println("----------------");
        //Using foreach
        for (String i :list){
            System.out.println(i);
        }

    }
}

Set interface

HashSet

characteristic

1. The storage sequence is different from the extraction sequence
2. Non repeatable
3. The elements put into the HashSet set are actually put into the key part of the HashMap set

package collection;

import java.util.HashSet;
import java.util.Set;

/*
HashSet Set:
    Unordered and unrepeatable
 */
public class HashsetTest01 {
    public static void main(String[] args) {
        Set<String> str = new HashSet<>();
        //Add element
        str.add("11");
        str.add("55");
        str.add("44");
        str.add("22");
        str.add("11");
        str.add("33");

        /*
        11
        33
        44
        22
        55
        1.The storage order is different from the extraction order
        2.Non repeatable
        3.The elements put into the HashSet set are actually put into the key part of the HashMap set.
         */

        for (String i : str){
            System.out.println(i);
        }
    }
}

TreeSet

characteristic

1. Unordered and unrepeatable, but the stored elements can be automatically sorted in size order, which is called sorting set
2. Disorder means that the order of saving is different from that of taking out, and there is no subscript

package collection;

import java.util.Set;
import java.util.TreeSet;

/*
TreeSet Characteristics of collection storage elements:
    1.Unordered and non repeatable, but the stored elements can be automatically sorted in size order, which is called sorting collection
    2.Disorder means that the order of saving is different from that of taking out, and there is no subscript
 */
public class HashsetTest02 {
    public static void main(String[] args) {
        Set<String> strs = new TreeSet<>();
        strs.add("11");
        strs.add("23");
        strs.add("45");
        strs.add("22");
        strs.add("45");
        /*
        11
        22
        23
        45
        Auto sort from small to large
         */
        for (String i : strs) {
            System.out.println(i);
        }
    }
}

Map collection

Common methods

1.Map and Collection have no inheritance relationship

2. The map set stores data in the form of key and value: key value pairs
Both key and value are reference data types
Both key and value are memory addresses of storage objects
Key plays a leading role, and value is an accessory of key

3. Common methods in map interface

V put(K key, V value) adds a key value pair to the Map set

void clear() clears the Map

V get(Object key) get value through key

boolean containsKey(Object key) determines whether a key is included in the Map

boolean containsValue(Object value) determines whether a value is included in the Map

boolean isEmpty() determines whether the number of elements in the Map collection is 0

Set < k > keyset() gets all keys in the Map set (all keys are a set set)

V remove(Object key) deletes key value pairs through key

int size() gets all key value pairs in the Map collection

Collection values() gets all values

Set < Map. Entry < K, V > > entryset() converts a Map set into a set set
map set
​ key value
​ 1 z
​ 2 s
​ 3 w

​ Set set = map.entrySet();
Set set
1=z [Note: the Map Set is a Set set converted by the wntrySet() method. The element type in the Set is Map. Entry < K, V >, and Map. Entry < K, V > is a static internal class in the Map]
​ 2=s
​ 3=w

package collection;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/*
java.util.Map Common methods of:
    1.Map There is no inheritance relationship with Collection
    2.Map The collection stores data in the form of key and value: key value pairs
        key And value are reference data types
        key And value are the memory addresses of the storage objects
        key Plays a leading role. value is an accessory of key
    3.Map Methods commonly used in interfaces
        V	put(K key, V value) Add a key value pair to the Map collection
        void clear() Empty Map
        V	get(Object key) Get value through key
        boolean	containsKey(Object key) Judge whether the Map contains a key
        boolean	containsValue(Object value) Judge whether a value is included in the Map
        boolean	isEmpty() Judge whether the number of elements in the Map collection is 0
        Set<K>	keySet() Get all keys in the Map collection (all keys are a Set collection)
        V	remove(Object key) Delete key value pairs through key
        int	size()  Gets all key value pairs in the Map collection
        Collection<V>	values()    Get all value s
        Set<Map.Entry<K,V>>	entrySet() Convert Map Set to Set set Set
            map aggregate
            key           value
            1              z
            2              s
            3              w

            Set set  = map.entrySet();
            set aggregate
            1=z [Note: the Map Set is a Set set Set converted by the wntrySet() method. The element type in the Set set is Map. Entry < K, V >, and Map. Entry < K, V > is a static internal class in the Map]
            2=s
            3=w




 */
public class MapTest01 {
    public static void main(String[] args) {
        //Create a Map object and add key value pairs to the Maop collection
        Map<Integer,String> map = new HashMap<>();
        //Add key value pair
        map.put(1,"zz"); //1 automatic packing is carried out here
        map.put(2,"ss");
        map.put(3,"ww");
        System.out.println("-----adopt key To get value-------");
        //Get value through key
        String s = map.get(2);
        System.out.println(s);
        System.out.println("-----Gets the number of key value pairs-------");
        //Gets the number of key value pairs
        System.out.println("Number of key value pairs:"+map.size());
        //Delete key value through key
        System.out.println("-----adopt key delete key-value-------");
        map.remove(1);
        System.out.println("Number of key value pairs:"+map.size());
        //Determine whether a key is included
        //The underlying calls of the contains method are all compared with the equals method, so all custom types need to override the equals method
        System.out.println("-----Determine whether to include a key-------");
        System.out.println(map.containsKey(1));
        //Determine whether a value is included
        System.out.println("-----Determine whether to include a value-------");
        System.out.println(map.containsValue("ww"));
        //Get all value s
        System.out.println("-----Get all value-------");
        Collection<String> c= map.values();
        for (String e:c){
            System.out.println(e);
        }
        //Empty collection
        System.out.println("-----Empty collection-------");
        map.clear();
        System.out.println(map.size());
        //Judge whether it is empty
        System.out.println("-----Judge whether it is empty-------");
        System.out.println(map.isEmpty());
        
        


    }
}


Usage of inner classes
package collection;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class Myclass {
    //Declare a static inner class
    private  static class InnerClass{
        public static  void m1(){
            System.out.println("Static method execution");
        }
        public void m2(){
            System.out.println("Static inner class instance method execution");
        }
    }

    public static void main(String[] args) {
        Myclass.InnerClass.m1();//External class internal class.m1
        Myclass.InnerClass mi  = new Myclass.InnerClass();//Create a static inner class object
        mi.m2();

        //Give a Set collection to store the static inner class
        Set<InnerClass> set = new HashSet<>();
        Set<MyMap.Myentry> set1 = new HashSet<>();
    }
}
class MyMap{
    public static class Myentry<k,v>{

    }
}

Traversal of Map collection

The first method: get all the key s to traverse the value

The second method: Set < Map. Entry < K, V > > entryset() converts a Map Set into a Set set
Convert all Map sets into Set sets
The types of elements in the Set are: map. Entry < K, V >

package collection;

import java.util.*;

/*
Map Convenience of collection
    The first method: get all the key s to traverse the value
    The second method: Set < Map. Entry < K, V > > 	 entrySet() converts a Map Set into a Set set
              Convert all Map sets into Set sets
              Set The types of elements in the collection are: map. Entry < K, V >
 */
public class MapTest02 {
    public static void main(String[] args) {
        Map<Integer,String> map = new HashMap<>();
        map.put(1,"zz");
        map.put(2,"ss");
        map.put(3,"ww");

        //First traversal
        Set<Integer> keys = map.keySet();
        //Traversal key
        //Iterator foreach
        Iterator<Integer> iterator = keys.iterator();
        System.out.println("------iterator ---------");
        while(iterator.hasNext()){
            Integer key = iterator.next();
            String value = map.get(key);
            System.out.println(key + "=" + value);
        }
        System.out.println("------foreach---------");
        //foreach
        for (Integer key:keys){
            System.out.println(key + "=" + map.get(key));
        }

        //The second way
        System.out.println("-----Set<Map.Entry<K,V>>--------");
        Set<Map.Entry<Integer,String>> set = map.entrySet();
        //Traverse the set set and take out the node every time
        Iterator<Map.Entry<Integer,String>> iterator1 = set.iterator();
        while(iterator1.hasNext()){
            Map.Entry<Integer,String> entry = iterator1.next();
            Integer key = entry.getKey();
            String value = entry.getValue();
            System.out.println(key + "=" +value);
        }
        System.out.println("-----Set<Map.Entry<K,V>> foreach-------");
        for (Map.Entry<Integer,String> e:set){
            System.out.println(e.getKey() + "=" + e.getValue());
        }

    }
}

Data structure of hash table

HashMap collection:

1. The bottom layer of HashMap set is the data structure of hash table / hash table

2. Hash table is a combination of array and one-way linked list.
Array: it is very efficient in query, and the efficiency of random addition and deletion is very low
One way linked list: random addition and deletion is very efficient, and the efficiency in query is very low
Hash table combines the two kinds of data to give full play to their respective advantages

3. The underlying source code of HashMap collection:
public class HashMap{

/ / the bottom layer of HashMap is actually a one-dimensional array
transient Node<K,V>[] table;

/ / static inner class
​ static class Node<K,V> implements Map.Entry<K,V>{
​ final int hash; // Hash value. The hash value is the execution result of the hashCode() method of key. The hash value can be converted into the subscript of the storage array through the hash algorithm / function
​ final K key; // The key stored in the Map collection
​ V value; // The value stored in the Map collection
​ Node<K,V> next; // Memory address of the next node
​ }
​ }
Hash table / hash table: a one-dimensional array in which each element is a one-way linked list (a combination of array and linked list)

4. The most important things to master are:
map.put(k,v)
v = map.get(k)
The implementation principles of the above two methods must be mastered

5. Some features of HashMap set key:
Unordered and unrepeatable
Why disorder? Because it is not necessarily linked to a one-way linked list
How to guarantee non repetition? The equals method is used to ensure that the key of the HashMap set is not repeatable
If the key is repeated, the value will be overwritten

The elements placed in the key part of the HashMap set are actually placed in the HashMap set
Therefore, the elements in the HashSet collection also need to override the hashCode()+equals() method at the same time

6. If HashMap is not used properly, performance cannot be brought into play
Assuming that all hashCode() methods return a fixed value, the underlying hash table will become a pure single Necklace table. This situation is called: uneven hash distribution

What is uniform hash distribution?
Suppose there are 100 elements and 10 one-way linked lists, then each one-way list has 10 nodes, which is the best and the hash is uniform

Assuming that all the returned values of hashCode() are set to different values, the underlying hash table will become a one-dimensional array. There is no concept of linked list, and the hash distribution is uneven

Uniform hash distribution requires some skill when you rewrite the hashCode method.

7. Key: the elements placed in the key part of the HashMap set and the elements placed in the HashSet set need to rewrite the hashCode and equals methods at the same time.

8. The default initialization capacity of HashMap set is 16 and the default loading factor is 0.75
The default loading factor is to start expanding when the capacity of the underlying collection array of HashMap reaches 75%
Important: the initialization capacity of HashMap set must be a multiple of 2, which is also officially recommended. This is necessary because it can improve access efficiency

Rewriting of equals and hashCode

1. The hashCode method of the key is called first, and then the equals method is called when saving to and fetching from the Map set
The equals method may or may not be called
Take put(k,v) for example,
k. The hashcode () method returns the hash value. The hash value is converted into an array subscript through the hash algorithm. If the array subscript position is null, equals does not need to be executed
Take get(k,v) for example
If the array subscript is null, no execution is required; If there are elements on the array one-way linked list, equals is required

2. Note: if the equals method of a class is overridden, the hashCode method also needs to be overridden. If the equals method returns true, the return value of the hashCode method must be the same

3. The rewriting method is directly generated by the IDEA method, and the two methods should be generated at the same time

**4. Conclusion: * * the elements placed in the key part of the HashMap set and the HashSet set need to be written from the hashCode method and the equals method at the same time

5. For hash table data structure:
If the hash values of o1 and o2 are the same, they must be placed on a one-way linked list
Of course, if the hash values of o1 and o2 are different, but the array subscripts converted after the execution of the hash algorithm may be the same, a * * hash collision will occur**

6. Capacity expansion: the expanded capacity is twice the original capacity

package collection;

import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
/*
1.The hashCode method of the key is called first, and then the equals method is called when saving to and fetching from the Map collection
    equals Method may or may not be called
        Take put(k,v) for example,
            k.hashCode()Method returns a hash value. The hash value is converted into an array subscript through a hash algorithm. If the array subscript position is null, equals does not need to be executed
        Take get(k,v) for example
            If the array subscript is null, no execution is required; If there are elements on the array one-way linked list, equals is required

2.Note: if the equals method of a class is overridden, the hashCode method also needs to be overridden. If the equals method returns true, the return value of the hashCode method must be the same
3.The rewriting method is directly generated using the IDEA method, and the two methods should be generated at the same time
4.Conclusion: the elements placed in the key part of the HashMap set and in the HashSet set need to write the hashCode method and the equals method at the same time
 */
public class HashMapTest02 {
    public static void main(String[] args) {
        Student student1 = new Student("zz");
        Student student2 = new Student("zz");
        System.out.println(student1.equals(student2)); //Equal after rewriting
        System.out.println(student1.hashCode()); //2003749087
        System.out.println(student2.hashCode()); //1324119927 is 3935 after rewriting

        //The result of student1.equals(student2) is true, which means that student1 and student2 are the same. If you put them into the HashSet set set,
        //Only one can be put in

        Set<Student> set = new HashSet<>();
        set.add(student1);
        set.add(student2);
        System.out.println(set.size()); // 2
    }
}
class Student{
    private String name;

    public Student() {
    }

    public Student(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

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

    //hashCode

    //equals
    /*public boolean equals(Object obj){
        if(obj == null || !(obj instanceof Student))return false;
        if (obj == this) return true;
        //Type conversion
        Student s = (Student) obj;
        if (this.name == s.name)return true;
        return false;
    }*/

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return Objects.equals(name, student.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name);
    }
}

JDK8: if the hash form has more than 8 elements in the linked list, the one-way linked list data structure will become a red black tree data structure. When the nodes on the red black tree are male and 6, it will be rewritten to turn the red black tree into a one-way linked list data structure

HashTable

The key and value parts of the HashMap collection are allowed to be null

The key and value of HashTable cannot be null

HashTable methods are synchronized: thread safe. There are other schemes for thread safety. This HashTable's processing of threads leads to low efficiency and less use

Hashtable, like HashMap, has a hash table data structure at the bottom. The initialization capacity of hashtable is 11, the default loading factor is 0.75f, and the expansion capacity of hashtable is the original capacity * 2 + 1

Properties

At present, you only need to master the relevant methods of the Properties property class object

Properties is a Map collection that inherits hashtable. The key and value of properties are of String type. Properties are property class objects

package collection;

import java.util.Properties;

/*
At present, you only need to master the relevant methods of the Properties property class object
Properties It is a Map collection that inherits hashtable. The key and value of properties are of String type
Properties Is an attribute class object
 */
public class PropertiesTest01 {
    public static void main(String[] args) {
        //Create a Properties object
        Properties properties = new Properties();
        //You need to master two methods of Properties, one saving and one fetching
        properties.setProperty("url","http://");
        properties.setProperty("driver","com.mysql.jac.Dirver");
        properties.setProperty("uername","root");
        properties.setProperty("password","123");
        //Get value through key
        String s1 = properties.getProperty("url");
        String s2 = properties.getProperty("driver");
        String s3 = properties.getProperty("username");
        String s4 = properties.getProperty("password");
        System.out.println(s1);
        System.out.println(s2);
        System.out.println(s3);
        System.out.println(s4);
    }
}

TreeSet set

1. The bottom layer of the TreeSet set is actually a TreeMap

2. The bottom layer of the treemap set is a binary tree

3. The elements placed in the TreeSet set are equivalent to the key part of the TreeMap set

4. The elements in the TreeSet set are out of order and cannot be repeated, but they can be automatically filmed according to the size order of the elements. It is called a sortable set

First sort method
package collection;

import java.util.TreeSet;

/*
1.TreeSet The bottom layer of the collection is actually a TreeMap
2.TreeMap At the bottom of the set is a binary tree
3.The elements placed in the TreeSet collection are the same as those placed in the key part of the TreeMap collection
4.Treeset The elements in the collection are out of order and cannot be repeated, but they can be automatically filmed according to the size order of the elements. It is called a sortable set
 */
public class TreeSetTest01 {
    public static void main(String[] args) {
        //Create a TreeSet collection
       TreeSet<String> ts = new TreeSet<>();
       ts.add("zz");
       ts.add("za");
       ts.add("aa");
       ts.add("wa");
       ts.add("sd");
       for (String s:ts){
           System.out.println(s);
       }
        TreeSet<Integer> ts1 = new TreeSet<>();
       ts1.add(100);
       ts1.add(200);
       ts1.add(45);
       ts1.add(78);
       ts1.add(150);
       for (int i : ts1){
           System.out.println(i);
       }
    }
}
For custom types, can TreeSet sort?

In the following program, you cannot sort for Person type because no collation is specified
This exception occurred in the following program:
​ java.lang.ClassCastException: class collection.
​ Person cannot be cast to class java.lang.Comparable

package collection;

import java.util.TreeSet;

/*
For custom types, can TreeSet sort?
    In the following program, you cannot sort for Person type because no collation is specified
    This exception occurred in the following program:
        java.lang.ClassCastException: class collection.
        Person cannot be cast to class java.lang.Comparable
 */
public class TreeSetTest02 {
    public static void main(String[] args) {
        Person p1 = new Person(20);
        Person p2 = new Person(20);
        Person p3 = new Person(20);
        Person p4 = new Person(20);
        Person p5 = new Person(20);
        TreeSet<Person> treeSet = new TreeSet<>();
        treeSet.add(p1);
        treeSet.add(p2);
        treeSet.add(p3);
        treeSet.add(p4);
        treeSet.add(p5);
        for (Person p : treeSet){
            System.out.println(p);
        }
    }
}
class Person{
    int age;

    public Person(int age) {
        this.age = age;
    }
    public String toString(String s){
        return "Person[age:" + age+"]";
    }
}
The second sort method of TreeSet

The second way the TreeSet collection elements can be sorted: using a comparator
Conclusion: there are two ways to sort the elements placed in the TreeMap or the key part of the TreeMap:
The first one: put it into the collection java.lang.Comparable interface
The second is to pass a comparator object to the TreeMap or TreeSet collection

How to choose Comparator and Comparable
When the comparison rule will not change, or when there is only one comparison rule, it is recommended to use the Comparable interface.
If there are multiple comparison rules and multiple comparison rules need to be switched frequently, the Comparator interface is recommended
Comparator interface complies with OCP principles

package collection;

import java.util.Comparator;
import java.util.TreeSet;

/*
TreeSet The second way that collection elements can be sorted: using a comparator
 Conclusion: there are two ways to sort the elements placed in the TreeMap or the key part of the TreeMap:
    The first one: put it into the collection java.lang.Comparable interface
    The second is to pass a comparator object to the TreeMap or TreeSet collection
Comparator And Comparable
    When the comparison rule will not change, or when there is only one comparison rule, it is recommended to use the Comparable interface.
    If there are multiple comparison rules and multiple comparison rules need to be switched frequently, the Comparator interface is recommended
    Comparator The interface complies with OCP principles
 */
public class TreeSetTest06 {
    public static void main(String[] args) {
        //You need to use this comparator when creating a collection of treesets
        TreeSet<W> w = new TreeSet<>(new Wcomparator());
        w.add(new W(100));
        w.add(new W(101));
        w.add(new W(10));
        w.add(new W(800));
        w.add(new W(2000));
        w.add(new W(1000));
        for (W s :w){
            System.out.println(s);
        }

        //Anonymous inner classes can be used (this class has no name and directly uses the new interface)
        TreeSet<W> w1 = new TreeSet<>(new Comparator<W>(){
            public int compare(W o1, W o2) {
                //Sort by age
                return o1.age - o2.age;
            }
        });

    }
}
//Write a comparator separately
//Implement Comparator interface

class Wcomparator implements Comparator<W> {

    @Override
    public int compare(W o1, W o2) {
        //Sort by age
        return o1.age - o2.age;
    }


}
class W {
    int age;

    public W(int age) {
        this.age = age;
    }
    public String toString(){
        return "W," + "age:" + age;
    }
}

Changing the comparator can modify the comparison rules

package collection;

import java.util.Collections;
import java.util.Comparator;
import java.util.TreeSet;

public class CollectionTest02 {
    public static void main(String[] args) {
        TreeSet<Integer> ts = new TreeSet<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2-o1;
            }
        });
        ts.add(1);
        ts.add(100);
        ts.add(150);
        for (int i :ts){
            System.out.println(i);
        }
      

    }
}

Self balanced binary tree

The self balanced binary tree follows the principle of small left and large right

Middle order traversal: left root right

Collections tool class

java.util.Collection collection collection interface
java.util.Collections collection tool class

How to sort collections.sort

package collection;

import java.util.*;

/*
java.util.Collection Collection interface
java.util.Collections Collection tool class
 */
public class CollectionTest1 {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        //Become thread safe
        Collections.synchronizedList(list);
        //sort
        list.add("avf");
        list.add("abc");
        list.add("qw");
        list.add("wes");
        System.out.println("------------------");
        Collections.sort(list);
        for (String s:list){
            System.out.println(s);
        }
        List<W2> list1 = new ArrayList<>();
        list1.add(new W2(200));
        list1.add(new W2(250));
        list1.add(new W2(400));
        list1.add(new W2(500));
        list1.add(new W2(700));
        //To sort the elements of the list set, you need to ensure the implementation of the elements in the list combination: the Comparable interface
        Collections.sort(list1);
        for (W2 w2 :list1){
            System.out.println(w2.age);
        }
        System.out.println("------------------");
        Set<String> set = new HashSet<>();
        set.add("king");
        set.add("king1");
        set.add("king2");
        set.add("king32");
        set.add("king4");
        //Convert Set set to List
        List<String> mylist = new ArrayList<>(set);
        Collections.sort(mylist);
        for (String s:mylist){
            System.out.println(s);
        }

        //This method can also be sorted
        //Collections.sort(list, comparator)
    }
}
class W2 implements Comparable<W2> {
    int age;

    public W2(int age) {
        this.age = age;
    }
    public String toString(){
        return "W," + "age:" + age;
    }

    @Override
    public int compareTo(W2 o) {
        return this.age - o.age;
    }
}

summary

day30 class notes

1. Master common methods in Map interface.

2. You should be proficient in both ways of traversing Map sets.
The first method: obtain all keys, traverse each key, and obtain value through key
The second method: get Set < map. Entry > and traverse the entries in the Set
Call entry.getKey() entry.getValue()

3. Understand the hash table data structure.

4. The elements stored in the key part of the HashMap set and the HashSet set set need to rewrite hashCode and equals at the same time.

5. The difference between HashMap and Hashtable.
HashMap:
The initialization capacity is 16 and the expansion capacity is 2 times.
Non thread safe
key and value can be null.

​ Hashtable
Initialization capacity 11, capacity expansion 2x + 1
Thread safety
Neither key nor value can be null.

6. There are two common methods of the Properties class.
setProperty
getProperty

7. Understand the data structure of self balanced binary tree.
Left small right large principle storage.
Middle order traversal mode.

8. There are two ways to sort the key of TreeMap or the elements in TreeSet collection:
The first is to implement the java.lang.Comparable interface.
Second: write a Comparator interface separately.

9. Collection tool class Collections:
synchronizedList method
sort method (requires the elements in the collection to implement the Comparable interface.)

What is the main content of the collection?
1.1. Creation of each collection object (new)
1.2. Add elements to the set
1.3. Extract an element from the set
1.4. Traversing the set
1.5. Main collection classes:
ArrayList
LinkedList
HashSet (the key of HashMap, and the elements stored in the key of HashMap set need to rewrite hashcode + equals at the same time)
TreeSet
HashMap
Properties
TreeMap

I/O flow

Understanding of I/O flow

I: Input

O: Output

Reading and writing of hard disk files can be completed through IO

Classification of IO streams?

There are many classification methods:

One way is to classify according to the direction of flow:

Taking memory as a reference and going to memory is called input. Or reading; Coming out of memory is called output, or write

One way is to classify according to different data reading methods:

* * some streams read data in the way of bytes, which is called byte stream. Reading one byte at a time * * is equivalent to reading 8 binary bits at a time. This stream is universal. Any type of file can be read, including text file, picture, sound file, video file, etc

Suppose the file file1.txt is read as follows if byte stream is adopted:
a China bc Zhang San fe
First read: one byte, just read 'a'
Second reading: one byte, just half of the 'medium' character.
The third reading: a byte, just read the other half of the 'medium' character.

* * some read data in the form of characters, one character at a time, * * called character stream. This stream exists to facilitate reading ordinary text files. This stream cannot be read: pictures, sounds, videos and other files can only be read from stored text files, not even word files.

Suppose the file file1.txt is read as follows if the character stream is adopted:
a China bc Zhang San fe
First reading: 'a' character ('a 'character takes 1 byte in windows system.)
Second reading: 'medium' character ('medium' character occupies 2 bytes in windows system.)

To sum up: classification of flow

Input stream, output stream, byte stream, character stream

I/O in java

I/O flows in Java are written well. Programmers don't need to care. We mainly master what flows are provided in Java, what are the characteristics of each flow, and what are the common methods on each flow object

All streams in Java are: java.io. *; lower

java mainly studies:
How to create a new stream object.
Which method of the calling stream object is read and which method is write.

Four families of java IO streams

Leaders of the four families:
java.io.InputStream byte input stream

java.io.OutputStream byte output stream

java.io.Reader character input stream

java.io.Writer character output stream

The leaders of the four families are abstract classes. (abstract class)

Note: in java, as long as the "class name" ends with Stream, it is a byte Stream. All characters ending with * * "Reader/Writer" are character streams * *.

close() and flush() methods

All streams implement:
java.io.Closeable interfaces are closable and have close() methods.
After all, a stream is a pipeline, which is the channel between memory and hard disk. It must be closed after use, otherwise it will consume (occupy) a lot of resources. Form a good habit and close the flow after use.

All output streams implement:
java.io.Flushable interfaces are refreshable and have flush() methods.
Make it a good habit to remember to refresh flush() after the final output of the output stream. This refresh means that the remaining data in the channel / pipeline that has not been output is forcibly output (empty the pipeline!). The function of refresh is to empty the pipeline.
Note: failure to flush() may result in data loss.

There are 16 streams to master under the java.io package:

File Exclusive:
java.io.FileInputStream (Master)
java.io.FileOutputStream (Master)
java.io.FileReader
java.io.FileWriter

Convert stream: (convert byte stream to character stream)
java.io.InputStreamReader
java.io.OutputStreamWriter

Buffer stream exclusive:
java.io.BufferedReader
java.io.BufferedWriter
java.io.BufferedInputStream
java.io.BufferedOutputStream

Data flow exclusive:
java.io.DataInputStream
java.io.DataOutputStream

Standard output stream:
java.io.PrintWriter
java.io.PrintStream (Master)

Object specific flow:
java.io.ObjectInputStream (Master)
java.io.ObjectOutputStream (Master)

java.io.FileInputStream

1. File byte input stream is universal. This stream can be used to read any type of file
2. Complete input operation and read operation in byte mode (hard disk - > memory)

Create byte stream file
//The following are absolute paths
//File path: C: \ users \ 77 \ downloads \ documents \ 07 javase advanced daily review and notes will brake the handle \ programming \ \, because \ in java represents escape
//It can also be written as C:/Users/77/Downloads/Documents/07-JavaSE advanced daily review and notes
package streamsIO;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/*
java.io.FileInputStream
    1.File byte input stream is universal. Any type of file can be read with this stream
    2.Byte mode to complete input operation and read operation (hard disk - > memory)
 */
public class FileInputTest01 {
    public static void main(String[] args) {
        FileInputStream fis  = null;
        //Create byte stream file
        //The following are absolute paths
        //File path: C: \ users \ 77 \ downloads \ documents \ 07 javase advanced daily review and notes will brake the handle \ programming \ \, because \ in java represents escape
        //It can also be written as C:/Users/77/Downloads/Documents/07-JavaSE advanced daily review and notes
        try {
            fis = new FileInputStream("C:\\Users\\77\\Downloads\\Documents\\07-JavaSE Advanced daily review and notes\\11.txt");
            int readData = fis.read();
            System.out.println(readData);//The return value of this method is the byte itself read
            readData = fis.read();
            System.out.println(readData);
            readData = fis.read();
            System.out.println(readData);
            readData = fis.read();
            System.out.println(readData);
            readData = fis.read();
            System.out.println(readData);//Read to the end, the return value is - 1
            //In the file: abcd

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //Ensure that the flow must be closed in the finally statement block. When the stream is null, there is no need to close it to avoid null pointer exceptions
            if (fis!=null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

Modify the program and use the while loop
package streamsIO;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/*
Improve the first program, cycle mode

Read one byte at a time, so the interaction between memory and hard disk is too frequent, which basically consumes time and resources
 */
public class FileInputTest02 {
    public static void main(String[] args) {
        FileInputStream fis = null;
        try {
             fis = new FileInputStream("C:\\Users\\77\\Downloads\\Documents\\07-JavaSE Advanced daily review and notes\\11.txt");
             /*while(true){
                 int readDate = fis.read();
                 if (readDate == -1){
                     break;
                 }
                 System.out.println(readDate);
             }*/
             //Improve while
             int readDate = 0;
             while((readDate = fis.read())!=-1){
                 System.out.println(readDate);
             }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

Continue the transformation and read multiple bytes at a time
package streamsIO;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/*
int read(byte[] b)
    A maximum of b.length bytes can be read at a time
    Reduce the interaction between hard disk and memory and improve the execution efficiency of programs
    Read into byte [] array
 */
public class FileInputTest03 {
    public static void main(String[] args) {
        FileInputStream fis  = null;
        try {
            //Use relative path
            //The current default path of IDEA is. The root of Project is the default current path of IDEA
            fis = new FileInputStream("myfile.txt");
            //Start reading, use byte array, read multiple bytes at a time, and read up to "array. length" bytes
            byte[] bytes = new byte[4];//Read up to four bytes at a time
            //xiaoqi
            int readCount = fis.read(bytes);//4
            System.out.println(readCount);
            //The following method is to convert all byte arrays into strings
            //System.out.println(new String(bytes));
            //Not all of them should be converted. It should be the number of bytes read and converted
            System.out.println(new String(bytes,0,readCount));

            //Only two bytes can be read the second time
            readCount = fis.read(bytes);//2
            System.out.println(readCount);
            //System.out.println(new String(bytes));
            System.out.println(new String(bytes,0,readCount));

            //Finally, if the data is not read, return - 1
            readCount = fis.read(bytes);//-1
            System.out.println(readCount);

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

Final improvement
package streamsIO;

import java.io.FileInputStream;
import java.io.IOException;

/*
Last version
 */
public class FileInputTest04 {
    public static void main(String[] args) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream("myfile.txt");
            //Prepare an array
            byte[] bytes = new byte[4];
            /*while(true){
                int readCount = fis.read(bytes);
                if (readCount==-1){
                   break;
                }
                System.out.println(new String(bytes,0,readCount));
            }*/
            int readCount = 0;
            while((readCount = fis.read(bytes))!= -1){
                System.out.println(new String(bytes,0,readCount));
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (fis!=null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

Two other commonly used methods

int available() returns the number of unread bytes remaining in the stream
long skip(long n) skip a few bytes without reading

package streamsIO;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/*
Two other common methods:
    int available() Returns the number of unread bytes remaining in the stream
    long skip(long n) Skip a few bytes without reading
 */
public class FileInputeTest05 {
    public static void main(String[] args) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream("myfile.txt");
            //Read a byte
            //int readByte = fis.read();// There are five bytes left
            //What's the use of this method
            //You don't need a cycle. Just read it once
            /*System.out.println("Number of bytes: "+ fis.available());
            byte[] bytes = new byte[fis.available()];//This method is not suitable for too large files because the bytes [] array cannot be too large
            int readCount = fis.read(bytes);
            System.out.println(new String(bytes));*/

            //Skip a few bytes without reading. This method may also be used in the future
            fis.skip(3);
            System.out.println(fis.read());


        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (fis!=null)
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
    }
}

java.io.FileOutput

File byte output stream, responsible for writing (from memory to hard disk)

Write mode
package streamsIO;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/*
File byte output stream, responsible for writing
 From memory to hard disk
 */
public class FileOutputTest01 {
    public static void main(String[] args) {
        FileOutputStream fos = null;
        try {
            //A new file is automatically created when the file does not exist
            //This method needs to be used with caution because it will empty the source file
            //Writes to the end of the file as an append. The contents of the source file are not emptied
            fos = new FileOutputStream("myfile.txt",true);
            //Start writing to the file
            byte[] bytes = {97,98,99,100};
            //Write out all byte arrays
            fos.write(bytes);//abcd
            //Write out a part of the bytes array
            fos.write(bytes,0,2);//Write ab
            String s= "china";
            byte[] ss = s.getBytes();//Convert string to byte array
            fos.write(ss);
            //Be sure to refresh after writing
            fos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (fos != null)
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
    }
}

Copy of file

Use Fileinput and FileOutput to copy files
The copy process should be read and write at the same time,
When using the above byte stream to copy files, the file type is arbitrary and versatile. Any kind of file can be copied

package streamsIO;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/*
Use Fileinput and FileOutput to copy files
 The copy process should be read and write at the same time,
When using the above byte stream to copy files, the file type is arbitrary and versatile. Any kind of file can be copied
 */
public class Copy1 {
    public static void main(String[] args) {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream("C:\\Users\\77\\Downloads\\Documents\\07-JavaSE Advanced daily review and notes\\day34 Class notes.txt");
            fos = new FileOutputStream("D:\\study\\day34 Class notes.txt");
            //The core is reading and writing
            byte[] bytes = new byte[1024*1024];
            int readCount = 0;
            while((readCount = fis.read(bytes)) != -1){
                fos.write(bytes,0,readCount);
            }
            //The output stream is refreshed at last
            fos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (fos != null)
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if(fis != null)
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
    }
}

FileReader

The file character input stream can only read ordinary text. When reading text content, it is more convenient and fast

package streamsIO;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

/*
FileReader: 
    File character input stream, can only read ordinary text.
    When reading text content, it is convenient and fast
 */
public class FileReaderTest01 {
    public static void main(String[] args) {
        FileReader reader = null;
        try {
            reader = new FileReader("myfile.txt");
            char[] chars  = new char[4];//Read four characters at a time
            reader.read(chars);
            for (char c : chars){ //Read in character mode, the first time a, the second time b, and the third time small
                System.out.println(c);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (reader!=null)
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
    }
}

FileWriter

File character output stream - write, only ordinary text can be output

package streamsIO;

import java.io.FileWriter;
import java.io.IOException;

/*
FileWriter:
    File character output stream, write
    Only plain text can be output
 */
public class FileWriterTest01 {
    public static void main(String[] args) {
        FileWriter out = null;
        try {
            //Create file character output stream object
            out  = new FileWriter("file",true);

            //Start writing
            char[] chars = {'1','x','3','Small','seven'};
            out.write(chars);
            out.write(chars,3,2);
            out.write("\n");//Line feed
            out.write("Twenty seven little seven");


            //Refresh required
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (out != null)
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
    }
}

Copy plain text file

If you use FileReader and FileWriter to copy, you can only copy ordinary text files

package streamsIO;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/*
If you use FileReader and FileWriter to copy, you can only copy ordinary text files
 */
public class Copy02 {
    public static void main(String[] args) {
        FileReader in = null;
        FileWriter out = null;
        try {
            in = new FileReader("file");
            out = new FileWriter("file1");
            char[] chars = new char[1024 * 512];//1M
            int readCount = 0;
            while((readCount = in.read(chars))!= -1){
                out.write(chars,0,readCount);
            }

            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(in!=null)
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if(out!=null)
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }

    }
}

BufferedReader

Character input stream with buffer. When using this stream, there is no need to customize char array or byte array. It has its own buffer

package streamsIO;

import lei.T;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

/*
BufferReader:
    Character input stream with buffer
    When using this stream, you do not need to customize the char array, or the byte array, with its own buffer
 */
public class BuggeredReaderTest01 {
    public static void main(String[] args) {
        FileReader reader = null;
        BufferedReader buf = null;
        try {
            reader = new FileReader("myfile.txt");
            //When a flow is required in the construction method of a flow, the flow passed in is called node flow
            //The external flow responsible for packaging is called packaging flow, and another name is processing flow
            //For the current program, FileReader is a node stream and BufferReader is a processing stream
            buf = new BufferedReader(reader);
            /*//Read a line
            String firstLine = buf.readLine();
            System.out.println(firstLine);
            //Reading a line
            String SecondLIne = buf.readLine();
            System.out.println(SecondLIne);//null is returned when the last line is read*/

            String s = null;
            //The readline method reads a line of text without a newline
            while((s = buf.readLine())!=null){ // No line breaks
                System.out.println(s);
            }

            //Close flow
            //For the packaging flow, you only need to close the packaging flow, and the flow inside will be closed automatically

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (buf!=null)
                try {
                    buf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
    }
}

Convert character stream to character
package streamsIO;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;

public class BufferReadTest02 {
    public static void main(String[] args) throws Exception {
        FileInputStream fileInputStream = new FileInputStream("file");
        //FileInputStream is a byte stream, not a character stream. A character stream needs to be transmitted in BufferedReader
        //BufferedReader buf = new BufferedReader(fileInputStream);
        //fileInputStream is a node stream and inputStreamReader is a wrapper stream
        /*InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);//Convert node stream to character stream
        //inputStreamReader Is a node flow and bufferedReader is a wrapper flow
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);*/
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
        //merge
        String line = null;
        while((line = bufferedReader.readLine())!=null){
            System.out.println(line);
        }
        //Close, close outermost layer
        bufferedReader.close();
    }
}


BufferedWriter

Character output stream with cache

package streamsIO;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

/*
BufferWriter:Character output stream with cache
 */
public class BufferWriterTest01 {
    public static void main(String[] args) throws IOException {
        BufferedWriter out = new BufferedWriter(new FileWriter("file2"));
        out.write("xiaoqi");
        out.write("\n");
        out.write("1111");
        out.flush();
        out.close();
    }
}

PrintStream

Standard byte output stream. Default output to console

Change the direction of the flow setOut
package streamsIO;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;

/*
Standard byte output stream. Default output to console
 */
public class PrintStreamTest {
    public static void main(String[] args) throws FileNotFoundException {
        //Joint start writing
        System.out.println("hello word");
        //Write separately
        PrintStream ps = System.out;
        ps.println("hello l");
        ps.println("hello l");
        ps.println("hello a");

        //The standard output stream does not need to be closed manually
        //Change the output direction of the quasi output stream
        /*
        These are the methods and properties used by the System class before
        System.gc();
        System.currentTimeMillis();
        PrintStream ps1 = System.out;
        System.exit();
         */
        //The standard output stream no longer points to the console, but to the myfile file
        PrintStream printStream= new PrintStream(new FileOutputStream("myfile"));
        System.setOut(printStream);
        System.out.println("11");
        System.out.println("222");
        System.out.println("3333");
    }
}

Use of logging tool class
package streamsIO;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/*
Log tool
 */
public class LogUtil {

    public static void log(String msg){
        PrintStream out = null;
        /*
        Method of logging
         */
        try {
             out = new PrintStream(new FileOutputStream("log.txt",true));
             //Change output direction
             System.setOut(out);
             //Date current time
             Date date = new Date();
             //format
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
            String strtime= sdf.format(date);
            System.out.println(strtime  + ":" + msg);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

package streamsIO;

public class LogTest {
    public static void main(String[] args) {
        //Test whether the tool class is easy to use
        LogUtil.log("Called System Class gc Method, it is recommended to start the garbage collector");
        LogUtil.log("Called UserService of doSome()method");
        LogUtil.log("The user attempted to log in and authentication failed");
    }
}

ObjectOutputStream

serialization and deserialization

serialize

1.NotSerializableException: streamsIO.S: S class does not support serialization

2. Objects participating in serialization and deserialization must implement the Serializable interface

3. Note: it is found from the source code that the Serializable interface is only a flag interface
public interface Serializable{
}
There is no code in this interface
It plays the role of a flag, Java virtual machine. Seeing that this class implements this interface, it may give special treatment to this class
After the java virtual machine sees the interface, it will automatically generate a serialized version number for the class.

Serialization version number:

If the source generation is changed, an error will be reported during the reverse sequence
java.io.InvalidClassException: streamsIO.S; local class incompatible:
Stream classdesc serialVersionUID = 14197437576022108, (previous serial number)
local class serialVersionUID = -7501560671412578309 (subsequent serial number)

What mechanism is used in the Java language to distinguish classification?
First: first, compare the class names. If the class names are different, they must not be the same class
Second: if the class name is the same, it is distinguished by the serialization number and version

The serialized version number is used to classify the

Serialization works when different people write the same class, but the two classes are not written by the same person
For the Java virtual machine, the Java virtual machine can distinguish the two classes because both classes implement the Serialaizeble interface
Both have default serialization version numbers. Their serialization version numbers are different, so they are distinguished (this is the advantage of automatically generating serialization version numbers)

Defect of automatically generated serialized version number: the disadvantage of this automatically generated serialized version number is that once the code is determined, subsequent modifications cannot be made, because as long as the code is modified, it must be recompiled,
At this time, a new serialization version number will be generated. At this time, the Java virtual opportunity thinks that this is a new class, which is not good

**Conclusion: * * if a class implements the Serializable interface, it is recommended to provide the class with a fixed serialization version number. In this way, even if the code of this class is modified, the version number remains unchanged, and the java virtual opportunity considers it to be the same class

It is recommended to write out the serialized version number manually, and it is not recommended to generate it automatically

package streamsIO;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/*
1.NotSerializableException: streamsIO.S:  S Class does not support serialization
2.Objects participating in serialization and deserialization must implement the Serializable interface
3.Note: it is found from the source code that the Serializable interface is just a flag interface
    public interface Serializable{
    }
    There is no code in this interface
    It plays the role of a flag, Java virtual machine. Seeing that this class implements this interface, it may give special treatment to this class
    java After the virtual machine sees this interface, it will automatically generate a serialized version number for this class.
4.Serialization version number:
 */
public class ObjectOutputStreamTest01 {
    public static void main(String[] args) {
        S s = new S(111,"zz");
        ObjectOutputStream objectOutputStream = null;
        //serialize
        try {
            objectOutputStream = new ObjectOutputStream(new FileOutputStream("data"));
            objectOutputStream.writeObject(s);
            objectOutputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (objectOutputStream!=null){
                try {
                    objectOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
//Inherit a serializable interface
class S implements Serializable {
    private int no;
    private String name;

    public S() {
    }

    public S(int no, String name) {
        this.no = no;
        this.name = name;
    }

    public int getNo() {
        return no;
    }

    public String getName() {
        return name;
    }

    public void setNo(int no) {
        this.no = no;
    }

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

    @Override
    public String toString() {
        return "S{" +
                "no=" + no +
                ", name=" + name +
                '}';
    }
}

Serialize multiple collections -- list collections

package streamsIO;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/*
You can serialize multiple objects at a time and put them into a serialized collection
 */
public class ObjectOutputStreamTest02 {
    public static void main(String[] args) throws Exception {
        List<U> list = new ArrayList<>();
        list.add(new U(1,"z"));
        list.add(new U(2,"x"));
        list.add(new U(3,"P"));
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("users"));
        //Serialize a collection with multiple objects
        oos.writeObject(list);
        oos.flush();
        oos.close();

    }
}
class U implements Serializable {
    private int number;
    private String name;

    public U() {
    }

    public U(int number, String name) {
        this.number = number;
        this.name = name;
    }

    public int getNumber() {
        return number;
    }

    public String getName() {
        return name;
    }

    public void setNumber(int number) {
        this.number = number;
    }

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

    @Override
    public String toString() {
        return "U{" +
                "number=" + number +
                ", name='" + name + '\'' +
                '}';
    }
}
Deserialization
package streamsIO;

import java.io.*;

public class ObjectInputeStreamTest01 {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("data"));
        //Deserialization
        Object obj = objectInputStream.readObject();
        //Deserialized back is a toString method of a student object
        System.out.println(obj);
        objectInputStream.close();
    }
}

Deserialize multiple collections -- list collections

package streamsIO;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.List;

public class ObjectInputStreamTest02 {
    public static void main(String[] args) throws Exception{
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("users"));
        /*Object obj = ois.readObject();
        System.out.println(obj instanceof List);*/
        List<U> list = (List<U>) ois.readObject();//Down type conversion
        for (U u:list){
            System.out.println(u);
        }
        ois.close();
    }
}

transient keyword

Variables defined by transient do not participate in serialization

File class

1.File class has nothing to do with the four families. All file classes cannot read and write files

2.File object represents the abstract representation of file and path name
C:\Users\Downloads\Documents-JavaSE advanced daily review and notes are File objects
A File object may be a directory or a File
File is just an abstract representation of a pathname

3. Master the common methods of File class

common method

boolean exists(); Tests whether the file or directory represented by this abstract pathname exists.

boolean createNewFile(); // Create as file

boolean mkdir(); Create the directory specified by this abstract pathname.

boolean mkdirs(); Create the directory specified by this abstract pathname, including all required but nonexistent parent directories.

String getAbsolutePath(); Returns the absolute pathname string for this abstract pathname.

String getParent(); Returns the pathname string of the parent directory of this abstract pathname; Returns null if the pathname does not specify a parent directory.

String getName() returns the name of the file or directory represented by this abstract pathname.

boolean isDirectory(); Tests whether the file represented by this abstract pathname is a directory.

boolean isFile(); Tests whether the file represented by this abstract pathname is a standard file

long length(); Returns the length of the file represented by this abstract pathname.

long lastModified(); Returns the time when the file represented by this abstract pathname was last modified.

package streamsIO;

import java.io.File;
import java.io.IOException;

/*
File
    1.File Class has nothing to do with the four families. All File classes cannot read and write files
    2.File Object representation, abstract representation of file and path names
        C:\Users\77\Downloads\Documents\07-JavaSE Advanced daily review and notes are File objects
        A File object may be a directory or a File
        File Just an abstract representation of a pathname
    3.Master the common methods of File class

 */
public class FileTest01 {
    public static void main(String[] args) throws IOException {
        File f1  = new File("D:\\file");
        System.out.println(f1.exists());//Determine whether there is

        //You can create multiple directories
        File f2 = new File("D:\\file\\11");

        //If the file on disk D does not exist, it will be created in the form of a file
        if(!f1.exists()){
            //Create as file
            //f1.createNewFile();
            f1.mkdir();//Create as a directory
        }
        if (!f2.exists()){
            f2.mkdirs();
        }
        File f3 = new File("D:\\java\\javaSE\\log.txt");
        String parentPath = f3.getParent();
        System.out.println(parentPath);//D:\java\javaSE
        File parentFile = f3.getParentFile();
        System.out.println("Get absolute path" + parentFile.getAbsolutePath());//Get absolute path D:\java\javaSE

        File f4 = new File("myfile");
        System.out.println("Absolute path"+ f4.getAbsolutePath());//Absolute path D:\java\javaSE\myfile
    }
}
package streamsIO;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

/*
File Common methods of class
 */
public class FileTest02 {
    public static void main(String[] args) {
        File f1  = new File("myfile");
        //Or named file
        System.out.println(f1.getName());

        //Determine whether it is a directory
        System.out.println(f1.isDirectory());

        //Determine whether it is a file
        System.out.println(f1.isFile());

        //Gets the last modification time of the file
        System.out.println(f1.lastModified());//The long returned is one millisecond
        //Convert milliseconds to dates
        Date time = new Date(f1.lastModified());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
        String strtime = sdf.format(time);
        System.out.println(strtime);

        //Gets the size of the file
        System.out.println(f1.length());
    }
}

File[] listFiles(); Returns an array of abstract pathnames representing files in the directory represented by this abstract pathname.

package streamsIO;

import java.io.File;

/*
File listFiles method in
 File[]	listFiles()
          Returns an array of abstract pathnames representing files in the directory represented by this abstract pathname.
 */
public class FileTest03 {
    public static void main(String[] args) {
        //File[] listFile()
        //Get all sub files in the current directory
        File f = new File("D:\\");
        File[] files = f.listFiles();
        for (File file:files){
            System.out.println(file.getAbsoluteFile());//All sub files
        }
    }
}

Copy files in the entire directory

package streamsIO;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Copy03 {
    public static void main(String[] args) {
        //Copy source and copy destination
        //Call method copy
        File f1 = null;
        File f2 = null;

        f1 = new File("D:\\java\\javaSE");
        f2 = new File("c:\\java");
        CopyDir(f1,f2);

    }

    /**
     * replica catalog 
     * @param src
     * @param dest
     */
    private static void CopyDir(File src, File dest) {
        if (src.isFile()){
            //If src is a file, recursion ends
            //It needs to be copied when it is a file
            FileInputStream fileInputStream = null;
            FileOutputStream fileOutputStream = null;
            try {
                fileInputStream = new FileInputStream(src);
                byte[] bytes = new byte[1024*1024];
                String path = dest.getAbsolutePath().endsWith("\\")?dest.getAbsolutePath(): dest.getAbsolutePath() + "\\" + src.getAbsolutePath().substring(3);
                fileOutputStream = new FileOutputStream(path);
                int readCount = 0;
                while((readCount = fileInputStream.read(bytes))!= -1){
                    fileOutputStream.write(bytes,0,readCount);
                }
                fileOutputStream.flush();
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                if (fileInputStream != null){
                    try {
                        fileInputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fileOutputStream != null){
                    try {
                        fileOutputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return;
        }
        //Get subdirectories under source
        File[] files = src.listFiles();
        for (File file: files){
            //System.out.println(file.getAbsolutePath());// Gets the absolute path of all files
            //It may be a file or a directory
            if (file.isDirectory()){
                String srcDir = file.getAbsolutePath();//Gets the absolute path of the source directory
                //System.out.println(srcDir);
                String destDir = dest.getAbsolutePath().endsWith("\\")?dest.getAbsolutePath(): dest.getAbsolutePath() + "\\" + srcDir.substring(3);
                //System.out.println(destDir);
                File newFile = new File(destDir);
                if (!newFile.exists()){
                    newFile.mkdirs();
                }
            }
            CopyDir(file,dest);
        }
    }
}

Combined use of IO and Properties

IO stream: read and write of files.
Properties: is a Map collection. Both key and value are String types.

Very good design concept: the data that often changes in the future can be written to a file separately and read dynamically by the program. In the future, only the content of this file needs to be modified. The Java code does not need to be changed, recompiled, and the server does not need to be restarted to get dynamic information. A file similar to the above mechanism is called a configuration file
And when the content format in the configuration file is:
key = value
When, we call this configuration file the property configuration file
The java specification requires that the property configuration file should end with properties, but it is not necessary
The properties object is a class that specifically stores the contents of the property configuration file

package streamsIO;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Properties;

/*
IO Combined with Properties
    Very good design concept: the data that often changes in the future can be written to a file separately and read dynamically by the program
        In the future, you only need to modify the contents of this file. The Java code does not need to be changed, recompiled, and the server does not need to be restarted to get dynamic information

    A file similar to the above mechanism is called a configuration file
    And when the content format in the configuration file is:
        key = value
    When, we call this configuration file the property configuration file
    java The specification requires that the property configuration file is recommended to end with properties, but it is not necessary
    The properties object is a class that specifically stores the contents of the property configuration file
 */
public class IOPropertiesTest01 {
    public static void main(String[] args) throws Exception {
        /*
        Properties Is a Map collection. Both key and value are String types.
        You want to load the data in the userinfo file into the Properties object.
         */
        //Create a new input stream object
        FileReader fileReader = new FileReader("demo\\src\\streamsIO\\userinfo.properties");
        //Create a new Map collection
        Properties properties  = new Properties();
        //Call the load method of the Properties object to load the data in the file into the Map collection
        properties.load(fileReader);//The data in the file is loaded into the Map collection along the pipeline, where = on the left is the key, and on the right is the value username = admin

        //Get value through key
        System.out.println(properties.getProperty("username"));
        System.out.println(properties.getProperty("password"));
    }
}

Property profile
username=admin
password=123
##########In the properties profile#It's a comment#############
#If the key of the attribute configuration file is repeated, the value will be overwritten
#There can be spaces in the property configuration file, but it is best not to have spaces
#Intermediate use is not recommended:
#It is recommended to use the format of =

Multithreading

Threads and processes

A process is an application (a process is a software). A thread is an execution scenario / execution unit in a process.
A process can start multiple threads.

For java programs, when entering in the DOS command window:
After the java HelloWorld returns. The JVM will be started first, and the JVM is a process.
The JVM starts another main thread to call the main method. At the same time, start a garbage collection thread to take care of and collect garbage.
At the very least, there are at least two concurrent threads in current java programs,
One is the garbage collection thread and the other is the main thread executing the main method.

Relationship between process and thread

Process can be regarded as a real-life company, and thread can be regarded as an employee in the company.

be careful:
The memory of process A and process B is independent and not shared. (Alibaba and JD will not share resources!)
Warcraft is a process
Cool dog music is a process
The two processes are independent and do not share resources

What about thread A and thread B?
In the java language:
Thread A and thread B, heap memory and method area memory are shared.
However, the stack memory is independent, one thread and one stack.

Assuming that 10 threads are started, there will be 10 stack spaces. Each stack and each stack do not interfere with each other and execute their own, which is multi-threaded concurrency. Multithreading concurrency can improve efficiency. The reason why there is multithreading mechanism in java is to improve the processing efficiency of programs.

After using the multithreading mechanism, the main method ends. Is it possible that the program will not end. The main method ends, but the main thread ends, the main stack is empty, and other stacks (threads) may still press the stack.

Single core CPU and multi-core CPU

For a single core CPU, can you really achieve real multithreading concurrency?

For multi-core CPU computers, real multithreading concurrency is no problem. 4-core CPU means that four processes can be executed concurrently at the same time point.

What is true multithreading concurrency?
The t1 thread executes t1.
The t2 thread executes t2.
t1 does not affect t2, and t2 does not affect t1. This is called true multithreading concurrency.

A single core CPU means that there is only one brain:
It can not achieve real multithreading concurrency, but it can give people a feeling of "multithreading concurrency".
For a single core CPU, only one thing can be processed at a certain point in time. However, due to the extremely fast processing speed of the CPU, * * multiple threads switch execution frequently, * * it feels like: multiple things are being done at the same time!!!!!
Thread A: play music
Thread B: run Warcraft game
Thread A and thread B frequently switch execution. Human beings will feel that the music is playing all the time and the game is running all the time,
It gives us the feeling that it is concurrent.

package thread;


/*
The parser has several threads, in addition to garbage collection
    One thread (because the program has only one stack)
    A main method calls m1,m1 calls m2, and M2 calls m3 in a stack.
 */
public class ThereadTest01 {
    public static void main(String[] args) {
        System.out.println("main begin");
        m1();
        System.out.println("main over");
    }

    private static void m1() {
        System.out.println("m1 begin");
        m2();
        System.out.println("m1 over");
    }

    private static void m2() {
        System.out.println("m2 begin");
        m3();
        System.out.println("m3 over");
    }

    private static void m3() {
        System.out.println("m3 exceute");
    }

}

Two ways to implement threads

The first way

The first way: write a class, directly inherit java.lang.Thread, and rewrite the run method.

// Define thread class
	public class MyThread extends Thread{
		public void run(){
		}
	}
    // Create thread object
	MyThread t = new MyThread();
	// Start the thread.
	t.start();
package thread;
/*
The first way to implement threads:
    Write a class that directly inherits java.lang. Thread, override the run method
    void	run()
          If the thread is constructed using an independent Runnable running object, call the run method of the Runnable object; Otherwise, the method does nothing and returns.

   How do I create a thread? Just new
   How do I start a thread? Call the short() method of the thread object
 */
public class ThreadTest02 {
    public static void main(String[] args) {
        //Here is the main method. The code here belongs to the main thread and runs in the main stack
        //Create a new branch thread object
        MyThread myThread = new MyThread();
        //Start thread
        myThread.start();
        //The code here still runs in the main thread
        
}
class MyThread extends Thread{
    public void run(){
        //Write a program that runs in a branch thread
    }
}

Stack when calling run method directly

Stack when calling the start method

package thread;
/*
The first way to implement threads:
    Write a class that directly inherits java.lang. Thread, override the run method
    void	run()
          If the thread is constructed using an independent Runnable running object, call the run method of the Runnable object; Otherwise, the method does nothing and returns.

   How do I create a thread? Just new
   How do I start a thread? Call the short() method of the thread object

  be careful:
    The code in the method body is always executed line by line from top to bottom

    The output results of the following programs have such characteristics:
        There are first and then, more and less
 */
public class ThreadTest02 {
    public static void main(String[] args) {
        //Here is the main method. The code here belongs to the main thread and runs in the main stack
        //Create a new branch thread object
        MyThread myThread = new MyThread();
        //Start thread
        //myThread.run(); // If you only call the run method, the thread will not be started and a new branch stack will not be allocated (this method is single thread)
        //The function of the start() method is to start a branch thread, open up a new stack space in the JVM, and the code ends instantly
        //The task of this code is to open a new stack space. As long as the new stack space is opened, the start() method ends and the thread starts successfully.
        //The successful thread will automatically call the run method, and the run method is at the bottom of the branch stack (pressing the stack)
        //The run method is at the bottom of the branch stack, the main method is at the bottom of the main stack, and run and main are at the same level
        myThread.start();
        //The code here still runs in the main thread
        for (int i = 0; i<1000;i++){
            System.out.println("Main thread --->" + i);
        }
    }
}
class MyThread extends Thread{
    public void run(){
        //Write a program that runs in a branch thread
        for (int i = 0; i<1000;i++){
            System.out.println("Branch thread --->" + i);
        }
    }
}

The second method (recommended)

The second method: implement the java.lang.Runnable interface and the run method

package thread;
/*
The second way to implement threads is to write a class to implement the java.lang.Runnable interface
 */
public class ThreadTest03 {
    public static void main(String[] args) {
        //Create a runnable object
        //MyRunnable myRunnable = new MyRunnable();
        //Encapsulate the runnable object into a thread object
        Thread thread = new Thread(new MyRunnable());//Merged code
        //Start thread
        thread.start();
        for (int i = 0; i<1000;i++){
            System.out.println("Main thread --->" + i);
        }
    }
}
//This is not a thread class, but a runnable class. It is not a thread yet
class MyRunnable implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i<1000;i++){
            System.out.println("Branch thread --->" + i);
        }
    }
}

This method is commonly used. A class implements an interface, and it can inherit other classes, which is more flexible

Use anonymous inner classes to create threads
package thread;

import lei.T;

/*
Use anonymous inner classes
 */
public class ThreadTese04 {
    public static void main(String[] args) {
        //Create thread objects by anonymous inner classes
        Thread thered = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i<1000;i++){
                    System.out.println("Branch thread --->" + i);
                }
            }
        });
        //Start thread
        thered.start();
        for (int i = 0; i<1000;i++){
            System.out.println("Main thread --->" + i);
        }
    }
}

Thread life cycle

New status, ready status, running status, dead status

1. How to get the current thread object

​ Thiead t = Thread.currentThread();
The return value t is the current thread

2. Get the name of the thread object

Thread object. getName()

3. Modify the name of the thread object

Thread object. setName("thread name")

4. Default name of thread

When the thread name is not set, the default name of the thread is:

​ Thread-0
​ Thread-1

package thread;
/*
1.How to get the current thread object
    Thiead t =  Thread.currentThread();
    The return value t is the current thread
2.Gets the name of the thread object
    Thread object. getName()
3.Modify the name of the thread object
    Thread object. setName("thread name")
4.When the thread name is not set, the default name of the thread is
    Thread-0
    Thread-1
 */
public class ThreadTest05 {
    public static void main(String[] args) {
        //Current is the current thread
        //This method appears in the main thread, which is the main thread
        Thread current = Thread.currentThread();
        System.out.println(current.getName());//Main main method name
        //Create thread object
        M m = new M();
        M m2 = new M();
        //Set the name of the thread
        m.setName("m1");
        m2.setName("m2");
        //Gets the name of the thread
        System.out.println(m.getName());//Default name Thread-0
        System.out.println(m2.getName());
        //Start thread
        m.start();
        m2.start();
    }
}
class M extends Thread{
    @Override
    public void run() {
        for (int i = 0; i<10;i++){
            //Current is the current thread
            //When the M thread executes the run method, the current thread is m
            //When M2 thread executes, the current thread is m2
            Thread current = Thread.currentThread();
            //System.out.println(current.getName() + " "+ i);
            //System.out.println(super.getName() + " "+ i);
            System.out.println(this.getName() + " "+ i);
        }
    }
}

5.sleep method

About the sleep method of threads:

​ static void slep(long millis)
1. Static method Thread.sleep(1000);

2. The parameter is Ms

3. Function: let the current thread enter the sleep state, enter the sleep state, give up occupying the cpu time slice and let it be used by other threads. If it appears in that thread, let that thread sleep

4.Thread.sleep() can achieve this effect: execute a specific piece of code at a certain interval.

package thread;

import lei.T;

/*
About the sleep method of threads:
    static void slep(long millis)
    1.Static method Thread.sleep(1000);
    2.The parameter is milliseconds
    3.Function: let the current thread enter the sleep state, enter the sleep state, give up occupying the cpu time slice and let it be used by other threads
        If it appears in that thread, let that thread sleep
    4.Thread.sleep()    This effect can be achieved: a certain interval of time to execute a specific piece of code.
 */
public class ThreadTest06 {
    public static void main(String[] args) {
        /*try {
            //Put the current thread into sleep
            Thread.sleep(1000*5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //5 Execute in seconds
        System.out.println("hello word");*/
        for (int i =0;i<10;i++){
            System.out.println(Thread.currentThread().getName() + " --- >" + i);
            //Sleep for one second and execute once
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

package thread;

/*
About sleep method
 */
public class ThreadTest07 {
    public static void main(String[] args) {
        M1 m = new M1();
        m.setName("m");
        m.start();

        //Call sleep method
        try {
           m.sleep(1000);//During execution, it will still be converted to Thread.sleep(). This line of code is used to sleep the current thread and the main method
                                //This line of code appears in the main method, and the main thread sleeps
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("hello world");
    }
}
class M1 extends Thread{
    @Override
    public void run() {
        for (int i =0;i<10;i++){
            System.out.println(Thread.currentThread().getName() + " --> " + i);
        }
    }
}

Wake up the sleeping thread

t.interrupt();

package thread;


/*
Wake up a sleeping thread. This is not to interrupt the execution of the thread, but to terminate the sleep of the thread
 */
public class ThreadTest08 {
    public static void main(String[] args) {
        Thread t = new Thread(new MyRunnable2());
        t.setName("t");
        t.start();

        //I want the t thread to wake up after 5 seconds
        try {
            Thread.sleep(1000*5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //Interrupt t thread sleep (this interrupt sleep mode relies on the java exception handling mechanism)
        t.interrupt();//interfere
    }
}
class MyRunnable2 implements Runnable{

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "--> begin");
        //This can only try catch, and the child class cannot throw more exceptions than the parent class
        try {
            Thread.sleep(1000*60*60);
        } catch (InterruptedException e) {
            //Print exception information
            //e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + "---> end");

        //Call doOther
        try {
            doOther();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //Other methods can throw
    public void doOther() throws Exception{

    }
}

6. Thread termination

The stop method is not recommended

package thread;

/*
Forcibly terminate a thread in java
    This method has great disadvantages: it is easy to lose data, because this method directly kills the thread
    Data not saved by the thread will be lost and is not recommended
 */
public class ThreadTest09 {
    public static void main(String[] args) {
        Thread thread = new Thread(new MyRunnable3());
        thread.setName("t");
        thread.start();
        //Simulate 5 seconds sleep
        try {
            Thread.sleep(1000*5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //Forcibly terminate t thread after 5 seconds
        thread.stop();//Deprecated 
    }
}
class MyRunnable3 implements Runnable{
    @Override
    public void run() {
        for (int i =0;i<10;i++){
            System.out.println(Thread.currentThread().getName() + "-->" + i);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

Boolean methods are recommended

package thread;

/*
Reasonable thread termination
 */
public class ThreadTest10 {
    public static void main(String[] args) {
        MyRunnable4 myRunnable4 = new MyRunnable4();
        Thread thread = new Thread(myRunnable4);
        thread.setName("t");
        thread.start();
        //Simulate five seconds
        try {
            Thread.sleep(1000*5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //Terminate thread
        //When you want to terminate the execution of t, change run to false
        myRunnable4.run = false;
    }
}
class MyRunnable4 implements Runnable{
    boolean run = true;//Set a boolean flag
    @Override
    public void run() {
        for (int i =0; i<10;i++) {
            if (run) {
                System.out.println(Thread.currentThread().getName() + "--->" + i);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            else{
                //return is over. Anything that hasn't been saved before the end can be saved here
                //save
                return;
            }
        }
    }
}

On thread scheduling

Common scheduling modes

Preemptive scheduling model:
The priority of that thread is relatively high, and the probability of grabbing CPU time slices is higher / more.
java adopts preemptive scheduling model.

Even fraction scheduling model:
Evenly allocate CPU time slices. Each thread occupies the same length of CPU time slice.
Equal distribution, all equal.
In some programming languages, the thread scheduling model adopts this method

Method of thread scheduling

Instance method:
void setPriority(int newPriority) sets the priority of the thread
int getPriority() get thread priority
Lowest priority 1
The default priority is 5
Highest priority 10
Those with higher priority may get more CPU time slices. (but not exactly. The probability is high.)

Static method:
static void yield() yield method
Pauses the currently executing thread object and executes other threads
The yield() method is not a blocking method. Make the current thread give way to other threads.
The execution of the yield() method will return the current thread from the "running state" to the "ready state".
Note: after returning to ready, it is possible to grab it again.

Instance method:
	void join() ,Merge thread
class MyThread1 extends Thread {
			public void doSome(){
				MyThread2 t = new MyThread2();
				t.join(); // The current thread enters blocking, and the t thread executes until the t thread ends. The current thread can continue.
			}
		}

class MyThread2 extends Thread{
}

Thread safety (key)

In the future development, our projects are running in the server. The second server has completed the definition of thread, the creation of thread object, the startup of thread, etc. We don't need to write any of this code. The most important thing is that the written code needs to be run in a multithreaded environment, and we need to pay more attention to whether these data are safe in a multithreaded concurrent environment.

Multithreading concurrency

When do thread safety problems occur

Three conditions:
Condition 1: multithreading concurrency.
Condition 2: shared data.
Condition 3: shared data can be modified.

After the above three conditions are met, there will be a thread safety problem.

Resolve thread safety issues

In the multi-threaded concurrent environment, there are shared data, and the data will be modified. At this time, there is a thread safety problem. Solve the thread safety problem:

Threads are queued for execution (cannot be concurrent)

This queued execution solves the thread safety problem

This mechanism is called thread synchronization mechanism

Solving thread safety problems: using thread synchronization mechanism

Thread synchronization is thread queuing. Thread queuing will sacrifice some efficiency. Data security comes first. Only when data is safe can efficiency be improved

Technical terms involved

Asynchronous programming model:

Thread t1 and thread t2 execute their own. t1 regardless of t2 and t2 regardless of t1, no one needs to wait for anyone. This programming model is called asynchronous programming model

In fact, it is multi-threaded concurrency and high efficiency

Asynchrony is concurrency

Synchronous programming model:

When thread t1 and thread t2 execute, they must wait for the end of t2 thread execution, or when t2 executes, they must wait for the end of t1 thread execution. There is a waiting relationship between the two threads, which is the synchronous programming model. The efficiency is low and threads are queued for execution

Synchronization is queuing

Thread safety example

Thread unsafe

package TgreadSAFE;
/*
Without using thread synchronization mechanism, multiple threads withdraw money from the same account, resulting in thread safety problems
 */
public class Account {
    private String acton;//account
    private double balance;//balance

    public Account() {
    }

    public Account(String acton, double balance) {
        this.acton = acton;
        this.balance = balance;
    }

    public String getActon() {
        return acton;
    }

    public double getBalance() {
        return balance;
    }

    public void setActon(String acton) {
        this.acton = acton;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }
    //Withdrawal method
    public void withdraw(double money){
        //Balance before withdrawal
        double before = this.balance;
        //Balance after withdrawal
        double after = before - money;
        //Simulate the network delay and 100% of the first problems
        try {
            Thread.sleep(1000*5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //Update balance
        this.setBalance(after);
    }
}

package TgreadSAFE;

public class AccountThread extends Thread {
    //Two threads must share an account object
    private Account account;

    //Pass the account object through the construction method
    public AccountThread(Account account){
        this.account = account;
    }
    @Override
    public void run() {
        //The execution of the run method indicates withdrawal
        double money = 5000;
        //Multiple threads execute this method concurrently (t1 and t2 stacks)
        account.withdraw(money);
        System.out.println(Thread.currentThread().getName() + "Balance:" + account.getBalance());

    }
}

package TgreadSAFE;

public class Test01 {
    public static void main(String[] args) {
        //Create account object (only one)
        Account account = new Account("001",10000);
        //Two threads are created to share an account
        AccountThread accountThread1 = new AccountThread(account);
        AccountThread accountThread2 = new AccountThread(account);
        //Set name
        accountThread1.setName("t1");
        accountThread2.setName("t2");
        //Start withdrawal
        accountThread1.start();
        accountThread2.start();
    }
}

Methods to solve thread safety

Syntax of thread synchronization mechanism:

 synchronized (){
    //Thread synchronization mechanism code block
}

() the data transmitted must be shared by multiple threads in order to achieve multi-threaded queuing

What does () say?
It depends on which threads you want to synchronize
Suppose there are t1,t2,t3,t4,t5 and 5 threads
You only want T1, T2 and T3 to queue, T4 and T5 do not need to queue. What should you do?
You must pass in T1, T2 and T3 shared objects in (), which are not shared for T4 and T5

package ThreadSafe2;
/*
Using thread synchronization mechanism, multiple threads withdraw money from the same account to solve thread safety problems
 */
public class Account {
    private String acton;//account
    private double balance;//balance

    public Account() {
    }

    public Account(String acton, double balance) {
        this.acton = acton;
        this.balance = balance;
    }

    public String getActon() {
        return acton;
    }

    public double getBalance() {
        return balance;
    }

    public void setActon(String acton) {
        this.acton = acton;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }
    //Withdrawal method
    public void withdraw(double money){
        //The following lines of code must be thread queued and cannot be concurrent
        //After one thread executes all the code here, another thread can come in
        /*
        Syntax of thread synchronization mechanism:
            synchronized (){
            //Thread synchronization mechanism code block
            }
            The transmitted data must be shared by multiple threads in order to achieve multi-threaded queuing
            ()What does it say?
                It depends on which threads you want to synchronize
                Suppose there are t1,t2,t3,t4,t5 and 5 threads
                You only want T1, T2 and T3 to queue, T4 and T5 do not need to queue. What should you do?
                You must pass in T1, T2 and T3 shared objects in (), which are not shared for T4 and T5
         */
        //The account object is shared. this is the account object
        synchronized (this){
            //Balance before withdrawal
            double before = this.balance;
            //Balance after withdrawal
            double after = before - money;
            //Simulate the network delay and 100% of the first problems
            try {
                Thread.sleep(1000*5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //Update balance
            this.setBalance(after);
        }

    }
}

In the java language, any object has a "lock". In fact, this lock is a tag (just call it a lock)
100 objects, 100 locks
How the following code works:
1. Assuming that t1 and t2 threads are concurrent, when starting to execute the following code, there must be one first and one later
2. Suppose t1 executes first and encounters synchronized. At this time, it will automatically find the object lock of the shared object later
After it is found, it occupies the lock, and then executes the program in the synchronization code block. It always occupies the lock during execution until the code of the synchronization code block ends,
This lock will release
3. Suppose t1 already owns the lock, t2 also encounters the synchronized keyword, and will also occupy the lock of the shared object later. As a result, the lock is occupied by t1,
t2 can only wait for the end of t1 outside the synchronization code block until t1 finishes executing the synchronization code block, and t1 will return the lock. At this time, t2 waits until the lock, and t2 occupies the lock,
Enter synchronous code block execution program

In this way, the thread is queued for execution
It should be noted that the shared objects must be selected. The shared object must be shared by the thread objects you need to queue for execution.

 synchronized (this){
            //Balance before withdrawal
            double before = this.balance;
            //Balance after withdrawal
            double after = before - money;
            //Simulate the network delay and 100% of the first problems
            try {
                Thread.sleep(1000*5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //Update balance
            this.setBalance(after);
        }

Security of three variables in java

Instance variables: heap

Local variables: stack

Static variables: method area

Among the above three variables, local variables will never have security problems, because local variables are not shared. Constants also have no thread safety issues

Instance variables are in the heap, static variables are in the method area, and there is only one heap and method area,

Heap and method area are shared by multiple threads, so there may be thread safety problems

Expand the scope of secure synchronization

The withraw method is synchronized in run to expand the synchronization range and lower efficiency

package ThreadSafe2;

public class AccountThread extends Thread {
    //Two threads must share an account object
    private Account account;

    //Pass the account object through the construction method
    public AccountThread(Account account){
        this.account = account;
    }
    @Override
    public void run() {
        //The execution of the run method indicates withdrawal
        double money = 5000;
        //Multiple threads execute this method concurrently (t1 and t2 stacks)
        //Expand the scope of thread synchronization
        synchronized (account){
            account.withdraw(money);
        }
        System.out.println(Thread.currentThread().getName() + "Balance:" + account.getBalance());

    }
}

Use synchronized on instance methods

Add synchronized in the instance method
synchronized appears on the instance method. This must be locked, so this method is not flexible;
There is another disadvantage: synchronized appears on the instance method, which means that the whole method needs to be synchronized. It may expand the scope of synchronization for no reason and reduce the efficiency of the program. Therefore, this method is not commonly used
The advantage of synchronized in the instance method: less code is written and frugal.
If the shared object is this and the code block to be synchronized is the whole method body, this method is recommended

package ThreadSafe3;

public class Account {
    private String acton;//account
    private double balance;//balance
    Object object = new Object();//Instance variable (Account is shared by multiple threads, and the instance variable object in Account is also shared)

    public Account() {
    }

    public Account(String acton, double balance) {
        this.acton = acton;
        this.balance = balance;
    }

    public String getActon() {
        return acton;
    }

    public double getBalance() {
        return balance;
    }

    public void setActon(String acton) {
        this.acton = acton;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }
    //Withdrawal method
    //Add synchronized in the instance method
    //synchronized appears on the instance method. This must be locked, so this method is not flexible,
    //There is another disadvantage: synchronized appears on the instance method, which means that the whole method needs to be synchronized. It may expand the scope of synchronization for no reason and reduce the efficiency of the program. Therefore, this method is not commonly used
    //The advantage of synchronized in the instance method: less code is written and it is economical
    //If the shared object is this and the code block to be synchronized is the whole method body, this method is recommended
    public synchronized void withdraw(double money){
            double before = this.balance;
            double after = before - money;
            try {
                Thread.sleep(1000*5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            this.setBalance(after);


    }
}

If local variables are used, it is recommended to use StringBuilder. Because local variables do not have thread safety problems, it is inefficient to select StringBuffer.

ArrayList is non thread safe and Vector is thread safe

HshMap and HashSet are non thread safe, and HashTable is thread safe.

summary

synchronized can be written in three ways:

The first: synchronous code block, flexible

synchronized(Thread shared object){
			Synchronous code block;
		}

Second: use synchronized on the instance method
Indicates that the shared object must be this
And the synchronization code block is the whole method body.

Third: use synchronized on static methods
Indicates that a class lock is not found.
There is always only one class lock.
Even if 100 objects are created, there is only one such lock.

Object lock: 1 lock for 1 object, 100 locks for 100 objects.
Class lock: 100 objects, or just 1 class lock.

Interview questions

package ThreadExam1;
/*
t2 There is no need to wait for t1 to execute. Only doSome has a lock
*/

public class Test01 {
    public static void main(String[] args) {
        M m = new M();
        Thread t1 = new MyThread(m);
        Thread t2 = new MyThread(m);
        t1.setName("t1");
        t2.setName("t2");
        t1.start();
        try {
            Thread.sleep(1000);//Ensure that the t1 thread executes first
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t2.start();

    }
}
class MyThread extends Thread{
    private M m;
    public MyThread(M m){
        this.m = m;
    }
    public void run(){
        if(Thread.currentThread().getName() == "t1"){
            m.doSome();
        }
        if(Thread.currentThread().getName() == "t2"){
            m.doOther();
        }

    }
}
class M {
    public synchronized void doSome(){//Thread safe method
        System.out.println("doSome begin");
        try {
            Thread.sleep(1000*10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("doSome over");
    }
    public void doOther(){//Non thread safe method
        System.out.println("doOther begin");
        System.out.println("doOther over");
    }
}

package ThreadExam2;
/*
t2 You need to wait until t1 execution is completed. doSome and doOther are both this locks
*/

public class Test01 {
    public static void main(String[] args) {
        M m = new M();
        Thread t1 = new MyThread(m);
        Thread t2 = new MyThread(m);
        t1.setName("t1");
        t2.setName("t2");
        t1.start();
        try {
            Thread.sleep(1000);//Ensure that the t1 thread executes first
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t2.start();

    }
}

class MyThread extends Thread{
    private M m;
    public MyThread(M m){
        this.m = m;
    }
    public void run(){
        if(Thread.currentThread().getName() == "t1"){
            m.doSome();
        }
        if(Thread.currentThread().getName() == "t2"){
            m.doOther();
        }

    }
}

class M {
    public synchronized void doSome(){//The lock is this
        System.out.println("doSome begin");
        try {
            Thread.sleep(1000*10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("doSome over");
    }
    public synchronized void doOther(){//The lock is this
        System.out.println("doOther begin");
        System.out.println("doOther over");
    }
}

package ThreadExam3;
/*
There are two thread objects, so t2 does not need to wait for t1 to execute
*/
public class Test01 {
    public static void main(String[] args) {
        M m = new M();
        M m1 = new M();
        Thread t1 = new MyThread(m);
        Thread t2 = new MyThread(m1);
        t1.setName("t1");
        t2.setName("t2");
        t1.start();
        try {
            Thread.sleep(1000);//Ensure that the t1 thread executes first
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t2.start();

    }
}

class MyThread extends Thread{
    private M m;
    public MyThread(M m){
        this.m = m;
    }
    public void run(){
        if(Thread.currentThread().getName() == "t1"){
            m.doSome();
        }
        if(Thread.currentThread().getName() == "t2"){
            m.doOther();
        }

    }
}

class M {
    public synchronized void doSome(){//The lock is this
        System.out.println("doSome begin");
        try {
            Thread.sleep(1000*10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("doSome over");
    }
    public synchronized void doOther(){//The lock is this
        System.out.println("doOther begin");
        System.out.println("doOther over");
    }
}

package ThreadExam4;
/*
Static methods are class locks, so t2 needs to wait for t1 to execute
*/
public class Test01 {
    public static void main(String[] args) {
        M m = new M();
        M m1 = new M();
        Thread t1 = new MyThread(m);
        Thread t2 = new MyThread(m1);
        t1.setName("t1");
        t2.setName("t2");
        t1.start();
        try {
            Thread.sleep(1000);//Ensure that the t1 thread executes first
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t2.start();

    }
}

class MyThread extends Thread{
    private M m;
    public MyThread(M m){
        this.m = m;
    }
    public void run(){
        if(Thread.currentThread().getName() == "t1"){
            m.doSome();
        }
        if(Thread.currentThread().getName() == "t2"){
            m.doOther();
        }

    }
}

class M {
    public synchronized static void doSome(){//The lock is this
        System.out.println("doSome begin");
        try {
            Thread.sleep(1000*10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("doSome over");
    }
    public synchronized static void doOther(){//The lock is this
        System.out.println("doOther begin");
        System.out.println("doOther over");
    }
}

Deadlock phenomenon

package DeadLock;

import lei.T;

/*
Deadlock code should be able to write
 Only those who can write will pay attention to this in future development
 Because deadlocks are hard to debug
 */
public class DeadLock {
    public static void main(String[] args) {
        Object o1 = new Object();
        Object o2 = new Object();
        //t1 and t2 share o1 and o2
        Thread t1 = new Mythread(o1,o2);
        Thread t2 = new Mythread2(o1,o2);
        t1.start();
        t2.start();
    }
}
class Mythread extends Thread{
    Object o1;
    Object o2;
    public Mythread(Object o1,Object o2){
        this.o1 = o1;
        this.o2 = o2;
    }
    public void run(){
        synchronized (o1){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (o2){

            }
        }
    }
}
class Mythread2 extends Thread{
    Object o1;
    Object o2;
    public Mythread2(Object o1,Object o2){
        this.o1 = o1;
        this.o2 = o2;
    }
    public void run(){
        synchronized (o2){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (o1){

            }
        }
    }

}

How to solve thread safety problems in development

Do you choose thread synchronization from the beginning? synchronized
No, synchronized will reduce the execution efficiency of the program and the user experience is not good.
The user throughput of the system is reduced. Poor user experience. Choose again as a last resort
Thread synchronization mechanism.

The first scheme: try to use local variables instead of "instance variables and static variables".

The second scheme: if it must be an instance variable, you can consider creating multiple objects so that the memory of the instance variable is not shared. (one thread corresponds to one object, and 100 threads correspond to 100 objects. If the objects are not shared, there is no data security problem.)

The third scheme: if you can't use local variables and create multiple objects, you can only choose synchronized at this time. Thread synchronization mechanism.

Thread other content

1. Daemon thread

Threads in the java language fall into two categories:
One is user thread
One is daemon thread (background thread)
The representative one is garbage collection thread (daemon thread).

Features of daemon thread:
Generally, the daemon thread is an endless loop. As long as all user threads end, the daemon thread ends automatically.

Note: the main method of the main thread is a user thread.

Where are daemon threads used?
The system data is automatically backed up at 00:00 every day.
This requires a timer, and we can set the timer as a daemon thread.
I've been watching there. I back up every 00:00. All user threads
If it is over, the daemon thread will exit automatically, and there is no need for data backup.

package thread;
/*
Daemon thread
 */
public class Test14 {
    public static void main(String[] args) {
        Thread t= new BakDtaThread();
        t.setName("beifeng");
        //Set the thread as a daemon before starting the thread
        t.setDaemon(true);
        t.start();

        //Main thread
        for (int i =0;i<10;i++){
            System.out.println(Thread.currentThread().getName() + "-->" + i);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
class BakDtaThread extends Thread{
    public void run(){
        int i = 0;
        while(true){
            System.out.println(Thread.currentThread().getName() + " --- >" + (++i));
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

2. Timer

Function of timer:
Execute specific programs at specific intervals.

General ledger operation of bank account shall be carried out every week.
Backup data every day.

In actual development, it is very common to execute a specific program every other time. In fact, there are many ways to implement it in java:
You can use the sleep method to sleep, set the sleep time, wake up before this time point and perform tasks. This method is the most primitive timer. (compare low)

A timer has been written in the java class library: java.util.Timer, which can be used directly. However, this method is rarely used in current development, because there are many high-level frameworks that support timed tasks.

In the actual development, the SpringTask framework provided by the Spring framework is widely used. As long as this framework is simply configured, it can complete the task of the timer.

3. The third way to implement threads: FutureTask, which implements the Callable interface

The thread implemented in this way can obtain the return value of the thread.
The two methods explained earlier cannot obtain the thread return value, because the run method returns void.

Thinking:
The system assigns a thread to execute a task. After the thread executes the task, there may be an execution result. How can we get the execution result?
The third way is to implement the Callable interface.

4. About the wait and notify methods in the Object class. (producer and consumer model)

First, the wait and notify methods are not methods of Thread objects, but methods of any java Object in java, because these two methods are built-in in the Object class.

The wait method and notify method are not called through the thread object. It is not like this: t.wait(), nor is it like this: t.notify()... No.

Second: what is the function of the wait() method?
Object o = new Object();
o.wait();

Means:
Let the thread active on the o object enter the waiting state and wait indefinitely until it is awakened.
​ o.wait(); Method will put the current thread (the thread active on the O object) into a waiting state.

Third: what is the function of the notify() method?
Object o = new Object();
o.notify();

Means:
Wakes up the thread waiting on the o object.
There is also a notifyAll() method:
This method wakes up all the waiting threads on the o object.

Producer and consumer model

One for production and one for consumption

package thread;

import lei.T;

import java.util.ArrayList;
import java.util.List;

/*
1.Using the wait method and notify method to implement producer and consumer patterns

2.What is the "producer and consumer model"?
    The production thread is responsible for production and the consumption thread is responsible for consumption
    Production threads and consumption threads should be balanced
    This is a special business requirement. In this special case, you need to use the wait and notify methods

3.wait The and notify methods are not thread object methods, but ordinary java object methods

4.wait Method and notify method are based on thread synchronization. Because multithreading has to operate a warehouse at the same time, there is a ready-made security problem

5.wait Method, o.wait() makes the thread t active on the O object enter the waiting state, and releases the lock of the O object held by the thread t

6.notify The function of the o.notify() method is to wake up the thread waiting on the O object. It is just a notification and will not release the lock previously held on the O object

7.Simulation requirements
    The warehouse adopts list collection
    list It is assumed that only one element can be stored in the collection
    1 One element means the warehouse is full
    If the element in the list collection is 0, it means that the warehouse is empty
    Ensure that the list collection always stores at most one element
    This effect must be achieved: one generation, one consumption
 */
public class ThreadTest16 {
    public static void main(String[] args) {
        //Create warehouse object
        List list  = new ArrayList();
        //Create two thread objects
        //One is the producer thread
        Thread thread1 = new Thread(new Procuder(list));
        //One is the consumer thread
        Thread thread2 = new Thread(new Consumer(list));

        thread1.setName("t1");
        thread2.setName("t2");
        thread1.start();
        thread2.start();
    }
}
//Production thread
class Procuder implements Runnable{
    //Shared warehouse
    private List list;

    public Procuder() {
    }

    public Procuder(List list) {
        this.list = list;
    }

    @Override
    public void run() {
        //Always produce
        while(true){
            synchronized (list){
                if(list.size() > 0){
                //The current thread enters a waiting state
                     try {
                        list.wait();//The current thread enters the waiting state and releases the lock of the list collection held by the procuder
                     } catch (InterruptedException e) {
                    e.printStackTrace();
                    }
                }
                //The program execution here shows that the warehouse is empty and can be produced
                Object obj = new Object();
                list.add(obj);
                System.out.println(Thread.currentThread().getName() + "--->" + obj);
                //Awaken consumers to consume
                list.notify();
            }
        }
    }
}
//Consumption thread
class Consumer implements Runnable{
    private List list;

    public Consumer() {
    }

    public Consumer(List list) {
        this.list = list;
    }

    @Override
    public void run() {
        //Always consumption
        while(true){
            synchronized (list){
                if(list.size() == 0){
                    try {
                        list.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                //When the program is executed here, it indicates that there is data in the warehouse for consumption
                Object obj = list.remove(0);
                System.out.println(Thread.currentThread().getName() + "---->" + obj);
                //Awaken producer production
                list.notify();
            }
        }
    }
}

Reflection mechanism

What's the use of reflection mechanism?

Bytecode files can be manipulated through the reflection mechanism in the java language.
The advantages are similar to hackers. (bytecode files can be read and modified.)
Code snippets can be manipulated through reflection mechanisms. (class file.)

Under which package are the related classes of reflection mechanism?

​ java.lang.reflect.*;

What are the important classes related to reflection mechanism?

java.lang.Class: represents the entire bytecode, represents a type, and represents the entire class.

java.lang.reflect.Method: represents the method bytecode in bytecode. Represents a method in a class.

java.lang.reflect.Constructor: represents the construction method bytecode in bytecode. Represents the construction method in the class

java.lang.reflect.Field: represents the attribute bytecode in bytecode. Represents member variables (static variables + instance variables) in a class.

java.lang.Class: 
public class User{
		// Field
		int no;

		// Constructor
		public User(){
				
		}
		public User(int no){
			this.no = no;
		}

		// Method
		public void setNo(int no){
			this.no = no;
		}
		public int getNo(){
			return no;
		}
}

Three ways to get bytecode

First:
Class c = Class.forName("full class name");

Second:
Class c = object. getClass();

Third:
Class c = int.class;
Class c = String.class;

package reflect;

import java.awt.dnd.DropTarget;
import java.util.Date;

/*
To operate the bytecode of a class, you need to obtain the bytecode of the class first. How to obtain the java.lang.Class instance
    Three ways
        1.The first method: Class.foename
        2.The second method: Class c = reference. getClass();
        3.The third method: Class c = any type. class;
 */
public class Test01 {
    public static void main(String[] args) {
        /*
        Class.forname()
            1.Static method
            2.Method is a string
            3.String requires a complete type
            4.The full class name must have a package name. java.lang cannot be omitted
         */
        Class c1 = null;
        Class c2 = null;
        try {
            c1 = Class.forName("java.lang.String");//c1 represents the String.class file, or c1 represents the String type
            c2 = Class.forName("java.util.Date");//c2 stands for Date type
            Class c3 = Class.forName("java.lang.Integer");
            Class c4 = Class.forName("java.lang.System");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        //Any object in java has a method: getClass()
        String s = "abc";
        Class x = s.getClass();//x represents the String.class bytecode file, and s represents the String type


        Date time = new Date();
        Class y = time.getClass();
        System.out.println(c2 == y); //True. The memory addresses stored in C2 and y variables are the same

        //Third, any type in the java language, including the basic data type, has a class attribute
        Class z = String.class;//z stands for String type
        Class k = Date.class;//k stands for Date type
        Class f = int.class;//f stands for int type
        Class e= double.class;//e stands for double type
        System.out.println(x == z);


    }
}

Instantiate the object through the newInstance method of class

It must be noted that:
The underlying call of newInstance() is the parameterless constructor of this type.
Without this parameterless constructor, an "instantiation" exception will occur.

package reflect;

import bean.User;

/*
Get class, what can I do
    Instantiate the object through the newInstance method of class
    Note: the newInstance() method actually calls the parameterless construction method. You must ensure that the parameterless construction exists

 */
public class Test02 {
    public static void main(String[] args) {
        //Create objects without reflection
        User user = new User();
        System.out.println(user);

        //Get the class through the reflection mechanism and instantiate the object through class
        try {
            Class c = Class.forName("bean.User");
            //Important: newInstance calls a parameterless construct, and the existence of a parameterless construct must be guaranteed
            Object object  = c.newInstance();//newInstance will call user's parameterless construction method to complete the creation of the object
            System.out.println(object);//bean.User@776ec8df
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Verify the flexibility of reflection mechanism

package reflect;

import java.io.FileReader;
import java.util.Properties;

/*
Verify the flexibility of reflection mechanism
 java Write the code once. You can instantiate different objects without changing the java code. It is very flexible (in line with the OCP principle, open to extension and closed to modification)

 In the later stage, we should learn the advanced framework, and we also learn the advanced framework in our work
 Including: SSH, SSM
 */
public class Test03 {
    public static void main(String[] args) {
        //Read the classinfo.properties file through the IO stream
        try {
            FileReader reader = new FileReader("D:\\java\\javaSE\\demo\\src\\reflect\\classinfo.properties");
            //Create attribute class object pr
            Properties properties = new Properties();
            //load
            properties.load(reader);
            //close
            reader.close();
            //Get class name
            String classname = properties.getProperty("className");
            System.out.println(classname);

            //Instantiate objects through reflection mechanism
            Class c = Class.forName(classname);
            c.newInstance();//Create instanced object
            System.out.println(c);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Study classforname

If you only want the "static code block" of a class to execute, what can you do?
Class.forName("class name of the class");
In this way, the class is loaded. When the class is loaded, the static code block is executed!!!!
Here, I am not interested in the return value of this method, mainly to use the action of "class loading".

package reflect;
/*
Study what happened to Class.forname
    Remember: focus
        If you just want a static code block of a class to execute, no other code will execute
        You can use:
            Class.forname("Full class name ")
          This method causes the class to load. When the class is loaded, the static code block is executed

 */
public class Test04 {
    public static void main(String[] args) {
        try {
            //This method causes: class loading
            Class c = Class.forName("reflect.MYcalss");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
class MYcalss{
    //Static code blocks are executed when the class is loaded and only once
    static{
        System.out.println("myclass Class");
    }
}

Questions about paths

The following explanation of how to obtain the absolute path of the file is common, but the premise is that the file can be used in this way only under the class path

String path = Thread.currentThread().getContextClassLoader()
						  .getResource("Write relative path, but this relative path from src Start looking").getPath();	

String path = Thread.currentThread().getContextClassLoader()
					  .getResource("abc").getPath();	//You must ensure that there is an abc file under src.

String path = Thread.currentThread().getContextClassLoader()
					  .getResource("a/db").getPath();	//You must ensure that there is a directory under src and db files under a directory.
String path = Thread.currentThread().getContextClassLoader()
					  .getResource("com/bjpowernode/test.properties").getPath();	
					  //It must be ensured that there is a com directory under src and a bjpowernode directory under com directory.
					  //There is a test.properties file in the bjpwernode directory.

This method is to obtain the absolute path of a file. (it is a general method and will not be affected by environment migration.)
However, the file must be placed under the class path, in other words, under src, which is the root path of the class.

Return directly as a stream:

InputStream in = Thread.currentThread().getContextClassLoader()
							.getResourceAsStream("com/bjpowernode/test.properties");
package reflect;
/*
Questions about paths
 The following explanation of how to obtain the absolute path of the file is common, but the premise is that the file can be used in this way only under the class path
 */
public class Test05 {
    public static void main(String[] args) {
       // try {
        //The disadvantage of this method is poor portability. The default path in idea is the root of the current path project
        //This code assumes that if you leave the IDEA and change to another location, the current path may not be the root of the project
        //FileReader reader = new FileReader("demo/src/reflect/classinfo.properties");

        //Next, let's talk about a more general path. Even if the code changes location, it is also common to write in this way
        //Note: the premise of using the following general method is that this file must be in the classpath
        //What is classpath?
        //Everything under src is under the classpath
        //src is the root path of the class
        /*
           Thread.current() Current thread object
           getContextClassLoader() Is the method of thread object. You can get the classloader object of the current thread
           getResource() [Get resources] this is the method of the classloader object. By default, the classloader of the current thread gets resources from the root path
        */
        String path =Thread.currentThread().getContextClassLoader().getResource("classinfo.properties").getPath();
        System.out.println(path);
        // /D:/java/javaSE/out/production/demo/classinfo.properties
        //Using the above method, you can get the absolute path of a file

        //} catch (FileNotFoundException e) {
        //   e.printStackTrace();
        //}

        //Get the absolute path of db.properties
        String path2 = Thread.currentThread().getContextClassLoader().getResource("src/bean/db.properties").getPath();
        // /D:/java/javaSE/out/production/demo/src/bean/db.properties
        System.out.println(path2);
    }

}

Return as path

package reflect;

import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;

public class IOPropertiseTest {
    public static void main(String[] args) throws IOException {
        //You can get the absolute path of a file
        String path = Thread.currentThread().getContextClassLoader().getResource("classinfo.properties").getPath();
        FileReader fileReader =new FileReader(path);
        Properties properties = new Properties();
        properties.load(fileReader);
        fileReader.close();
        //Get value through key
        String className = properties.getProperty("className");
        System.out.println(className);
        //java.util.Date
    }
}

Returns directly as a stream

package reflect;

import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class IOPropertiseTest {
    public static void main(String[] args) throws IOException {
        //You can get the absolute path of a file
        /*
        String path = Thread.currentThread().getContextClassLoader().getResource("classinfo.properties").getPath();
        FileReader fileReader =new FileReader(path);
        */
        //Return as stream
        InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("classinfo.properties");
        Properties properties = new Properties();
        properties.load(in);
        in.close();
        //Get value through key
        String className = properties.getProperty("className");
        System.out.println(className);
        //java.util.Date
    }
}

Resource binder

A resource binder is provided under the java.util package to obtain the contents of the property configuration file. When using this method, the property configuration file xxx.properties must be placed under the class path

**Requirement: * * first, this file must be in the classpath
Second, the file must end with. properties.

ResourceBundle bundle = ResourceBundle.getBundle("com/bjpowernode/test");
		String value = bundle.getString(key);

The simplest way

package reflect;


import java.util.ResourceBundle;

/*
java.util A resource binder is provided under the package to obtain the content in the property configuration file
 When using this method, the property configuration file xxx.properties must be placed under the classpath
 */
public class ResourceBunleTest {
    public static void main(String[] args) {
        //The resource binder can only bind the xxx.properties file. And this file must be in the classpath. The file extension must also be properties
        //And when writing the path, the extension behind the path cannot be written
        ResourceBundle resourceBundle = ResourceBundle.getBundle("classinfo");
        ResourceBundle resourceBundle1 = ResourceBundle.getBundle("src/bean/db");
        String className = resourceBundle.getString("className");
        String className1 = resourceBundle1.getString("className");
        System.out.println(className);
        System.out.println(className1);

    }
}

Class loader

What is a class loader?

Commands / tools specifically responsible for loading classes.
​ ClassLoader

The JDK comes with three class loaders

Start class loader: rt.jar
Extension class loader: ext/*.jar
Application class loader: classpath

Suppose there is such a code: String s = "abc";

Before the code starts executing, all the required classes will be loaded into the JVM. Load through the class loader. When you see the above code, the class loader will find the String.class file and load it when it finds it. So how do you load it?

First, load through the "start class loader".

Note: start the class loader to load specifically: C:\Program Files\Java\jdk1.8.0_101\jre\lib\rt.jar
rt.jar is the core class library of JDK.

If it cannot be loaded through the "startup class loader",

It is loaded through the extended class loader.
Note: the extension class loader is specially loaded: C:\Program Files\Java\jdk1.8.0_101\jre\lib\ext*.jar

If the extension class loader is not loaded into the

It is loaded through the application class loader.
Note: the application class loader specifically loads classes in the classpath.

In order to ensure the security of class loading, the two parent delegation mechanism is used in java.

Priority is given to loading from the boot class loader, which is called "parent"
"Parent" cannot be loaded into and then loaded from the extension class loader. This is called "parent". Parental delegation. If they cannot be loaded, they will be loaded from the application class loader. Until loaded to.

Access the modifier list / attribute / attribute name of a class attribute through the reflection mechanism

package reflect;

import java.io.File;
import java.io.FileReader;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

public class reflectTest06 {
    //Reflect properties in all student classes
    public static void main(String[] args) throws ClassNotFoundException {
        //Get the entire class
        Class studentclass = Class.forName("reflect.Student");
        //Gets all field s in the class
        //You can get all the exposed properties in the class
        Field[] fields = studentclass.getFields();

        //Class can also getName
        String className = studentclass.getName();
        System.out.println(className);
        System.out.println(studentclass.getSimpleName());
        System.out.println("------------------------");

        System.out.println(fields.length);//1
        Field f = fields[0];
        String fieldName = f.getName();
        System.out.println(fieldName);//no

        System.out.println("--------------------------");
        //Get all fields
        Field[] fds = studentclass.getDeclaredFields();
        System.out.println(fds.length);
        for (Field field:fds){
            //Gets the list of modifiers for the property
            int modifier = field.getModifiers();//The returned modifier is a number, and each number is the code of a modifier
            //You can convert code numbers to strings
            String modifierString = Modifier.toString(modifier);

            //Gets the type of the property
            String fieldTyepe = field.getType().getSimpleName();
            //Get the name of each property
            System.out.println(modifierString + " + " + fieldTyepe + " + " + field.getName());
        }

    }
}

Decompile the properties of a class through reflection mechanism

package reflect;
//Decompile the properties of a class through reflection mechanism
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

public class reflextTest07 {
    public static void main(String[] args) throws ClassNotFoundException {
        StringBuilder stringBuilder = new StringBuilder();//To splice strings

        Class studentClass = Class.forName("reflect.Student");
        Field[] fields = studentClass.getDeclaredFields();

        stringBuilder.append(Modifier.toString(studentClass.getModifiers()) + " class " + studentClass.getSimpleName() + "{" + "\n");
        for(Field field:fields){
            stringBuilder.append("\t");
            stringBuilder.append(Modifier.toString(field.getModifiers()) + " ");
            stringBuilder.append(field.getType() + " ");
            stringBuilder.append(field.getName());
            stringBuilder.append(";" + "\n");
        }


        stringBuilder.append("}");
        System.out.println(stringBuilder);
    }
}

Accessing a class of an object through reflection

package reflect;

import java.lang.reflect.Field;

/*
How to access the properties of an object through reflection mechanism?
    Assign values to attributes
    Gets the value of the property

 */
public class reflectTest08 {
    public static void main(String[] args) throws Exception {
        Class studentclass = Class.forName("reflect.Student");
        Object object = studentclass.newInstance();//Obj is the object of student (the bottom layer calls the parameterless construction method)
        //Get the property (get the field according to the name of the property)
        Field noField = studentclass.getDeclaredField("no");
        //Assign a value to the no attribute
        /*
        Although the reflection mechanism is used, the three elements are still indispensable
            Element 1: obj object
            Element 2: no attribute
            Value of element 3:2
         Note: the reflection mechanism makes the code load, but it's worth it for flexibility
         */
        noField.set(object,2);//Assign 2 to the no attribute of the Object

        //Read the value of the property
        System.out.println(noField.get(object));//Gets the value of the no attribute of the object object

        //Private properties can be accessed
        //Break the encapsulation for access. After setting, you can also access the private attribute externally
        Field namefield = studentclass.getDeclaredField("name");
        namefield.setAccessible(true);
        namefield.set(object,"w");
        System.out.println(namefield.get(object));


    }
}

    }
}

}
class MYcalss{
//Static code blocks are executed when the class is loaded and only once
static{
System.out.println("static code block execution of myclass class");
}
}

### Questions about paths

How to get the absolute path of the file,**The following explanation is common, but the premise is that the file can be used in this way only under the classpath**

String path = Thread.currentThread().getContextClassLoader()
. getResource("write the relative path, but the relative path starts from src"). getPath();

String path = Thread.currentThread().getContextClassLoader()
. getResource("abc"). getPath(); / / ensure that there is an abc file under src.

String path = Thread.currentThread().getContextClassLoader()
. getResource("a/db"). getPath(); / / you must ensure that there is a directory under src and a db file under directory a.




String path = Thread.currentThread().getContextClassLoader()
.getResource("com/bjpowernode/test.properties").getPath();
//It must be ensured that there is a com directory under src and a bjpowernode directory under com directory.
//There is a test.properties file in the bjpwernode directory.

​	**This method is to obtain the absolute path of a file**. (Common mode, not affected by environment migration.)
​	However, the file is required to be placed under the classpath, in other words: it is required to be placed under the classpath src below. src The following is the root path of the class.

​	

Return directly as a stream:

InputStream in = Thread.currentThread().getContextClassLoader()
.getResourceAsStream("com/bjpowernode/test.properties");



```java
package reflect;
/*
Questions about paths
 The following explanation of how to obtain the absolute path of the file is common, but the premise is that the file can be used in this way only under the class path
 */
public class Test05 {
    public static void main(String[] args) {
       // try {
        //The disadvantage of this method is poor portability. The default path in idea is the root of the current path project
        //This code assumes that if you leave the IDEA and change to another location, the current path may not be the root of the project
        //FileReader reader = new FileReader("demo/src/reflect/classinfo.properties");

        //Next, let's talk about a more general path. Even if the code changes location, it is also common to write in this way
        //Note: the premise of using the following general method is that this file must be in the classpath
        //What is classpath?
        //Everything under src is under the classpath
        //src is the root path of the class
        /*
           Thread.current() Current thread object
           getContextClassLoader() Is the method of thread object. You can get the classloader object of the current thread
           getResource() [Get resources] this is the method of the classloader object. By default, the classloader of the current thread gets resources from the root path
        */
        String path =Thread.currentThread().getContextClassLoader().getResource("classinfo.properties").getPath();
        System.out.println(path);
        // /D:/java/javaSE/out/production/demo/classinfo.properties
        //Using the above method, you can get the absolute path of a file

        //} catch (FileNotFoundException e) {
        //   e.printStackTrace();
        //}

        //Get the absolute path of db.properties
        String path2 = Thread.currentThread().getContextClassLoader().getResource("src/bean/db.properties").getPath();
        // /D:/java/javaSE/out/production/demo/src/bean/db.properties
        System.out.println(path2);
    }

}

Return as path

package reflect;

import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;

public class IOPropertiseTest {
    public static void main(String[] args) throws IOException {
        //You can get the absolute path of a file
        String path = Thread.currentThread().getContextClassLoader().getResource("classinfo.properties").getPath();
        FileReader fileReader =new FileReader(path);
        Properties properties = new Properties();
        properties.load(fileReader);
        fileReader.close();
        //Get value through key
        String className = properties.getProperty("className");
        System.out.println(className);
        //java.util.Date
    }
}

Returns directly as a stream

package reflect;

import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class IOPropertiseTest {
    public static void main(String[] args) throws IOException {
        //You can get the absolute path of a file
        /*
        String path = Thread.currentThread().getContextClassLoader().getResource("classinfo.properties").getPath();
        FileReader fileReader =new FileReader(path);
        */
        //Return as stream
        InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("classinfo.properties");
        Properties properties = new Properties();
        properties.load(in);
        in.close();
        //Get value through key
        String className = properties.getProperty("className");
        System.out.println(className);
        //java.util.Date
    }
}

Resource binder

A resource binder is provided under the java.util package to obtain the contents of the property configuration file. When using this method, the property configuration file xxx.properties must be placed under the class path

**Requirement: * * first, this file must be in the classpath
Second, the file must end with. properties.

ResourceBundle bundle = ResourceBundle.getBundle("com/bjpowernode/test");
		String value = bundle.getString(key);

The simplest way

package reflect;


import java.util.ResourceBundle;

/*
java.util A resource binder is provided under the package to obtain the content in the property configuration file
 When using this method, the property configuration file xxx.properties must be placed under the classpath
 */
public class ResourceBunleTest {
    public static void main(String[] args) {
        //The resource binder can only bind the xxx.properties file. And this file must be in the classpath. The file extension must also be properties
        //And when writing the path, the extension behind the path cannot be written
        ResourceBundle resourceBundle = ResourceBundle.getBundle("classinfo");
        ResourceBundle resourceBundle1 = ResourceBundle.getBundle("src/bean/db");
        String className = resourceBundle.getString("className");
        String className1 = resourceBundle1.getString("className");
        System.out.println(className);
        System.out.println(className1);

    }
}

Class loader

What is a class loader?

Commands / tools specifically responsible for loading classes.
​ ClassLoader

The JDK comes with three class loaders

Start class loader: rt.jar
Extension class loader: ext/*.jar
Application class loader: classpath

Suppose there is such a code: String s = "abc";

Before the code is executed, all the required classes will be loaded into the JVM. When you see the above code through the class loader, the class loader will find the String.class file and load it upon finding it. So how do you load it?

First, load through the "start class loader".

Note: start the class loader to load specifically: C:\Program Files\Java\jdk1.8.0_101\jre\lib\rt.jar
rt.jar is the core class library of JDK.

If it cannot be loaded through the "startup class loader",

It is loaded through the extended class loader.
Note: the extension class loader specifically loads: C:\Program Files\Java\jdk1.8.0_101\jre\lib\ext*.jar

If the extension class loader is not loaded into the

It is loaded through the application class loader.
Note: the application class loader specifically loads classes in the classpath.

In order to ensure the security of class loading, the two parent delegation mechanism is used in java.

Priority is given to loading from the boot class loader, which is called "parent"
"Parent" cannot be loaded into and then loaded from the extension class loader. This is called "parent". Parental delegation. If they cannot be loaded, they will be loaded from the application class loader. Until loaded to.

Access the modifier list / attribute / attribute name of a class attribute through the reflection mechanism

package reflect;

import java.io.File;
import java.io.FileReader;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

public class reflectTest06 {
    //Reflect properties in all student classes
    public static void main(String[] args) throws ClassNotFoundException {
        //Get the entire class
        Class studentclass = Class.forName("reflect.Student");
        //Gets all field s in the class
        //You can get all the exposed properties in the class
        Field[] fields = studentclass.getFields();

        //Class can also getName
        String className = studentclass.getName();
        System.out.println(className);
        System.out.println(studentclass.getSimpleName());
        System.out.println("------------------------");

        System.out.println(fields.length);//1
        Field f = fields[0];
        String fieldName = f.getName();
        System.out.println(fieldName);//no

        System.out.println("--------------------------");
        //Get all fields
        Field[] fds = studentclass.getDeclaredFields();
        System.out.println(fds.length);
        for (Field field:fds){
            //Gets the list of modifiers for the property
            int modifier = field.getModifiers();//The returned modifier is a number, and each number is the code of a modifier
            //You can convert code numbers to strings
            String modifierString = Modifier.toString(modifier);

            //Gets the type of the property
            String fieldTyepe = field.getType().getSimpleName();
            //Get the name of each property
            System.out.println(modifierString + " + " + fieldTyepe + " + " + field.getName());
        }

    }
}

Decompile the properties of a class through reflection mechanism

package reflect;
//Decompile the properties of a class through reflection mechanism
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

public class reflextTest07 {
    public static void main(String[] args) throws ClassNotFoundException {
        StringBuilder stringBuilder = new StringBuilder();//To splice strings

        Class studentClass = Class.forName("reflect.Student");
        Field[] fields = studentClass.getDeclaredFields();

        stringBuilder.append(Modifier.toString(studentClass.getModifiers()) + " class " + studentClass.getSimpleName() + "{" + "\n");
        for(Field field:fields){
            stringBuilder.append("\t");
            stringBuilder.append(Modifier.toString(field.getModifiers()) + " ");
            stringBuilder.append(field.getType() + " ");
            stringBuilder.append(field.getName());
            stringBuilder.append(";" + "\n");
        }


        stringBuilder.append("}");
        System.out.println(stringBuilder);
    }
}

Accessing a class of an object through reflection

package reflect;

import java.lang.reflect.Field;

/*
How to access the properties of an object through reflection mechanism?
    Assign values to attributes
    Gets the value of the property

 */
public class reflectTest08 {
    public static void main(String[] args) throws Exception {
        Class studentclass = Class.forName("reflect.Student");
        Object object = studentclass.newInstance();//Obj is the object of student (the bottom layer calls the parameterless construction method)
        //Get the property (get the field according to the name of the property)
        Field noField = studentclass.getDeclaredField("no");
        //Assign a value to the no attribute
        /*
        Although the reflection mechanism is used, the three elements are still indispensable
            Element 1: obj object
            Element 2: no attribute
            Value of element 3:2
         Note: the reflection mechanism makes the code load, but it's worth it for flexibility
         */
        noField.set(object,2);//Assign 2 to the no attribute of the Object

        //Read the value of the property
        System.out.println(noField.get(object));//Gets the value of the no attribute of the object object

        //Private properties can be accessed
        //Break the encapsulation for access. After setting, you can also access the private attribute externally
        Field namefield = studentclass.getDeclaredField("name");
        namefield.setAccessible(true);
        namefield.set(object,"w");
        System.out.println(namefield.get(object));


    }
}

Tags: Java Algorithm JavaSE

Posted on Tue, 12 Oct 2021 15:24:43 -0400 by scorpioy