Follow brother nan to learn java (javase notes)

Introduction to JAVA (4.14)

JDK

JDK (java development kit)

JDK is provided for Java developers, including java development tools and JRE. Therefore, if JDK is installed, JRE does not need to be installed separately

JRE

JRE (Java runtime environment)

Including Java virtual machine (JVM) and core class libraries required by Java programs. If you want to run a developed Java program, the computer only needs to install JRE.

class

First, compile the file with the suffix. java into a. class file that can run on the JVM

cmd use

[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-w3plcpag-16352961140) (assets / CMD use. png)]

cd: transfer path

-Version: View version

Configure environment variables

[the external chain picture transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-3r2h4hux-16352961143) (assets / 1618366391307. PNG)]

[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-khogehvl-16352961146) (assets / 1618366452228. PNG)]

Install java jdk

You can directly unzip the compressed package to the java folder on disk C

Use of jshell

[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-ytspbe5n-16352961150) (assets / 1618369091139. PNG)]

You can write Java applets directly in cmd (generally not required)

JAVA general naming rules

1. Project name all lowercase

2. Package name all lowercase

3. The first letter of the class name is capitalized, and the first letters of other constituent words are capitalized in turn

4. Variable name and method name should be lowercase. If the name is composed of multiple words, the first letter of each word except the first letter should be capitalized

5. Constant names are all uppercase

All naming rules must comply with the following rules:

  • Naming can only consist of letters, numbers, underscores and $symbols

  • Cannot start with a number

  • The name cannot use keywords in JAVA

  • Chinese and Pinyin names are not allowed.

    The java language has 51 keywords, among which const and goto are reserved but not used. Reserved keywords cannot be used to name classes, methods, and variables.

Writing format of notes

Single-Line Comments

//Single-Line Comments 

multiline comment

/*multiline comment */

Document type notes

/**Document type notes*/

data type

1. Data type

Basic data type   byte 1 Bytes short 2 Bytes int  4 Bytes long  8 Bytes float   4 Bytes double  8 Bytes char  2 Bytes boolean One byte
  • Value range of source code complement and inverse code

    The source code complement and inverse code of positive numbers are the same

    The source code of negative numbers is itself, the inverse code is the inverse of other bits except the sign bit, and the complement code is the inverse code + 1

  • Scientific counting represents floating point numbers

    • Convert decimal to binary output

    System.out.println("Integer.toBinaryString()")

    [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-cfhtjiut-1635252961151) (Java notes. assets/image-20210414173429389.png)]

    Character encoding extension

    GBK

    GB2312

    UTF-8

    Unicode (universal code)

    ISO–8859

2. Define variables

Variable: it can save some variable quantities, such as age, income, etc

Convenience: it is convenient to define "everywhere" (within the scope) at one time

Fast: it's actually a memory address, c pointer, java reference

(1) Process

Define int i;

Assignment I = 5; The definition and assignment can be int i = 5 together;

use;

(2) Rules for defining variables

1. Variable names cannot have spaces.

2. Avoid using keywords, class public int static

3. Avoid using Chinese characters

4. The whole hump is named with lowercase initials

5. $and_ It can be used everywhere

6. The number cannot begin

Variables defined outside the main function are member variables

Differences between member variables and local variables

Member variables:

1. Member variables are defined in the class and can be accessed in the whole class.

2. Member variables are created with the creation of the object, disappear with the disappearance of the object, and exist in the heap memory where the object is located.

3. Member variables have default initialization values.

Local variables:

1. Local variables are only defined in the local range, such as within functions and statements, and are only valid in the region to which they belong.

2. Local variables exist in the stack memory. When the scope of action ends, the variable space will be automatically released.

3. Local variables have no default initialization value

The principles to be followed when using variables are: proximity principle

First, find in the local scope and use it if necessary; Then look at the member location.

3. Boolean operation truth table

And

Condition1 condition1Condition2 condition2result
111
100
010
000

or

Condition1 condition1Condition2 condition2result
111
101
011
000

wrong

Condition1 condition1result
10
01

(1) Symbolic representation

& | ! && ||

&&If the short circuit operator is false, the direct result is false and the operation will not continue

||If the short circuit operator is true, the direct result is true and the operation will not continue

4. Arithmetic operator

  +  -  *  /   %    ++   --   +=      -=(1+2)*3

5. Define array

definition

int[]  array = new int[10];

Definition and initialization

int[]  array = new int[]{1,2,3};int[]  array = {1,2,3};

6. Ternary operator

Conditions? Result 1: result 2;

The result of the condition must be boolean, true, false;

Conditions can be complex

boolean condition1 = 5 > 3;boolean condition2 = 5 > 3;boolean condition3 = 5 > 3;int num = (condition1 && (condition2 || condition3)) ? 1 : 2;

7. Displacement operator

[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-vyH9ig3B-1635652961153)(JAVA notes. assets/image-20210415202244232.png)]

Basic data type definition (4.15)

byte b = 10;short s = 100;int i = 1000;long l = 100L;float f = 0.1F;double d = 0.2D;boolean is = true;char c = 'b';

If there is an addition or subtraction between two variables of different types, it will be automatically converted to int or manually forced

Input and output

[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-cHHIfGNh-1635652961154)(JAVA notes. assets/image-20210415212304745.png)]

Cycle judgment (4.16)

1, switch usage

String next = scanner.next();int grade  = 1;switch (next){    case "Baojun":        grade ++;        break;    case "dominate":        System.out.println("Welcome to master.");        grade += 2;        break;    default:        grade += 3;        break;}Can't be long Type can byte shor int     ((not base type) String  

2, Circulation

1,for

for (int j = 1; j <= 9 ; j++) {    for (int i = 1; i <= j ; i++) {        System.out.print("1 * " + i + " = " + i*1 + "\t");    }    System.out.println();}Define condition variables    Entry conditions   ; Variable change    Self increment in order to meet the exit condition            

3, While and do while

int i = 0;while( i < 5){    ......        i++;}do{    ......    i = i + 8;}while(i < 7)Define condition variables    Entry condition variable change    Variables are changed to meet exit conditions

difference

do while must execute the following before judging

Only when the conditions are met can you enter

4, Several keywords

break

In any case, all the current loops should be ended, and the program will continue to execute downward.

contiune

Skip this cycle and continue to the next cycle.

Label

for loop can be labeled. Use break + tag name to exit the labeled loop

flag:for (int i = 0; i < 2; i++) {        for (int j = 0; j < 2; j++) {                if( j > 0 ){                        break flag;               }                System.out.println("===="+j);        }}

array

1, Definition of array

int[] nums = {1,2,3};int[] nums = new int[3];type[] name = new type[length];

2, Properties of arrays

1. Once the array is established, its length cannot be changed.

2. Only one value can be saved in each position, and more values will be overwritten.

3. The number starts with 0 and subscripts.

4. It has a length attribute, and the number of the last position is length - 1.

5. The array can be either a basic type or a reference type.

3, Simple and practical of array

1. Find the maximum value in the form of challenge Arena

int[] salary = {4,5,0,6,7,8};int maxIndex = 0 ;for (int i = 1; i < salary.length; i++) {    if(salary[i] > salary[maxIndex]){        maxIndex = i;    }}System.out.println("Yes n The most valuable subscript obtained in this round of competition is:"+maxIndex+". The values are:"+salary[maxIndex]);

2. Loop through each value of the print array

for (int i = 0; i < salary.length; i++) {    System.out.print(salary[i] +  " ");}

3. Find a value that exists in an array.

int targetIndex = -1;for (int i = 0; i < salary.length; i++) {    if(salary[i] == 9){        targetIndex = i;    }    break;}

4. The displacement of the element.

int[] salary = {4,5,0,6,7,8};int temp = salary[0];salary[0] = salary[1];salary[1] = temp;

4, Sorting algorithm

1. Choose

Each round is looking for a minimum value to be placed at the first of the unordered elements

int[] nums = {4,6,0,8,7};for (int j = 0 ; j < nums.length -1 ; j++){    int minIndex = j;    for (int i = j+1; i < nums.length; i++) {        minIndex =  nums[i] < nums[minIndex] ? i : minIndex;    }    int temp = nums[minIndex];    nums[minIndex] = nums[j];    nums[j] = temp;}for (int i = 0; i < nums.length; i++) {    System.out.print(nums[i] + " ");}

	//Select sort 		 int[] array = {12,4,3,43,56,23,555,14,87,354,65,37,28,54,43,94,56}; 	// 1. Find minimum value 	 for (int y = 0; y < array.length - 1; y++){ 		 int targetArray = y; 	 for (int i = y + 1; i < array.length; i++){ 		 if (array[targetArray] > array[i]){ 			 targetArray = i; 		}	}	// 2. Swap the minimum with the first 	 int middle = 0; 	 middle = array[y]; 	 array[y] = array[targetArray]; 	 array[targetArray] = middle; 	}	// Output each value of the array 	 for (int i = 0 ;i < array.length; i++){ 		 System.out.println(array[i]); 	}

2. Bubbling

Each round is compared in pairs, which will take the biggest to the last

