Advanced Features of Java Key Knowledge Points

Summary: Android Xiaobai's Growth Path_Knowledge System Summary【Continuously updated...】

Table of contents

abnormal

  • In java, the exception object is derived from Throwablean instance of the class, and the next layer is divided into two branches: ErrorandException

    • Error: Internal errors and resource exhaustion errors of the Java runtime system, applications should not throw objects of this type
    • Exception: It is divided into two branches, one branch is derived from RuntimeException, and the other branch contains other exceptions. The exceptions caused by program errors belong to , and the program itself is fine, but the exceptions caused by problems RuntimeExceptionlike errors belong to other exceptionsI/O
      • RuntimeException: Wrong type conversion, array access out of bounds, access to null pointer, should be modified to avoid, not capture processing
      • Other exceptions: trying to read data after the end of the file, trying to open a file that does not exist, trying to find a Class object based on the given string, but the class does not exist. This type of exception must be caught or thrown, otherwise the compiler will report an error
  • Use try/catcha statement block to catch exceptions. If tryany code in the statement throws an catchexception class specified in the clause, the program will skip trythe rest of the code in the statement block and start executing catchthe processing code in the clause. If catchthe clause is in If the exception type is not declared, the method will exit immediately

  • finally clause: Regardless of whether an exception is caught, the code in this clause will be executed. If the code throws an exception, but the exception is not caught by the clause, then the execution of the code will be catchinterrupted and the code in the clause trywill be executed directly . You can only and statement without clausefinallytryfinallycatch

  • There is a nice way of catching exceptions:

    try{
          
          
    	try{
          
          
    		...
    	}finally{
          
          
    		//释放资源
    	}
    }catch(Excepyion e){
          
          
    	...
    }
    

    The inner trystatement block has only one responsibility, which is to ensure that resources are released, and the outer trystatement block has only one responsibility, which is to ensure that errors that occur are caught, so that writing can finallycatch all exceptions that occur inside

  • When the exploit returnstatement is exited from the statement block, the contents of the clause will be executed trybefore the method returns . finallyIf finallythere is also a statement in the clause return, this return value will override the original return value

generic

  • Generic programming means writing code that can be reused by many different types of objects

  • Generic class:

    public class Pair<T>
    {
          
          
    	private T first;
    	private T second;
    	public Pair(){
          
          first = null; second = null}
    	public Pair(T first,T second){
          
          this.first = first;this.second = second;}
    	public T getFirst(){
          
          return first;}
    	public T getSecond(){
          
          return second;}
    }
    

    The Pair class introduces a type variable T, enclosed in angle brackets <>, and placed after the class name, a generic class can have multiple type variables, for example:

    public class Pair<T, U>{
          
          }
    
  • Generic method:

    public static <T> T getMiddle(T... a){
          
          
    	return a[a.length / 2];
    }
    

    The type variable is placed after the modifier and before the return type. When calling a generic method, put the specific type in the angle brackets before the method name:

    String middle = <String>getMiddle("a","b","c");
    
  • Restrictions on type variables:

    public static <T extends Comparable> T min(T[] a)...
    

    The above form limits the generic type T to classes that implement Comparablethe interface. If the type passed in does not satisfy this rule, an error will be reported when compiling. A type variable or wildcard can have multiple qualifications, such as:

    T extends Comparable & Serializable
    

    Limited types are separated by &

  • Type erasure: Whenever a generic type is defined, a corresponding primitive type is automatically provided. The name of the primitive type is the generic type name after deleting the type type parameter, erasing the type variable, and replacing it with the qualified type (unqualified variables default to Object), for example Pair<T>the primitive type is as follows:

    public class Pair
    {
          
          
    	private Object first;
    	private Object second;
    	public Pair(){
          
          first = null; second = null}
    	public Pair(Object first,Object second){
          
          this.first = first;this.second = second;}
    	public Object getFirst(){
          
          return first;}
    	public Object getSecond(){
          
          return second;}
    }
    

    If there are multiple qualified types, the original type is replaced by the first qualified type variable. If the qualification is to be switched, the compiler will insert a cast to the qualification to be switched when necessary. Therefore, in order to improve efficiency, the Interfaces without methods are placed at the end of the bounds list

  • Generic constraints and limitations:

    • Type parameters cannot be instantiated with primitive types, e.g. no Pair<double>, only Pair<Double>, the reason for this is type erasure, after erasure the primitive type is Object, and Objectcannot store doublea value (of a primitive type)

    • Runtime type queries only work with primitive types, not with generic types, that is, the following query is wrong:

      if(a instanceof Pair<T>) ...
      
    • Arrays of parameterized types cannot be created. For example, the following writing is wrong:

      Pair<String>[] table = new Pair<String>[10];
      

      Because after type erasure, the type of table is Pair[]. It can be converted to Object[], the array will remember its element type, and if it stores other types of elements, an ArrayStoreExceptionexception will be thrown, so it is not allowed to create an array of parameterized types. However, variables of type can be declared Pair<String>[], but cannot be new Pair<String>[10];initialized with

    • Type variables cannot be instantiated. For example, the following writing is wrong:

      public Pair(){
              
              first = new T(); second = new T();}
      
    • Generic arrays cannot be constructed. For example, the following writing is wrong:

      public static <T extends Comparable> T[] minmax(T[] a){
              
              T[] mm = new T[2];}
      

      Type erasure would make this method always construct the Comparable[2] array

    • Type variables in the static context of generic classes are invalid, and type variables cannot be referenced in static fields or methods, for example:

      public class Singleton<T>
      {
              
              
      	private static T singleInstance;	//error
      	public static T getSingleInstance()	//error
      	{
              
              
      		if(singleInstance == null) return new SingleInstance();
      		return singleInstance;
      	}
      }
      

      After type erasure, only the Singleton class is left, which will only contain a singleInstance field. Generally speaking, static fields or methods take precedence over the instantiation of classes, etc., so we don’t know what type of parameter is actually passed, so we can’t use

    • cannot throw or catch instances of generic classes

    • The detection of checked exceptions can be eliminated. A basic principle of java exception handling is that a handler must be provided for all checked exceptions, but this limitation can be eliminated by using generic erasure

wildcard type

  • In wildcard types, type parameter changes are allowed, for example:

    Pair<? extends Employee>
    

    Represents any generic Pair type whose type parameter is a subclass of Employee

  • Wildcard qualifications are similar to type variable qualifications, but with the added ability to specify a supertype qualification, for example:

    ? super Manager
    

    This wildcard is restricted to all supertypes of Manager

  • A wildcard qualified with a supertype can write to a generic object, and a wildcard qualified with a subclass can read from a generic object

  • Unlimited wildcards, for example Pair<?>, Pair<?>are essentially different from Pair in that: you can call the setObject method of the original Pair class with any Object object

Guess you like

Origin blog.csdn.net/Nbin_Newby/article/details/120668461