Day 3: Java Basic Review (3)

generic

Definition: parameterized type, specify a parameter for the type, and then specify the specific value of this parameter when using it, so that the type can be determined when it is used; this parameter can be used in the creation of classes, interfaces, and methods , known as generic classes, generic methods, and generic interfaces;

Features:

        1. If the generic type is not passed, it defaults to Object;

        2. When using a class with generics to create an object, the generics on both sides must be consistent;

        3. It is only valid in the compilation phase, and it will automatically de-generate the operation when compiling

        4. Generic types are logically multiple different types, but they are actually the same basic type

benefit:

        1. In order to achieve arbitrary parameterization (the disadvantage is that mandatory type conversion is required)

        2. Check type safety at compile time, all mandatory conversions are automatic and implicit, improving code reuse rate

        3. The type checking can be completed at compile time and errors can be raised

        4. Simplify development and ensure improved code quality

use:

Generic class: Generics are used in class definitions, and the incoming actual parameters must be of the same type as the generic parameters;

class 类名称 <泛型标识:可以随便写任意标识号,标识指定的泛型的类型>{
      private 泛型标识 /*(成员变量类型)*/ 
}
//当不传入泛型类型的实参时,方法或变量可以为任何类型
Generic generic = new Generic("111111");
Generic generic1 = new Generic(222222);

Log.d("泛型测试","key is " + generic.getKey());
Log.d("泛型测试","key is " + generic1.getKey());

Generic method: To judge whether a method is a generic method, it mainly depends on whether <> is used before the return value

public class Generic<T> {     
    public T name;     
    public  Generic(){}     
    public Generic(T param){         
        name=param;     
    }     
    public T m(){        
         return name;    
    }     
    public <E> void m1(E e){ }     
    public <T> T m2(T e){ } 
}

m()方法不是泛型方法,m1()与m2()都是;
m2()方法中声明的类型T与类申明里面的那个参数T不是一个,也可以说方法中的T隐藏了类型中的T

Generic interface: When no generic actual parameter is passed in, it is the same as the definition of the generic class. When declaring the class, the generic declaration must also be added to the class;

//定义一个泛型接口
public interface Generator<T> {    
     public T next(); 
}

Generic wildcards:

Generic wildcards in general use? Instead of concrete type arguments, you can put the ? Seen as the parent class of all types, it is a real type

public void showKeyValue1(Generic<?> obj){     
    Log.d("泛型测试","key value is " + obj.getKey()); 
}

Wildcard upper and lower bounds:

Upper bound: Use the <? extends T> format, which means that T or a subclass of T is required, and T is a specific type

public void printIntValue(List<? extends Number> list) {       
    for (Number number : list) {           
        System.out.print(number.intValue()+" ");        
    }  
 }

Lower bound: Use the <? super T> format, which means that T or the parent class of T is required, and T is the specific type

public void fillNumberList(List<? super Number> list) {       
    list.add(new Integer(0));       
    list.add(new Float(1.0));   
}

abnormal

Definition: Interrupting the instruction flow of the execution terminal during the execution process; an exception means that when an exception occurs in the program, the program is forcibly terminated and the exception information is returned. Some developers think whether to handle the exception

cause:

        1. An exception occurred inside java (Java virtual machine)

        2. Code errors generate exceptions

        3. Manually generated exceptions are generated by throw

type:

        1. Runtime exceptions: These exceptions are usually caused by some logic errors; common: null pointer exception, type conversion exception, array out-of-bounds exception, etc.

        2. Compile-time exception: must be handled, otherwise the program compilation will not pass, common: stream transmission exception, database operation exception, etc.

deal with:

        1. try-catch; try is used to monitor exceptions, catch captures and handles exceptions, and multiple catches are executed sequentially from top to bottom

try{
//程序代码
}catch(Exception e){
    //catch块
}

        2. try-catch-finally; try is used to monitor exceptions, catch captures and handles exceptions, and finally will always be executed;

try{
//程序代码
}catch(Exception e){
    //catch块
}finally{
    ......
}
在catch中遇到return时,仍然会先执行finally语句,再回来执行对应catch语句中的return语句;
当finally中存在return ,返回值会被return 覆盖掉

        3. Throw/throws, when it cannot be processed, tell the caller on the method or statement that there is a problem; if a method does not catch a checked exception, then the method must be declared with the throws keyword (the statement throws multiple Exceptions, separated by commas), you can also use the throw keyword in the statement to throw an exception