int[] nums = {3, 7, 4, 9, 5, 4, 1};for (int j = 0; j < nums.length - 1 ; j++) {    for (int i = 0; i < nums.length - 1 -j ; i++) {        if (nums[i] > nums[i + 1]) {            int temp = nums[i];            nums[i] = nums[i + 1];            nums[i + 1] = temp;        }    }}for (int i = 0; i < nums.length; i++) {    System.out.print(nums[i] + " ");}
//Bubble sorting 	 int[] array = {12,4,3,43,56,23,555,14,87,354,65,37,28,54,43,94,56}; 	 for (int i = 0; i < array.length - 1; i++){ 		 for (int y = 0; y < array.length - i - 1; y++){ 			 if (array[y] > array[y + 1]){ 				 int middle = array[y]; 				 array[y] = array[y + 1]; 				 array[y + 1] = middle; 			}		}	}	 for(int i = 0; i < array.length; i++){ 		 System.out.println(array[i]); 	}

3. Insert sort

By default, each previous number is ordered. Insert the latter number into the previous ordered number sequence

//Insert sort 	 int[] array = {12,4,3,43,56,23,555,14,87,354,65,37,28,54,43,94,56}; 	 for(int i = 1; i < array.length; i++){ 		// Save the numbers to be arranged 		 int temp = array[i]; 		 for(int j = i-1; j >= 0; j--){ 			 if (array[j] > temp){ 				 array[j+1] = array[j]; 				 if (j == 0){ 					 array[0] = temp; 				}			}			 else{ 				 array[j+1] = temp; 				 break; 						}			}	}

IDEA basic settings (4.17)

Font appearance

[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-uilxzric-1635252961155) (Java notes. assets/image-20210417082729788.png)]

[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-pyi0tyop-1635252961157) (Java notes. assets/image-20210417082846794.png)]

[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-gqqcaa8g-163565961158) (Java notes. assets/image-20210417083655453.png)]

1. Font settings

(1) Setting themes and fonts for non code blocks

file --> settings --->appearance--->theme  Change theme Use custom font Tick to select font and text size
file --> settings --> plugins --> installed --->theme   plug-in unit ctrl art shift +s

(2) Modify the font of the code block

file --> setting -->editor -->font

2. Configure jdk

(1) It can be configured at startup

(2) ctrl + alt + shift + s project configuration

project ---> project Sdk   --> new   Find your own installation jdk Be sure to save Click ok

3. Some shortcuts

main Method input main Boss input psvm Output statement   sout Copy a row   ctrl+D shear       ctrl+X notes    ctrl+/Automatic error correction   alt + enterfori shift+F6ctrl+shift+Next and next lines swap positions ctrl+alt+L     formatting code 

Enhanced for loop and some shortcuts

Enhanced for loop

Value is an independent variable. Each loop assigns the value in the array to value and then prints it. The disadvantage is that the subscript cannot be obtained

int[] arr = {1,2,4,5};for (int value : arr){    System.out.println(value)}

Methods (equivalent to functions in c language), methods encapsulated are called objects, and those describing features are called attributes

Some practical methods

1. Generate random number

Math.random() randomly generates a number from 0 to 1, and because it is a floating-point type, it must be converted to an integer

//Probability, random int a = (int)(Math.random()*10+20);

[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-uPJfyY4W-1635652961159)(JAVA notes. assets/image-20210426094124393.png)]

2. Delay

public static void sleep(int time){    try {        Thread.sleep(time);    }catch (InterruptedException e){        e.printStackTrace();    }

3. Number to string

Anything with a string is a string

[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-sxtlbbwu-163552961160) (Java notes. assets/image-20210420154435699.png)]

4. String to number

[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-c6xcxdou-1635296162) (Java notes. assets/image-20210420162050517.png)]

5. String comparison

Use equals

[the external chain picture transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-y6giu4ss-1635296163) (Java notes. assets/image-20210421161046457.png)]

Get current time

[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-l9or9li-1635296163) (Java notes. assets/image-20210426094936868.png)]

Object oriented (4.19)

Methods (equivalent to functions in c language), methods encapsulated are called objects, and those describing features are called attributes.

import java.util.Scanner;//package... public class Car {/ / you can define a color without assigning a value. Public string color; public int saddle; public void run() {System.out.println("start"); System.out.println("refueling");} / / example: the encapsulated method has a reference (address) stored in the method area stack (high execution efficiency) . basic data type; public static void main(String[] args) {/ * * * construction method * 1 new is actually calling construction method * 2 if there is no construction method in a class, an empty construction method will be automatically created * 3 the construction method can pass parameters and assign the value of the object during construction * 4 once there is a construction method with new parameters, the empty construction will not exist. If you want to ensure If you want to stay, you have to manually write that * Car is a class, and the small Car is a reference (pointing to an area in memory) * 5 overloaded construction method with the same name and different parameters. * / / * * * this keyword refers to the (object) with allocated space in memory ** overloaded * 1 method with the same name * 2 method with different parameter types * 3 method with different return types * 4 method with different modifiers * 5 main method can also be overloaded * * / Car car = new Car(); Car.color = "red" ;        Car.saddle = 4;        Car.run();    }java}

1. Package

Simple and classy, it's a folder

Request

The domain name is written upside down. com.xinzhi must be all lowercase and separated by.

1. When introducing classes written by others, ensure that they do not have the same name.

2. At a glance, you can see which company's works and protective effects.

2. Permission modifier

ScopeCurrent classSame as packageChildren and grandchildrenOther package s
public
protected×
Friendly (default)×
privatekeyiXX

Why

1. For yourself, protect your code from contamination

2. For others, give others a clean class

The access permissions for the protected modifier are as follows:

  • Subclasses and base classes are in the same package: variables, methods and constructors declared as protected can be accessed by any other class in the same package;
  • The subclass is not in the same package as the base class: in the subclass, the subclass instance can access the protected method inherited from the base class, and the subclass cannot access the protected method of the base class instance.

4. Class new object focus

The new object actually calls the constructor, but we find that there is no constructor in the class just written. In fact, if your class has no constructor, the system will send an empty constructor.

Construction method

Construction method    /***  1 new In fact, the constructor is called * 2. If there is no constructor in a class, an empty constructor will be automatically created * 3. The constructor can pass parameters and assign the value of the object during construction * 4. Once there is a constructor with new parameters, the empty constructor will not exist. If you want to keep it, you have to manually write that * car is a class and small car is a reference (pointing to an area in memory) * 5 overloaded construction methods have the same name and different parameters**/

How do we write our own construction method:

The name is exactly the same as the class name, and there can be no difference in case. There can be no return value, and void is not written.

Once you define your own construction method, the system will not give empty construction methods

heavy load

/**Overload * 1 method with the same name * 2 method with different parameter types * 3 method with different return types * 4 method with different modifiers * 5 main method can also be overloaded**/

Key work and difficulty I: understand:

package com.xinzhi.test;/** * @author Zhang Nan * @ date 2020/2/6 */public class Dog {    public static void main(String[] args) {        //Use the parameterless construction method Dog teddy = new Dog(); / / use the setter to assign teddy.setName("golden hair"); system.out.println (Teddy. Getname()); system.out.println ("--------------------------------------"); / / use the parameterless construction method to assign dog golden = new dog ("golden hair") to name directly ; system. Out. Println (golden. Getname()); system. Out. Println ("---------------------------------------"); / / directly check the new object to see if the constructor is called when new. It turns out that it is new dog ("husky");} private string name; public string getname() {return name;} Public void setname (string name) {this.name = name;} / / an empty constructor. The name must be the same as the class name and cannot be a little different. public Dog() {} / / the constructor can be overloaded like other methods and can have parameters. The name must be the same as the class name and cannot be a little different. Public dog (string name) {system.out.println( "Verify when the construction method is called: [" + name + "] is created!"); this.name = name;}} result golden hair ------------------------------------------------------- verify when the construction method is called: [golden hair] is created! Golden hair --------------------------------------------- verify when the construction method is called: [husky] is created!

5. setter and getter, specification, just remember to write it like this

All properties must be privatized:

Setters and getter s are used because methods can control the process of value taking and assignment.

/** * Define dogs * @ author zn * @date 2020/2/2 */public class Dog {        //What are the characteristics / / define the dog's color attribute private String color; / / define the dog's type attribute private String type; / / define the dog's age attribute private int age; / / the Java convention uses setter and getter methods to value and assign the attribute public string getcolor() {return color;} public void SetColor (string color) {this. Color = color;} public string gettype() {return type;} public void setType (string type) {this. Type = type;} public int getage() {return age;} public void setage (int age) {this. Age = age;} / / dogs have many attributes and methods, which we can't list one by one}

6. Encapsulation

Single inheritance, a father can have multiple sons, and a son can only have one father.

There is a top-level parent class called Object. All objects have a parent class called Object. This is a rule. Remember.

Therefore, all objects have all methods of object. Object obj = new Object();

Idea: when an Object calls a method, first look in its own class. If it cannot be found, go to the parent class. If the parent class cannot be found, go to the parent class of the parent class until the Object is found!

Key work and difficult point 2. Understand the same:

//When you create a package, you will automatically create packagepackage com.xinzhi.myextensions; / * * * encapsulate an animal class as the parent class * @ author Zhang Nan * @ date 2020 / 2 / 6 * / public class animal {private string name; public void breath() {system. Out. Println (this. Name + "breathing");} public void eat() {system. Out. Println (this. Name +“ Can eat. ");} public string getname() {return name;} public void setname (string name) {this. Name = name;}}
package com.xinzhi.myextends;/** * Encapsulated birds * @ author Zhang Nan * @ date 2020/2/6 */public class Bird extends Animal {    //Public void fly() {system. Out. Println (this. Getname() + "can fly!");}}
package com.xinzhi.myextends;/** * Package a fish * @ author Zhang Nan * @ date 2020/2/6 */public class Fish extends Animal {    //Fish have independent methods. Swimming public void swimming() {system. Out. Println (this. Getname() + "can swim!");} / / override the breathing method. Because of the special, fish will first look here when calling the breath method. If they find it, they will not go to the parent class to find public void breath() {system. Out. Println ("I breathe with my cheek!");}}
package com.xinzhi.myextends;import java.io.FilterReader;/** * @author Zhang Nan * @ date 2020/2/6 */public class Test {    public static void main(String[] args) {        Bird bird = new Bird();        //If there is no setName method in bird, what should I do? Go to the parent class to find bird.setName("bird")// There is a fly method in bird, which directly calls bird. Fly()// If there is no breath method in bird, what should I do? Go to the parent class to find bird. Breath(); System.out.println("-----------------------------");         Fish fish = new Fish();        // If there is no setName method in fish, what should I do? Go to the parent class to find fish.setName("little fish")// If you find something in your own class, you won't find it in the parent class. This is called overriding the parent class's method fish. breathe()// What if there is no swimming method in fish? Go to the parent class to find fish.swimming();}}

7,String

String is a reference type, but why not use new? Because it is too common, it is simplified.

If you don't feel the trouble, you can also write:

String name = new String("name");actually String name = "name";   That's all

Since it is an object, it has properties and methods:

His method is nothing more than to help us deal with this string conveniently.

Note: when using a string, be sure to note that it must be accepted with a new string.

String substring = name.substring(1, 3);

Cases, these are the best to remember:

String lookup

The indexOf() method of String class finds the position where the substring appears in the String. For example, if it exists, it returns the position where the String appears (the first bit is 0). If it does not exist, it returns - 1.

public class SearchStringEmp {   public static void main(String[] args) {      String strOrig = "xinzhi bigdata Java";      int intIndex = strOrig.indexOf("Java");      if(intIndex == - 1){         System.out.println("String not found Java");      }else{         System.out.println("Java String position " + intIndex);      }   }}

You can also use the contains() method

String substitution

The replace method of the java String class can replace characters in a string.

public class test {    public static void main(String args[]){            String str="Hello World,Hello Java.";            System.out.println(str.replace('H','W')); //Replace all System.out.println(str.replaceFirst("He","Wa"))// Replace the first encountered System.out.println(str.replaceAll("He", "Ha"))// Replace all}}

String segmentation

The split(string) method divides a string into an array by specifying a delimiter.

public class test {    public static void main(String args[]){            String str="www-baidu-com";            String delimeter = "-";  //Specify the separator string [] temp = str.split (delete)// Split string / / ordinary for loop for (int i = 0; I < temp. Length; I + +) {system. Out. Println (temp [i]); system. Out. Println ("");} system. Out. Println ("---- Java for each loop output method -----"); String str1 = "www.baidu.com";            String delimeter1 = "\.";   // Specify the separator. The. Sign needs to be escaped. String [] temp1 = str1.split (deleter1) will not be used tomorrow; for (String x : temp1){                System.out.println(x);                System.out.println("");            }           }}

String truncation

substring(string) method can intercept the string from the first subscript (starting with 0, including this one) to the second subscript (excluding).

public class test {    public static void main(String args[]){        String name = new String("name");        String substring = name.substring(1, 3);    }}

String lowercase to uppercase

The String toUpperCase() method converts the string from small to uppercase.

String str = "string runoob";String strUpper = str.toUpperCase();

8. Wrapper class of base type

Now it's OK to know that there is such a thing. There's no need to practice. There are few important methods to talk about when you use them.

Because the basic type has no method, it is difficult to operate.

All java packages each basic type and generates wrapper classes

int -> Integer

Integer is an object. It was supposed to be new

But it is too common, so it simplifies the definition method, just like the basic type.

Integer i= 3;

Automatic packing = > new Integer (3); If you see that the variable is an Integer and there is no new behind it, you will automatically create a new one for you.

System.out.println(i)

Automatic unpacking is a packaging class, but what needs to be printed here is the basic type, which is automatically transferred.

9. this keyword

this keyword refers to the (object) with allocated space in memory

thinking

First of all, we should think about the role of this project

1. First, think about the function of the system. First, it must be a function and a method. 2. How complex each function is and whether complex functions can be disassembled. For example, a function is divided into three steps. Can each step be defined as a method separately. 3. Think about the logical order of the whole system and when it will be called. 4. Some small functions can be independent methods. Many common codes need to be separated into methods.

Class loading (4.20)

1. Member variables and local variables

There is a default initial value after the member variable attribute definition. The basic data type has an initial value

Basic data type, reference data type and local variable must be initialized manually

All static variables are capitalized, underlined and linked

2. Reference passing and value passing

Reference passes an address and value passes a value

3. Basic data type packing class

[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-jwvyvert-1635252961164) (Java notes. assets/image-20210420161225708.png)]

4. Automatic disassembly box

  • Automatic packing

Convert basic data type to wrapper class

[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-ischcbk1-1635296165) (Java notes. assets/image-20210421081540919.png)]

  • Automatic unpacking

Convert wrapper class to basic data type

[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-qpltsmld-1635296166) (Java notes. assets/image-20210421081620741.png)]

5. Load memory diagram of class

[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-1wksXh0t-1635652961167)(JAVA notes. assets / class loading process. png)]

Succession (4.21)

1. Inherit

  1. Use the extends keyword to implement.

  2. Single inheritance, a father can have multiple sons, and a son can only have one father.

  3. There is a top-level parent class called object. All objects have a parent class called object. This is a rule. Remember. Therefore, all objects can call all methods of object, such as toString().

  4. If new is a subclass, it must first create a parent class. The first sentence in the subclass construction method defaults to super(), which means that when constructing a subclass, it must first construct a subclass.

  5. Override the method of the parent class using the @ override annotation

  6. super

    super points to the referenced parent class, which can be used as the constructor of the parent class

    [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-hwiyuse3-1635252961168) (Java notes. assets/image-20210421114937713.png)]

2. Example diagram

[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-yv7ekuuq-1635252961169) (Java notes. assets/image-20210421111925285.png)]

/** * @author zn * @date 2020/2/10 **/public class Father {    public Father(){        System.out.println("Dad was created");    }    public void say(){        System.out.println("I'm dad");    }}
/** * @author zn * @date 2020/2/10 **/public class Son extends Father {    public Son(){        super();        System.out.println("Son was created!");    }}
/** * @author zn * @date 2020/2/9 **/public class Test {    public static void main(String[] args) {        Son son = new Son();    }}result--Father is created, son is created!

Idea: when an Object calls a method, first look in its own class. If it cannot be found, go to the parent class. If the parent class cannot be found, go to the parent class of the parent class until the Object is found!

Loading order of classes

1. Static attribute of parent class

Called when the class is loaded

When a class is loaded, the class will be actively loaded and loaded into memory for the first time

2. Static code block of parent class

3. Static attributes of subclasses

4. Static code block of subclass

5. Non static attribute of parent class

6. Non static code block of parent class

7. Constructor of parent class

8. Non static attributes of subclasses

9. Non static code block of subclass

10. Constructor of subclass

instanceof and object transformation

instanceof

instanceof determines whether the passed class is the specified parent class

rewrite

When the method of the parent class does not meet the required requirements, it needs to be overridden

[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-ibxit16o-1635252961170) (Java notes. assets/image-20210422092959956.png)]

Static method

Static methods are generally used as tools

The static attribute is usually used as a constant to record something that is constant but can be used everywhere

ToString

[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-qtllmcuf-16352961170) (Java notes. assets/image-20210422173010992.png)]

To print the specific contents and properties of a class, you need to override its ToString method

[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-wkqwcrk2-163552961171) (Java notes. assets/image-20210422173326070.png)]

polymorphic

Premise of existence

1. There must be inheritance

//Define a parent class first

/** * @author zn * @date 2020/2/9 **/public class  Animal {    private String type;    public Animal(String type) {        this.type = type;    }        //All animals can eat public void eat() {system. Out. Println ("animals are eating food");}; Public void breath() {system. Out. Println ("breathing");} public string gettype() {return type;} public void setType (string type) {this. Type = type;}}

2. There must be rewriting

/** * @author zn * @date 2020/2/9 **///It inherits public class dog extends animal {public dog (string type) {super (type);} / / dogs have dog eating methods / / it rewrites @ override public void eat() {system.out.println (this. Gettype() + "eating bones!");} public void enjoy() {system.out.println ("wagging tail!");}}
/** * @author zn * @date 2020/2/9 **///Inherit public class cat extensions animal {public cat (string type) {super (type);} / / rewrite @ override public void eat() {system.out.println (this. Gettype() + "eating fish!");}}

3. A parent class reference should point to a child class object

/** * @author zn * @date 2020/2/9 **/public class Test {    public static void main(String[] args) {        //The parent class reference points to the child class object, which can complete all the work of the parent class. Animal dog= new Dog("puppy"); dog.eat();        // The parent class reference points to the child class object, which can complete all the work of the parent class. Animal cat = new Cat("kitten"); cat.eat();    }}-- As a result, the dog is eating bones! The kitten is eating fish!

Benefit 1: flexibility

/** * @author zn * @date 2020/2/10 **/public class Girl {    public void KeepAnimal(Animal animal){        System.out.println("The little girl began to give"+animal.getType()+"feed.");         System.out.println("The little girl began to give"+animal.getType()+"feed.");        //If there is no overridden method, it is not called polymorphic animal. Breath()// The overridden method will call animal.eat();}}
/** * @author zn * @date 2020/2/9 **/public class Test {    public static void main(String[] args) {        Animal dog= new Dog("puppy");        Animal cat = new Cat("kitten");                //Wu Sanshui has a dog girl WSS = new girl (); wss.KeepAnimal(dog);        // Liu Huihui has a cat girl LHH = new girl (); lhh.KeepAnimal(cat);                // This allows girl to keep animals flexibly}}

There are many benefits, and I'll experience them later

abstract class

Some classes are natural for subclasses to be inherited, not to be called in the parent class. The purpose of such methods is to specify subclasses, and these methods must be used. For example, animal classes require that you implement the eat method and you must rewrite it.

In this case, java proposes an abstract class. In this class, there can be some methods without method body, which we call abstract methods. Abstract methods must be modified with abstract. At the same time, if there are abstract methods, this class must be defined as abstract methods and modified with abstract.

Abstract methods are constraints on subclasses. Whether it's a cat, a dog, a snake or a dragon, he must be able to eat.

/** * @author zn * @date 2020/2/9 **/public abstract class  Animal {    private String type;    public Animal(String type) {        this.type = type;    }    //All animals can eat / / it is specified that this is an abstract method, and the subclass must implement public abstract void eat(); Public void breath() {system. Out. Println ("breathing");} public string gettype() {return type;} public void setType (string type) {this. Type = type;}}

be careful:

  1. Cannot new because some methods do not have a method body. These methods are used to override, which defines that subclasses must have these methods.
  2. It must be inherited to use and must implement all abstract methods
  3. If a class inherits an abstract class, either declare itself as an abstract class; 2. Implement all methods of the abstract class

2. Implement all methods of the abstract class

Interface

When a class is full of abstract methods, we call such methods interface. Omit abstract and change class to interface.

Note: the permission modifier is omitted from the interface and is public by default. One reason is that it must be implemented for subclasses (called override in inheritance).

/** * @author zn * @date 2020/2/10 **/public interface Car {    /**     * Cars can run, no matter what cars can run. The permission modifier is omitted from the interface. It is public by default     */    public void run();    /**     * Cars can seat people, no matter what cars can seat people. The permission modifier is omitted in the interface. It is public by default     */    void ride();}
/** * @author zn * @date 2020/2/10 **///To implement the interface, the keyword implements must implement all the methods inside public class CRV implements car {@ override public void run() {System.out.println("CRV beeping run");} @ override public void ride(){ 		 System.out.println("CRV seats are big and spacious");}}
/** * @author zn * @date 2020/2/10 **/public class Passat implements Car {    @Override    public void run() {        System.out.println("Pasar ran away");    }    @Override    public void ride() {		System.out.println("CRV The seat is dignified and has face");    }}

java is single inheritance, but multiple implementations. A class can implement multiple interfaces, but can only inherit one parent class.

To implement an interface, you must implement all the methods in the interface.

There can only be static constants and abstract methods in the interface.

Static constants can be defined in any class, abstract class and interface. They have no relationship with inheritance, encapsulation, polymorphism and new.

public static final int num  = 1;

Upgraded super array

1. Class name

Simple class name:  SuperLinked Full class name:    com.zhixin.util.SuperLinked   (Package name plus class name)

2. Package introduction

//All contents under the package are imported into import com. Zhixin. Util. *// Only one class import com.zhixin.util.SuperLinked is introduced;

3. Object transformation

Forced Transformation: forced transformation from the type of the parent class to the child class. If the type is really passed in, there is no problem with forced transformation; If not, an error will be reported.

The appropriate method is to use instanceof to judge first and determine the type before processing.

package com.xinzhi.polymorphism;/** * @author zn * @date 2020/2/10 **/public class Girl {    public void KeepAnimal(Animal animal){        //Use instanceof to judge whether the object passed in is a Dog type if(animal instanceof Dog) {/ / forcibly convert it to a subclass Dog dog = (Dog) animal; Dog. Enjoy();} system. Out. Println ("little girl starts feeding" + animal.getType() +)// If there is no overridden method, it is not called polymorphic animal. Breath()// The overridden method will call animal. Eat() according to the actual animal passed in;} Public void buycar (Carola car) {system. Out. Println ("little girl bought a car! Start"); car.run();}}

4. Generics

   when a class does not know the real type of data processed internally, it can use generic type. The method is to add < T > after the class, not necessarily T. other letters are also OK, but it is generally written as t or E. T is an unknown. Only when you specify a certain type when you go to the new object, the T in the code will become the actual type. Think specifically from the code.

2, Project code

package com.zhixin.util;/** * @author zn * @date 2020/2/7 **/public class SuperArray<T> extends Super<T> {    //Maintain an array. If you want to save everything, you need to use the top-level parent class private Object[] array// The lower edge of the current last number should be - 1, which means that the first subscript of the array is 0, private int currentindex = - 1// The construction is to initialize public superarray() {array = new object [8];} / / the method of adding data public void add (t data) {system.out.println ("I am the implementation of array! --- add"); currentindex + +; / / automatic capacity expansion if (currentindex > array. Length-1) {array = division (array);} array [currentindex] = data;} / / query the number public t get (int index) {system.out.println ("I am the implementation of the array -- get"); return (T) array [index];} / / check the current number of numbers public int size() {return currentindex + 1;} / / the method of array expansion private object [] division (object []) Oldarray) {object [] newarray = new object [oldarray. Length * 2]; for (int i = 0; I < oldarray. Length; I + +) {newarray [i] = oldarray [i];} return newarray;} / / verify whether the subscript is legal private boolean validateIndex(int index) {/ / false is returned if one of them is not satisfied. Return index < = currentindex & & index > = 0;}}
package com.zhixin.util;/** * @author zn * @date 2020/2/11 **/public class SuperLinked<T> extends Super<T> {    private Node head = null;    private Node tail = null;    private int length = 0;    //Add the element public void add (t data) {system.out.println ("I am the implementation of linked list ------ add"); node < T > node = new node < > (); node.setnum (data); if (length = = 0) {/ / if there is only one node added for the first time, head = node;} else {/ / and tail.setNextNode(node) ;} / / add the heart as the tail; tail = node; length + +;} / / query the number according to the subscript. It is very interesting to write public t get (int index) {system. Out. Println ("I am the implementation of linked list ------ get"); if (index > length) {return null;} //Tips: node targetnode = head; for (int i = 0; I < index; I + +) {targetnode = targetnode. Getnextnode();} return (T) (targetnode. Getnum());} / / check the current number of numbers public int size() {return length;} class node < T > {/ / stored real data private T num; / / write a node private node nextnode = null; public t getnum() {return num;} public void setnum (t Num) {this. Num = num;} public node getnextnode() {return nextnode;} public void setnextnode (Node nextNode) {            this.nextNode = nextNode;        }    }}
package com.zhixin.util;/** * @author zn * @date 2020/2/11 **/public abstract class Super<T> {    /**     * Mark that all subclass implementations must have an add method to add data * @ param data     */    public abstract void add(T data);    /**     * Mark that all subclass implementations must have get methods to obtain data * @ param index * @ return     */    public abstract T get(int index);    /**     * Mark that all subclass implementations must have a size method, data size * @ return     */    public abstract int size();}

Static inner class (4.24)

usage method

[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-awy2o2by-1635252961172) (Java notes. assets/image-20210424091302922.png)]

If a class is called by only one class, it can be placed inside the class, which is called a static inner class.

Anonymous Inner Class

[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-fagjspca-16352961173) (Java notes. assets/image-20210424093537156.png)]

Interface has no name, but implements all methods

It can only be used once to implement an interface and must be rewritten

Save the inner class and use it several times

[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-cdzakyzs-1635252961174) (Java notes. assets/image-20210424093758226.png)]

Making jar packages and importing jar packages

[the external chain picture transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-nf1eqywg-163565291175) (Java notes. assets/image-20210424094932967.png)] [the external chain picture transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-lkc5b8tk-163565291176) (Java notes. assets/image-20210424095041715.png)]

final

A class modified by final cannot be inherited

The value of the modification variable cannot be changed [the external chain picture transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-ml66kflm-1635252961177) (Java notes. assets/image-20210424104828279.png)]

Set and linked list

LinkedList is essentially a linked list

ArrayList is essentially an array

There is little difference between the two methods

public void Testlist(){    List<User> list = new ArrayList<>();    list.add(new User("Xiao Qian",456));    list.remove(new User("Xiao Qian",456));    for (int i = 0; i < list.size() ; i++) {      System.out.println(list.get(i).getUsername() + list.get(i).getPassword());    }}

Hash

Hashcoad

Convert the string into a group of numbers [the external chain picture transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-8svurcpu-16352961178) (Java notes. Assets / image-202104250848195. PNG)]

What is hash
Hash is a function. The implementation of this function is an algorithm, which obtains a hash value through a series of algorithms. At this time, we need to know another thing, the hash table. The hash value obtained through the hash algorithm is in this hash table, that is, the hash table is composed of all hash values. There are many kinds of hash functions, This means that there are many algorithms to get hash values. Writing hash functions is an old research topic and a research task for mathematicians and theoretical computer scientists. We only need to know what is easy to use and why

What is hashcode
hashcode is obtained through the hash function. Generally speaking, it is obtained through an algorithm. hashcode has a corresponding position in the hash table.

Every object has a hashcode. How do you get the hashcode of the object?

First of all, an object must have a physical address. Some people on the Internet say that the hashcode of the object is the address of the object. In fact, this view is not comprehensive. It is true that some JVM s directly return the storage address of the object during implementation, but most of the time it is not. It can only be said that the storage address is related to a certain extent,

So how do objects get hashcode? The internal address (that is, the physical address) of the object is converted into an integer, and then the integer is hashcode through the algorithm of hash function (the implementation of different JVMs is different, and the implementation of hotspot is attached at the end). Therefore, what is hashcode? Is the corresponding position in the hash table. If it is not clear here, for example, there are eight positions in the hash table where hashcode is 1, hashcode is 2, (...) 3, 4, 5, 6, 7 and 8, and there is an object A. the physical address of A is converted to an integer 17 (this is if). Through the direct remainder algorithm, 17% 8 = 1, then the hashcode of A is 1, and A is at the position of 1 in the hash table.

Why HashCode
hashCode exists mainly for the convenience of searching. hashCode is used to determine the storage address of the Object in the hash storage structure (hashCode is used to represent the position of the Object in the hash table). One of the important reasons for the existence of hashCode is that it is used in HashMap(HashSet is actually HashMap) (in fact, the hashCode method annotation of Object class has been explained), HashMap is fast because it uses a hash table to generate an array subscript according to the hashCode value of the key (you do not need to judge directly by the memory address, but you need a lot of more memory, which is equivalent to exchanging space for time)

HashMap

[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-vj5iivys-16352961179) (Java notes. assets/image-20210425091928855.png)]

[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-Ji20aV2L-1635652961180)(JAVA notes. assets/image-20210425085027641.png)]

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-ggZkIhk9-1635652961181)(JAVA notes. assets/image-20210425084737456.png)]

In HashMap, if the keys are the same, the previous one will be overwritten

Traverse HashMap

[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-fdhu1ane-16352961182) (Java notes. assets/image-20210425090605462.png)]

Hash is out of order and cannot be sorted

HashSet

When storing, there is only Key but no value. Duplicate values cannot be stored

[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-k54mnwyh-1635252961183) (Java notes. assets/image-20210425091742912.png)]

Because there is no subscript, use enhanced for traversal

iterator

iterator

[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-zphu9frg-16352961184) (Java notes. assets/image-20210425163548845.png)]

