A brief review of Java generics~~~~~

What is generic

The introduction of generics:

The collection type can store objects arbitrarily, as long as the object is stored in the collection, it will be upcasted to the Object type. When we take out the objects in the collection for operation, we need to perform downcasting of the object (forcing conversion ), this is not safe, because you may put different types of objects into the same collection, and take out the transformation error caused by the transformation

For example: you create a collection to hold dogs, and then you put cats in. Both cats and dogs are transformed into Objects, and then when you take them out, you will force cats and dogs into dogs. Obviously unreasonable! ! !

Therefore, a generic mechanism is added after ***jdk5***, which not only guarantees the safety of the program, but also does not require manual
forcing. When the generic mechanism is not used, the objects in the collection are directly transformed, and the objects in the collection are directly transformed at compile time. Will throw a ClassCastException,

Generic

  1. concept:
    • The core concept of generics is to tell the compiler what type you want to use, which is checked by the compiler. It is essentially a parameterized type, which makes it possible to predictably use "unknown" types in classes or methods.
    • Generics are a compile-time type-safe checking mechanism
  2. The benefits of generics:
    • Since there is no need to manually transform the objects in the collection, the code becomes more concise
    • The program is more robust, as long as there is no warning during compilation, ClassCastException will not be thrown during runtime
    • Improved code readability and stability

Generic basics

Generic class

  • Define a generic class: class class name <generic parameter>{}
    • General generic parameters can be arbitrarily identified, common ones are T\K\V... etc.

For example: the definition of ArrayList collection in java api

class ArrayList<E>{
    
    
public boolean add(E e){
    
     }
public E get(int index){
    
     }
....
}

Note
1. When instantiating a generic class, the parameter type must be given, and it cannot be a basic type
2. The type parameter can be omitted in the construction method, and the omitted parameter type will be inferred from the specified specific type parameter (generic It is to postpone the work of clear type until the time of creating an object or calling a method to specify a special type)
3. Define generics on the class, which can also be used in the methods of the class

Generic method

  • The definition contains a generic method: modifier <generic parameter> return value type method name (parameter) {}

Generic structure 2

  • The definition contains a generic interface: modifier interface interface name <generic parameter>{}

Generic wildcard

[Http://www.zuidaima.com/blog/3689434434948096.htm]: java 3y example is used here

The java 3y example is
used here. The java 3y example
is used here. Now there is a requirement: the method receives a collection parameter, traverses the collection and prints the collection elements, what should I do?

According to us before learning 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 during compilation, saying that the type of the collection element has not been determined... This is not elegant...

So we learned about generics, what should we do now? ? Some people might 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 the syntax to do this, but it is worth noting here: the test() method can only traverse the collection loaded with Object! ! !

Emphasize: Generics are not inherited as before, which means that List and List have nothing to do with each other! ! ! !

What should I do now? ? ? We don't know what type of elements are loaded in the List collection. List does not work like this... So Java generics provides type wildcards?

So the code should be changed to this:

public void test(List<?> list){
    
    


    for(int i=0;i<list.size();i++){
    
    
    
        System.out.println(list.get(i));
    
    }
}

The wildcard character means that any type can be matched, and any Java class can be matched...

Now it is very worth noting that when we use the? Wildcard: we can only call methods that are not related to the object's type, and cannot call methods that are related to the object's type.

Remember, you can only call methods that have nothing to do with the object, not methods that are related to the object's type. Because it is not known what the specific type is until the outside world uses it. In other words, in the above List collection, I cannot 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.

Set wildcard restrictions

  1. Set the upper limit
    Format: Type name <? extends class> Object name
    Meaning: Only this type and its subclasses can be received

  2. The lower limit of generics:
    Format: Type name <? super class> Object name
    Meaning: Only the type and its parent type can be received

Generic erasure mechanism

Generics are provided to the compiler. The compiler can ensure that you place an object of the generic parameter type, but the generated .class file does not contain generic information.

Java generics are implemented using erasure, which means that when you are using generics, any specific type information is erased, and the only thing you know is that you are using an object. Therefore, List and List are actually the same type at runtime. Both forms have been erased into their "native" types

  • The role of the erasure mechanism
    1. Reduce the potential confusion about erasure, because generics did not exist at the beginning of the design of the java language, so when it is introduced, it can only be introduced in a compromise, that is, to ensure that the current code is legal and continue to maintain the previous Meaning, so that the old code will not affect the new code (allowing generic code and non-generic code to coexist)
    2. The core motivation of erasure can be summarized in one sentence: non-generalized clients can be used with generalized libraries, and vice versa. This is also called: "migration compatibility"

Constraints and limitations of generics

  1. Cannot use basic types to instantiate parameters
  2. Run-time type query only applies to primitive types (ie before generic erasure)
  3. Cannot create parameterized array
  4. Cannot instantiate type variables
  5. Static variables or static methods of generic classes cannot refer to generic variables
  6. Cannot throw or catch instances of generic classes-the catch clause cannot use type parameters

The article was only written when reviewing the knowledge points, and some of the expressions of some bigwigs were used for reference. Because it is only a review of the knowledge points, the article does not use a lot of code to illustrate the case. If it is a basic learning partner, you can Move!

Guess you like

Origin blog.csdn.net/weixin_45727731/article/details/108861468