public static void test() {          
      int a = 520;          
      int b = 0;           
      if (b == 0) {               
          throw new ArithmeticException();           
      } else {               
          System.out.println(a / b);           
      }       
  }
  
  public static void test() throws Exception {           
      int a = 520;           
      int b = 0;          
       if (b == 0) {               
           throw new Exception();           
       } else {               
           System.out.println(a / b);           
       }       
   }

The difference between throw and throws:

throw:

        Used after the method declaration, followed by the exception class name
        can be followed by multiple exception class names, separated by commas
        to indicate that an exception is thrown, and the caller of the method handles
        throws to indicate a possibility of an exception, not necessarily These exceptions occur

throws:

        Used in the method body, followed by the exception object name,
        only one exception object name can be thrown
        to indicate that an exception is thrown, and the execution of throw by the statement in the method body
        must throw some kind of exception

        4. Custom exceptions

step:

        1. Create a custom exception class

        2. Throw an exception through throw in the method

Exception mechanism process:

        1. When the program cannot run, jump out from the current environment

        2. New an exception object, then terminate the program at the exception location, and return the exception from the environment

        3. The exception handling mechanism takes over the program and finds a place where the program can continue to be executed

io

The essence of stream is the processing of data transmission to files, and its function is to establish a transmission channel for data and destination;

The io model design adopts the Decorator (decorator) mode

Input stream: read data; output stream: write data.

byte stream

character stream

input stream

InputStream

Reader

output stream

OutputStream

Writer

byte stream:

        All file data (text, pictures, videos, etc.) are stored in the form of binary numbers, one byte at a time, and the same is true for transmission. Therefore, byte streams can transmit arbitrary file data.

Character stream:

        It is a data stream formed by adding encoding on the basis of the byte stream; because when the byte stream manipulates characters, there may be Chinese characters that cause garbled characters, so the character stream is derived on the basis of the byte stream.

The File class is an object that encapsulates files and folders in the file system, and can operate files and folders through the idea of ​​objects

 The difference between character stream and byte stream:
        1. The byte stream itself does not need a buffer area when operating, and is directly connected to the file; while the character stream requires a buffer area when operating.
        2. When using a byte stream, even if the stream is not closed, it can eventually be output to a file;
        3. When using a character stream, all content is stored in the buffer, and when the stream is closed, the buffer content will be forcibly written to the file , if the stream is not closed, nothing will be output in the file.
How to choose character stream and byte stream:
        1. In most cases, it is better to use byte stream, because most of the IO operations are directly operating disk files, so these streams are transmitted in bytes (pictures, etc. are stored in bytes)
        2. It would be better to use character streams for operations that require frequent processing of strings in memory through IO, because character streams have buffers, which improves performance

Conversion of character streams and byte streams:

1. Convert byte input stream to character input stream (InputStreamReader):

public class Test {
   public static void main(String[] args) throws IOException {
    //1.定义输出文件路径
    File file = 
      new File("d:"+File.separator+"Demo"+File.separator+"OutputStreamWriter.txt");
     //判断目录是否存在
     if(!file.getParentFile().exists()){
        //创建文件目录
        file.getParentFile().mkdirs();
     } 
     //2.取得字节输出流
     OutputStream outputStream = new FileOutputStream(file);
     //3.将字节输出流转换为字符输出流
     OutputStreamWriter out = new OutputStreamWriter(outputStream);
     out.write("欢迎使用字节输出流转换字符输出流!");
     //4.关闭流
     out.close();
   }
}

2. Convert byte output stream to character output stream (OutputStreamWrite):

File f = new File("c.txt");
FileOutputStream fos = new FileOutputStream(f);
OutputStreamWriter osw = new OutputStreamWriter(fos,"UTF-8");

buffer:

        1. The buffer is a special memory area. In many cases, when the program needs to frequently operate a resource (such as a file or database), the performance will be very low. Therefore, in order to improve performance, part of the data can be temporarily read and written to the buffer. In the future, you can directly read and write data from this area, which significantly improves security.
        2. The operations on the Java character stream are all performed in the buffer, so if we want to actively flush the buffer to the file during the character stream operation, we can use the flush() method to operate.

Guess you like

Origin blog.csdn.net/qq_35056891/article/details/126462589