[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-TvgcasHX-1635652961186)(JAVA notes. assets/image-20210425163104329.png)]

HashMap traverses using iterators

[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-nD14ojyE-1635652961187)(JAVA notes. assets/image-20210425170434967.png)]

!!! Delete an element using an iterator

The difference between Collections and Collections in Java

1. java.util.Collection is a collection interface (a top-level interface of a collection class). It provides general interface methods for basic operations on collection objects. The collection interface has many specific implementations in the Java class library. The meaning of the collection interface is to provide a maximized unified operation mode for various specific collections. Its direct inheritance interfaces include List and Set.

2. Collections is a tool class / help class of the collection class, which provides a series of static methods for sorting, searching, thread safety and other operations on the elements in the collection.

Variable parameters

public int sun (...nums){} //... num stands for variable parameters

Variable parameters must be placed at the end, and there can only be one method [the external chain picture transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-nydxm2eh-16352961188) (Java notes. assets/image-20210427154149908.png)]

Data method

Timestamp

Timestamp refers to the total number of milliseconds from 00:00:00 GMT on January 1, 1970 (8:00:00 GMT on January 1, 1970) to the present

Data usage

[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-cqwuidmp-1635252961188) (Java notes. assets/image-20210427161345111.png)]

Calendar Class Calender

Create Calendar object
Calendar is an abstract class and cannot be instantiated directly. Therefore, calendar provides a method getInstance to obtain a calendar object. The resulting calendar is initialized by the current time

Calendar cal = Calendar.getInstance();

[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 glpoilcg-163525961189) (Java notes. assets/20181205012638154.png)]

[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-3a7ukylb-1635296190) (Java notes. assets/20181205012900902.png)]

Months start from 0 (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)

[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-txbrixh0-1635252961191) (Java notes. assets/image-20210502104405044.png)]

[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-kznjvytw-1635252961192) (Java notes. assets/image-20210502104435087.png)]

Design mode (5.2)

Most frequently asked (abstract factory, agent, singleton)

Single case

There can only be one instance object in heap memory, which is called a singleton

Singleton mode
Singleton pattern is one of the simplest design patterns in Java. This type of design pattern is a creation pattern, which provides the best way to create objects. This pattern involves a single class that is responsible for creating its own objects while ensuring that only a single object is created. This class provides a way to access its unique object, which can be accessed directly without instantiating the object of this class.
1. A singleton class can only have one instance.
2. A singleton class must create its own unique instance.
3. A singleton class must provide this instance to all other objects.
Intent: ensure that a class has only one instance and provide a global access point to access it. Main solution: a globally used class is frequently created and destroyed.
When to use: when you want to control the number of instances and save system resources.
How to solve it: judge whether the system already has this single instance. If yes, it will be returned. If not, it will be created. Key code: constructors are private.

Hungry Han style single case

[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-udcz0kay-1635252961193) (Java notes. assets/image-20210502113501649.png)]

Is thread safe

Lazy single case

[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-vQ89sLow-1635652961194)(JAVA notes. assets/image-20210502130338279.png)]

The thought of merging

public static int[] Lianjie(int[] a1,int[] a2){    //Define a new array int [] stamp = New Int [A1. Length + A2. Length]; int left = 0;     int right = 0;     int con = 0; 	     while (a1.length != left){        if (a1[left] > a2[right]){            tamp[con] = a2[right];            right++;        }else {            tamp[con] = a1[left];            left++;        }        con++;    }    if (con >= a1.length){        for (int i = right; i < a2.length ; i++) {            tamp[con++] = a2[i];        }    }    if  (con >= a2.length){        for (int i = left; i < a1.length ; i++) {            tamp[con++] = a1[i];        }    }    return tamp;}

Thread

The difference between process and thread: a software is a process. A process can run multiple threads. We can use multiple threads to execute at the same time to improve efficiency.

When multiple threads execute at the same time, there is no necessary order between them. It is determined by the scheduling of cpu.

The starting thread must call the start method, not run. Calling run is just a method call. Start is a native local method that will call cpu resources and open up threads.

synchronized ensures thread safety

List thread is not safe. Vector is thread safe

[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 wnpbhace-1635296195) (Java notes. assets/image-20210503112117934.png)]

HashMap is not thread safe, but HashTable is thread safe

String,StringBuffer,StringBuilder

Unlike the String class, the objects of the StringBuffer and StringBuilder classes can be modified multiple times without generating new unused objects.
The StringBuilder class is proposed in Java 5. The biggest difference between it and StringBuffer is that the StringBuilder method is not thread safe (cannot be accessed synchronously) . because StringBuilder has a speed advantage over StringBuffer, = = it is recommended to use StringBuilder class in most cases. = = however, when the application requires thread safety, you must use StringBuffer class.

[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-sx0bcmmm-1635296195) (Java notes. assets/image-20210503120204509.png)]

[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 nuleslzt-16352961196) (Java notes. assets/image-20210503121248118.png)]

UUAD

Generate a unique string in the world

[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-fo9lkslj-16352961197) (Java notes. assets/image-20210503121740825.png)]

abnormal

[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-iqjmxmtv-163552961197) (Java notes. assets/image-20210503123907041.png)]

[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-pqii5ekf-16352961198) (Java notes. assets/image-20210503124017044.png)]

[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-xxshxpgu-16352961198) (Java notes. assets/image-20210503124434268.png)]

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-hvxvvkoc-1635296199) (Java notes. assets/image-20210503124457226.png)]

InterruptedException

Throw the exception up one level

public static void main(String[] args) throws InterruptedException {    time();}public static void time() throws InterruptedException {    Thread.sleep(200);}

try{ }catch( ){ }

[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-hOKzn4Ce-1635652961200)(JAVA notes. assets/image-20210504094911509.png)]

If an Exception inherits from Exception, it is a checking Exception

==The printStackTrace() = = method means to print the exception information on the command line, the location and cause of the error in the program.

System.out.println(e), this method prints out exceptions and prints out where exceptions occur, but it is different from another e.printStackTrace() method. The latter also prints exceptions, but it will also show deeper call information

2. Function of throw

Throw exceptions manually, but sometimes some errors are not errors in the view of the jvm, for example
int age = 0;
age = -100;
System.out.println(age);

It's normal to assign values to shaping variables, but it's not normal in our eyes. Whose age will be negative. So we need to throw exceptions manually, which is the function of throw
int age = 0;
age = -100;
if(age<0)
{
Exception e = new Exception(); / / create exception object
throw e; / / throw an exception
}
System.out.println(age);

3. Function of throws

If an exception is thrown, it needs to be handled. Therefore, there is a try catch in java. However, sometimes an exception occurs in a method, but you don't know how to deal with it, so leave it alone. When an exception is thrown, the method will be interrupted, and the exception will be thrown to the caller of the method. This is a bit like handing over problems that cannot be handled by subordinates to superiors. This situation is called avoiding exceptions, but it makes calling this method dangerous, because no one knows when this method will throw an exception to the caller, so when defining the method, You need to use throws in the method header to declare exceptions that the method may avoid

throws and throw

**throws:

It is used to declare all exceptions that may be generated by a method. Instead of doing any processing, it uploads the exceptions to whoever calls me.
Used after the method declaration, followed by the exception class name
It can be separated from multiple exception class names by commas
Indicates that an exception is thrown and handled by the caller of the method
throws indicates a possibility of exceptions that do not necessarily occur
throw:

Is used to throw a specific exception type.
Used in the method body, followed by the exception object name
Only one exception object name can be thrown
Indicates that an exception is thrown and handled by the statement in the method body
Throw throws an exception, and executing throw must throw an exception

Runtime exception

ArithmeticException arithmetic exception

ClassCastException: class conversion exception

Null pointerexceptionextends null pointer exception

Checking abnormality

ClassNotFoundException, class not found

InterruptedException, interrupt exception

ioException

SQLException,

TimeoutException,

FileNotFoundException

Getting started with java IO

1, Concept of java IO stream

java io is the basis of input and output. It can easily realize data input and output operations. In java, different input / output sources (keyboard, file, network connection, etc.) are abstractly expressed as "stream".

2, Classification of Io flow:

According to different classification methods, streams can be divided into different types. There are three common classifications:

1. According to the flow direction, the flow can be divided into input flow and output flow.

  • Input stream: data can only be read from, not written to.
  • Output stream: data can only be written to it, not read from it.
    The input and output here involve one direction. For the data flow as shown in Figure 15.1, the data from memory to hard disk is usually called output flow - that is, the input and output here are divided from the perspective of the memory where the program runs.

For the data flow as shown in Figure 15.2, the data flows from the Server to the Client through the network. In this case, the memory on the Server side is responsible for outputting the data to the network, so the program on the Server side uses the output stream; The Client side memory is responsible for reading data from the network, so the Client side program should use the input stream.

[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-ynam9gxh-163552961201) (Java notes. assets/11798292-1268450dfccafde7.png)]

2. According to the division of operation units, it can be divided into byte stream and character stream.

The usage of byte stream and character stream is almost the same. The difference is that the data units operated by byte stream and character stream are different. The unit operated by byte stream is the data unit, which is 8-bit byte, and the character stream operates the data unit, which is 16 bit character.

The byte stream mainly uses InputStream and outPutStream as the base class, while the character stream mainly uses Reader and Writer as the base class.

3. According to the role of flow, it is divided into node flow and processing flow.

The stream that can read / write data from / to a specific IO device (such as disk and network) is called node stream. Node flows are also called low-level flows. Figure 15.3 shows a schematic diagram of node flow. Where you need it.

As can be seen from figure 15.3, when using node flow for input and output, the program is directly connected to the actual data source and the actual input / output node.

The processing stream is used to connect and encapsulate an existing stream, and the data read / write function is realized through the encapsulated stream. Processing flows are also called high-level flows. Figure 15.4 shows a schematic diagram of the process flow.

[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-grh2lpqs-16352961201) (Java notes. assets/11798292-52e163c670a11e01.png)]

4. Classification table of streams commonly used in java input / output stream system

|Classification | byte input stream | byte output stream | character input stream | character output stream|

classificationByte input streamByte output streamCharacter input streamCharacter output stream
Abstract base classInputStreamOutputStreamReaderWriter
access filesFileInputStreamFileOutputStreamFileReaderFileWriter
Access arrayByteArrayInputStreamByteArrayOutputStreamCharArrayReaderCharArrayWriter
Access stringStringReaderStringWriter
Buffer streamBufferedInputStreamBufferedOutputStreamBufferedReaderBufferedWriter
Conversion flowInputStreamReaderOutputStreamWriter
Object flowObjectInputStreamObjectOutputStream

The conversion stream can flow characters into byte stream

[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-u6nevdyn-16352961202) (Java notes. assets/20161220152558257)]

3, Specific operation

1. Basic operation of files

@Testpublic void testFile() throws Exception{    //Create file file = new file ("E: \ \ test \ \ b.txt"); file.createNewFile();    // View the file in the folder File2 = new file ("E: \ \ test \ \ b.txt"); String[] list = file2.list();     For (int i = 0; I < list. Length; I + +) {system. Out. Println (list [i]);} / / check other methods by yourself}

2. Copy file with progress bar

@Testpublic void testFileInputStream() throws Exception {    File file = new File("E:\\test\\a\\233.mp4");    //Get the file size long dataLength = file.length()// Build an input stream, and its data will flow into memory. Our program InputStream inputStream = new FileInputStream(file)// Build an output stream whose data will flow from memory (our program) to another folder OutputStream outputStream = new FileOutputStream("E:\test\b\233.mp4")// A new water pump can store a little water, 1K byte [] buffer = new byte [1024 * 1024 * 50] each time; Long currentLength = 0L;    // If read returns - 1, it indicates that int len has been read; int showNumber = 0;     While ((len = InputStream. Read (buffer))! = - 1) {OutputStream. Write (buffer, 0, len); currentlength + = len; / / what percentage of int currentper = (int) (((double) currentlength / datalength) * 100) is currently loaded. / / the purpose is not to display if (shownumber! = currentper) repeatedly {shownumber = currentper; system. Out. Println ("percent copied + shownumber);}} OutputStream. Flush(); OutputStream. Close(); InputStream. Close();}

3. Byte stream read file

@Testpublic void testInputStream() throws Exception{    //An input stream is connected to the file InputStream wordInput = new FileInputStream("E:\test\a\word.txt")// Create buffer byte [] bytes = new byte [1024]; int len;     while ( (len = wordInput.read(bytes)) != -1 ){        System.out.println(new String(bytes,0,len, Charset.forName("ISO8859-1")));    }    wordInput.close();}

4. Character stream pair file

@Testpublic void testReader() throws Exception{    //Connect an input stream to the file reader reader = new FileReader ("E: \ \ test \ \ a \ \ word. TXT"); BufferedReader br = new BufferedReader(reader);     String str;     while ((str = br.readLine()) != null){        System.out.println(str);    }    reader.close();     br.close();}

5. Write to the file

//Use the main method to test public void testWriter() throws Exception {/ / an input stream is connected to a file. Writer writer = new filewriter ("E: \ \ test \ \ a \ \ writer. TXT"); bufferedwriter BW = new bufferedwriter (writer); scanner = new scanner (system. In); while (true) {system. Out. Print ("please enter:") ;        String words = scanner.next();        bw.write(words);        bw.flush();    }}

6. StringReader is to connect to a String

@Testpublic void testStringReader() throws Exception{    //Connected a string OutputStream OS = new fileoutputstream ("E: \ \ test \ \ a \ \ user. TXT"); ObjectOutput oo  = new ObjectOutputStream(os);     OO. Writeobject (new user ("Mr. Wang", 3,4)); oo.flush();     oo.close();     os.close();}

7. Object stream is to serialize the new object

The object must implement the Serializable interface to be serialized.

Objects in memory are a pile of 0 and 1. Any file in memory is 0 and 1, which can be transformed into a byte array for storage or network transmission.

The same is true for object serialization, which is to save memory objects in the form of byte arrays. We can save them on disk or transfer them over the network.

import java.io.Serializable;/** * @author zn * @date 2020/2/14 **/public class User implements Serializable {    private String name;    private int age;    private int gander;    public User(String name, int age, int gander) {        this.name = name;        this.age = age;        this.gander = gander;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }    public int getGander() {        return gander;    }    public void setGander(int gander) {        this.gander = gander;    }}
@Testpublic void testObjectOut() throws Exception{    //A string InputStream is = new FileInputStream ("E: \ \ test \ \ a \ \ user. TXT"); ObjectInputStream oi  = new ObjectInputStream(is);     User user = (User)(oi.readObject());     System.out.println(user.getName());     is.close();     oi.close();}

4, Introduction to flush() method

Referring to the documentation, it can be found that each class in the IO stream implements the Closeable interface. After resource operations, they need to execute the close() method to close the stream. But the difference between byte stream and character stream is that byte stream directly interacts with data, and character stream needs to pass through a buffer before interacting with data.
Sketch:
[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-GS39TjAw-1635652961203)(JAVA notes. assets/20160825235002516)]

When using character stream to operate resources, if the close() method is not used, the read data will be saved in the buffer. There are two ways to empty the data in the buffer:

  • public abstract void close() throws IOException
    When the stream is closed, the data in the buffer will be emptied. This abstract method is implemented by a specific subclass

  • public abstract void flush() throws IOException
    If the stream is not closed, the data in the buffer can be emptied by using this method, but it should be noted that this method is only owned by the Writer class or its subclass, but not provided in the Reader class. This method is also implemented in specific subclasses.

Client and server

The server

public class QQsocket {    public static void main(String[] args) {        ServerSocket server;        InputStream inputStream = null;        try {                //Create a server server = new ServerSocket()// Connect a port server.bind(new InetSocketAddress(8888))// Wait for input data Socket acc = server.accept()// Waiting to receive InputStream with stream = acc.getinputstream(); byte[] by = new byte[1024];                 int len ;                 while ((len = inputStream.read(by) )!= -1){                    System.out.println(new String(by,0,len));                }            } catch (IOException e) {                e.printStackTrace();            }finally {                if (inputStream != null){                    try {                                         inputStream.close() ;                    } catch (IOException e) {                        e.printStackTrace();                    }                }            }    }

client

public class qq {    public static void main(String[] args) {        Socket socket = new Socket();        OutputStream outputStream = null;        try {            socket.connect(new InetSocketAddress("172.16.1.243", 8888));             outputStream = socket.getOutputStream();            String nas = "good morning~~~Xiaoqian!";            outputStream.write(nas.getBytes());        } catch (IOException e) {            e.printStackTrace();        }finally {            if (outputStream != null){                try {                    outputStream.flush();                    outputStream.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        }    }}

serialization and deserialization

1. What are serialization and deserialization

(1) Java serialization refers to the process of converting Java objects into byte sequences, while Java deserialization refers to the process of restoring byte sequences into Java objects;

(2) * * serialization: * * the main purpose of object serialization is to ensure the integrity and transitivity of objects when passing and saving objects. Serialization is to convert an object into an ordered byte stream for transmission on the network or saving in a local file. The serialized byte stream stores the state of the Java object and the related description information. The core function of serialization mechanism is the preservation and reconstruction of object state.

(3) * * deserialization: * * after the client obtains the serialized object byte stream from the file or the network, the object is reconstructed through deserialization according to the object state and description information saved in the byte stream.

(4) In essence, serialization is to write the entity object state to the ordered byte stream according to a certain format. Deserialization is to reconstruct the object from the ordered byte stream and restore the object state.

2. Why do I need serialization and deserialization

We know that when two processes communicate remotely, they can send various types of data to each other, including text, pictures, audio, video, etc., and these data will be transmitted on the network in the form of binary sequence.

So when two Java processes communicate, can object transfer between processes be realized? The answer is yes! How? This requires Java serialization and deserialization!

In other words, on the one hand, the sender needs to convert the Java object into a byte sequence and then transmit it on the network; On the other hand, the receiver needs to recover the Java object from the byte sequence.

When we understand why we need Java serialization and deserialization, we naturally think about the benefits of Java serialization. The first advantage is to realize the persistence of data. Through serialization, the data can be permanently saved to the hard disk (usually stored in the file). The second is to realize remote communication by serialization, that is, to transmit the byte sequence of the object on the network.

In general, it can be summarized as follows:

  • Permanently save the object, and save the byte sequence of the object to the local file or database;
  • The object is transmitted and received in the network in the form of byte stream through serialization;
  • Passing objects between processes through serialization;

enum enumeration

What is enumeration

We have studied the singleton pattern, that is, there is only one instance of a class. Enumeration is actually multiple instances. A class has multiple instances, but the number of instances is not infinite, but finite. For example, there are several alignment methods for word documents: left alignment, center alignment, and right alignment. There are several driving directions: front, rear, left and right!
We call the instance in the enumeration class an enumeration item! Generally, the number of enumeration items of an enumeration class should not be too many. If an enumeration class has 30 enumeration items, it will be too many!

Define enumeration type

enum keyword is required to define enumeration type, for example:

public enum Direction {    FRONT, BEHIND, LEFT, RIGHT;}Direction d = Direction.FRONT;

Note that the keyword defining the enumeration class is enum, not enum, and all keywords are lowercase!
FRONT, BEHIND, LEFT and RIGHT are enumeration items. They are all instances of this class. There are only four instance objects in this class.
When defining enumeration items, multiple enumeration items are separated by commas. Semicolons are required after the last enumeration item! However, if there are only enumeration items (no constructors, methods, instance variables) in the enumeration class, you can omit the semicolon! It is recommended not to omit semicolons!
You cannot use new to create an object of an enumeration class, because the instance in the enumeration class is the enumeration item in the class, so you can only use the class name. Enumeration item outside the class.

Enumeration and switch

Enumeration types can be used in switch

Direction d = Direction.FRONT;  switch(d) {    case FRONT: System.out.println("front");break;    case BEHIND:System.out.println("behind");break;    case LEFT:  System.out.println("left side");break;    case RIGHT: System.out.println("right side");break;    default:System.out.println("Wrong direction");}Direction d1 = d;System.out.println(d1);

Note that in the switch, the enumeration class name cannot be used, for example: "case Direction.FRONT:" this is wrong, because the compiler will determine each enumeration type according to the type of d in the switch. In the case, the enumeration option of the same type as d must be given directly, and there can be no more types.

  1. All enumeration classes are subclasses of Enum
    All enumeration classes are subclasses of Enum class by default, and we do not need to use extensions to inherit. This means that all enumeration classes of methods in Enum have.
  • Int CompareTo (E, e): compare the two enumeration constants. In fact, the comparison is the order in which the enumeration constants are declared in the enumeration class. For example, if the subscript of FRONT is 0 and the subscript of BEHIND is 1, then FRONT is less than BEHIND;
  • boolean equals(Object o): compare whether two enumeration constants are equal;
  • int hashCode(): returns the hashCode of the enumeration constant;
  • String name(): returns the name of the enumeration constant;
  • int ordinal(): returns the sequence number of the enumeration constant declared in the enumeration class. The sequence number of the first enumeration constant is 0;
  • String toString(): convert enumeration constants into strings;
  • static T valueOf(Class enumType, String name): converts a string into an enumeration constant.

Constructor of enumeration class

Enumeration classes can also have constructors. Constructors are private modifiers by default, and can only be private. Because the instance of enumeration class cannot be created by the outside world!

enum Direction {    FRONT, BEHIND, LEFT, RIGHT;//[a semicolon must be added after the enumeration constant because it is required when there are other members after the enumeration constant. The enumeration constant must be declared above all members in the enumeration class.]Direction()// [the constructor of an enumeration class cannot add an access modifier. The constructor of an enumeration class is private by default. However, you cannot add private to modify the constructor yourself.] {System.out.println("hello");}}

In fact, creating an enumeration item is equivalent to calling the parameterless constructor of this class, so the four enumeration items FRONT, BEHIND, LEFT and RIGHT are equivalent to calling the parameterless constructor four times, so you will see four hello outputs.

Enumeration classes can have members

In fact, like normal classes, enumeration classes can have instance variables, instance methods, static methods, etc., but the number of instances is limited and can no longer create instances.

enum Direction {    FRONT("front"), BEHIND("behind"), LEFT("left"), RIGHT("right");        private String name;        Direction(String name) {        this.name = name;    }        public String getName() {        return name;    }}Direction d = Direction.FRONT;System.out.println(d.getName());

Because the Direction class has only a unique constructor and is a constructor with parameters, when creating an enumeration item, you must assign a value to the constructor: FRONT("front"), where "front" is the parameter passed to the constructor. Don't despise this syntax. What you should do is to accept this syntax!
There is also an instance field in the Direction class: String name. We assign a value to it in the constructor. Moreover, this class also provides the instance method getName(), which will return the value of name.

  1. Enumeration classes can also have abstract methods
    You can also give abstract methods in the enumeration class, and then use the "special" syntax to repeat the abstract methods when creating each enumeration item. The so-called "special" syntax is an anonymous inner class! That is, each enumeration item is a subclass object of an anonymous class!

Generally, the fun() method should be defined as an abstract method, because every enumeration constant overrides it.
You cannot declare Direction as an abstract class, but you need to declare the fun() method as an abstract method.

enum Direction {    FRONT() {        public void fun() {            System.out.println("FROND: Rewritten fun()method");        }    },     BEHIND() {        public void fun() {            System.out.println("BEHIND: Rewritten fun()method");        }    },     LEFT() {        public void fun() {            System.out.println("LEFT: Rewritten fun()method");        }    },    RIGHT() {        public void fun() {            System.out.println("RIGHT: Rewritten fun()method");        }    };        public abstract void fun()[Just put fun()Method is modified to be an abstract method, but you can't Direction Class is declared as an abstract class.];}
  1. Each enumeration class has two special methods
    Each enumeration class has two static methods that can be called without declaration, and these two methods are not methods in the parent class. This is another special place of the enumeration class. The following is the special method of the Direction class.
  • static Direction[] values(): returns all enumeration constants of this class;
  • static Direction valueOf(String name): returns the Direction constant by enumerating the name of the constant. Note that this method has different parameters from the valueOf() method in Enum class.

generic paradigm

1, What is generics?

Java generic design principle: as long as there is no warning at compile time, there will be no ClassCastException exception at run time

Generics: special types that postpone the type - specific work until the object is created or the method is called

Parameterization type:

  • Pass the type as an argument
  • < data type > can only be a reference type

Related terms:

  • E in ArrayList < E > is called type parameter variable
  • The Integer in ArrayList < Integer > is called the actual type parameter
  • The whole is called ArrayList < E > generic type
  • The entire ArrayList < integer > is called ParameterizedType

2, Why do I need generics

Early Java used Object to represent any type, but the downward transformation had the problem of strong transformation, so the program was not very safe

First, let's imagine: what would happen to a collection without generics

  • Collection and Map collections have no restrictions on the type of elements. Originally, all Dog objects were loaded in my collection, but there was no syntax error when storing Cat objects in the collection.
  • When an Object is thrown into a collection, the collection does not know what the type of element is, but only knows that it is an Object. Therefore, in get(), Object is returned. To get the Object outside, you also need to cast

With generics:

  • More concise code [no coercion]
  • The program is more robust [as long as there is no warning at compile time, there will be no ClassCastException exception at run time]
  • Readability and stability [when writing a collection, it defines the type]

2.1 use enhanced for to traverse collections with generics

When creating a collection, we have defined the type of the collection, so we can use the enhanced for to traverse the collection!

        //Create a collection object ArrayList < string > List = new ArrayList < > (); list.add("hello");         list.add("world");         list.add("java");        // Traversal. Since the type is specified, we can enhance for (string s: list) {system. Out. Println (s);}

3, Generic basis

3.1 generic classes

A generic class defines a generic type on a class. When users use the class, they define the type... In this way, the user knows what type the class represents... When users use it, they don't have to worry about forced conversion and runtime conversion exceptions.

  • Generics defined on a class can also be used in class methods!
/*    1:Define generics on class 2: type variables are defined on class, and can also be used in methods */public class ObjectTool<T> {    private T obj;    public T getObj() {        return obj;    }    public void setObj(T obj) {        this.obj = obj;    }}
  • Test code:

The type you want to use is specified when you create it. When used, the class will be automatically converted to the type that the user wants to use.

    public static void main(String[] args) {        //Create an object and specify the element type objecttool < string > tool = new objecttool < > (); Tool. Setobj (new string ("Zhong Fucheng"); String s = tool.getObj();        System.out.println(s);        // Create an object and specify the element type objecttool < integer > objecttool = new objecttool < > (); / * ** If I pass in string type in this object, it will not pass during compilation. * / objecttool. Setobj (10); int i = objectTool.getObj();         System.out.println(i);    }

3.2 generic methods

Generic classes have been introduced earlier. Generics defined on classes can also be used in methods

Now, we may only need to use generics on a certain method... The outside world only cares about the method and does not care about other properties of the class... In this case, we will make a fuss about defining generics on the whole class.

  • Define generic methods... Generics are defined before they are used
    //Define generic methods.. public < T > void show (T) {system. Out. Println (T);}
  • Test code:

What type is passed in by the user and what type is the return value

    public static void main(String[] args) {        //Create objecttool = new objecttool()// Call the method. What type of parameters are passed in and what type of return value is tool. Show ("hello"); tool.show(12);         tool.show(12.5);    }

3.3 subclasses derived from generic classes

We have defined a generic class earlier. A generic class is a class with the feature of genericity. It is essentially a Java class, so it can be inherited

How was it inherited?? There are two cases

  1. Subclasses specify the type parameter variables of generic classes
  2. Subclass ambiguous type parameter variable of generic class

3.3.1 subclasses specify the type parameter variables of generic classes

  • generic interface
/*    Define generics on interfaces */public interface Inter<T> {    public abstract void show(T t);}
  • Classes that implement generic interfaces
/** * Subclasses specify the type parameter variables of generic classes: */public class InterImpl implements Inter<String> {    @Override    public void show(String s) {        System.out.println(s);    }}

3.3.2 the subclass does not specify the type parameter variable of the generic class

  • When the subclass does not specify the type parameter variable of the generic class, when the subclass is used by the outside world, the type parameter variable also needs to be passed in, and the type parameter variable needs to be defined on the implementation class
/** * The subclass is not clear about the type parameter variable of the generic class: * the implementation class should also define the type of < T >* */public class InterImpl<T> implements Inter<T> {    @Override    public void show(T t) {        System.out.println(t);    }}

Test code:

    public static void main(String[] args) {        //Test the first case / / inter < string > I = new interimpl()// i.show("hello");        // In the second case, test inter < string > II = new interimpl < > (); ii.show("100");    }

It is worth noting that:

  • If the implementation class overrides the method of the parent class, the type of return value should be the same as that of the parent class!
  • A generic declared on a class is valid only for non static members

3.4 type wildcards

Why do I need type wildcards???? Let's look at a demand

Now there is a requirement: the method receives a set parameter, traverses the set and prints out the set elements. What should I do?

  • Before we learn generics, we might do this:
public void test(List list){    for(int i=0;i<list.size();i++){                System.out.println(list.get(i));        }}

The above code is correct, but a warning will appear when compiling, saying that the type of collection elements is not determined... This is not elegant

  • So we've learned generics. What should we do now?? Some people may do this:
public void test(List<Object> list){    for(int i=0;i<list.size();i++){                System.out.println(list.get(i));        }}

There is nothing wrong with this syntax, but it is worth noting here that the test() method can only traverse the collection loaded with objects!!!

Emphasize that < Object > in generic types is not inherited as before, that is, list < Object > and list < string > are irrelevant!!!!

What now??? We don't know what type of elements are loaded in the list collection. List < objcet > doesn't work... So Java generics provide type wildcards?

So the code should be changed as follows:

public void test(List<?> list){    for(int i=0;i<list.size();i++){                System.out.println(list.get(i));        }}

? Wildcard indicates that any type can be matched, and any Java class can be matched

Now it is very noteworthy that when we use? No. wildcard: you can only call object type independent methods, and cannot call object type related methods.

Remember, you can only call object independent methods, not object type related methods. Because the specific type is not known until it is used by the outside world. That is, in the List set above, I can't use the add() method. Because the add() method throws the object into the collection, and now I don't know what the type of the object is.

3.4.1 setting the upper limit of wildcards

First, let's take a look at where to set the upper limit of wildcards

Now, I want to receive a List set, which can only operate on elements of numeric type (Float, Integer, Double, Byte and other numeric types are OK). What should I do???

We learned about wildcards, but if we use wildcards directly, the set can not only operate on numbers. Therefore, we need to set the upper limit of wildcards

List<? extends Number>

The above code indicates that the elements loaded in the List collection can only be subclasses of Number or themselves

    public static void main(String[] args) {        //The list collection is loaded with integers. You can call this method list < Integer > Integer = new ArrayList < > (); test(Integer);        // The list set is loaded with strings, and an error is reported during compilation. List < String > strings = new ArrayList < > (); test(strings);    }     public static void test(List<? extends Number> list) {            }

3.4.2 setting the lower limit of wildcard

Since we have explained how to set the upper limit of wildcards, it is not strange to set the lower limit of wildcards. Let's go straight to grammar

    //The passed in can only be type or the parent class of type <? super Type>

It is not uncommon to set the lower limit of wildcards. There are in the TreeSet set... Let's take a look

    public TreeSet(Comparator<? super E> comparator) {        this(new TreeMap<>(comparator));    }

What's the use of it?? Let's think about it. When we want to create a variable of TreeSet < String > type, we pass in a Comparator that can compare the size of String.

There are many choices for this Comparator. It can be Comparator < String >, or the parent class whose type parameter is String, such as Comparator < objcet >

This is very flexible. That is, as long as it can compare the string size

After comments, it is added that there is a principle in the upper and lower limits of generics: PECS (producer extensions consumer super)

The book says:

Subclass qualified can be read from generic types [i.e. - > (? Extend T)] ----- > producer extensions
Users with superclass restrictions can write from generic types [i.e. - > (? Super T)] ----- > consumer super
There are also relevant blog posts that are well written:

http://blog.51cto.com/flyingc...
https://blog.csdn.net/xx32666...

3.5 wildcard and generic methods

Most of the time, we can use generic methods instead of wildcards

    //Use the wildcard public static void test (list <? > list) {} / / use the generic method public < T > void test2 (list < T > t) {}

Both of the above methods are OK... So now the question is, shall we use wildcards or generic methods??

principle:

  • If the types of parameters are dependent, or the return value is dependent on the parameters. Then use generic methods
  • If there are no dependencies, use wildcards, which will be more flexible

3.6 generic erasure

Generics are provided for the javac compiler to use. They are used to limit the input type of the collection and let the compiler insert illegal data into the collection at the source code level. However, after the compiler compiles the java program with generics, the generated class file will no longer contain generics information, so that the running efficiency of the program will not be affected. This process is called "erasure".

3.6.1 compatibility

JDK5 puts forward the concept of generics, but JDK5 did not have generics before. That is, generics need to be compatible with collections below JDK5.

When a collection with generic characteristics is assigned to an old version of the collection, the generics are erased.

It is worth noting that it retains the upper limit of the type parameter.

        List<String> list = new ArrayList<>();        //The type is erased and the upper limit of the type is reserved. The upper limit of String is object list LIST1 = list;

What if I assign a set without type parameters to a set with type parameters??

        List list = new ArrayList();        List<String> list2 = list;

It also does not report an error, but simply prompts "unchecked conversion"

4, Application of generics

When we write web pages, there are often multiple Daos. We have to write several Daos every time, which will be a little troublesome.

[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-llykadqe-1635252961204) (Java notes. assets/162810c81b07499d)]

So what effect do we want?? Write only one abstract DAO, and other Daos will have corresponding methods as long as they inherit the abstract DAO.

To achieve this effect, generics must be used. Because in an abstract DAO, it is impossible to know which DAO will inherit itself, so we do not know its specific type. A generic type specifies its specific type only when it is created.

  • Abstract DAO
public abstract class BaseDao<T> {    //Simulate hibernate... Private session; private Class clazz;            // Which subclass calls this method, the class obtained is the type handled by the subclass (very important) public basedao() {class clazz = this. Getclass(); / / the subclass parametrizedtype Pt = (parametrizedtype) clazz. Getgenericsuperclass(); / / BaseDao < category > clazz = (class) Pt. Getactualtypearguments() [0] ;        System.out.println(clazz);            }        public void add(T t){        session.save(t);    }        public T find(String id){        return (T) session.get(clazz, id);    }        public void update(T t){        session.update(t);    }        public void delete(String id){        T t = (T) session.get(clazz, id) ;        session.delete(t);    }    }
  • By inheriting the abstract DAO, the implementation class has the corresponding methods of adding, deleting, modifying and querying.

CategoryDao

public class CategoryDao extends BaseDao<Category> {}

BookDao

public class BookDao extends BaseDao<Book> {}

Keywords: Java JavaEE

Added by Bea on Sun, 31 Oct 2021 05:36:46 +0200