1. Java generics

Generics in Java were introduced in JDK1.5. Java generics are pseudo generics.

  • 1. When a generic class creates an instance, it needs to assign a value to its type variable
 class A<T>{
    }
Copy the code
  • 2. Generic methods
class A<T>{
        public T fun1(){} public void fun2(T T){} public void fun2(T T){} public <T> Tfun3Class B{public <T>fun1(){// also generic methods, generic methods need not be in the generic class}Copy the code
  • Generic methods are not directly related to generic classes

  • 3. Use of generic classes

* Generics defined in generic classes > can be used in method return values > can be used in method parameters > can be used in local variables is class C<T>{public Tfun1(){// return value T T =... } public void fun2(T T){} public void fun2(T T){}Copy the code
  • 4. Generics inheritance and implementation
* Subclass is not generic: you need to pass a specific type constant to the parent class > then all generic arguments in the parent class will be replaced by that type constant. * Subclass is generic: Class AA1 extends A<String>{} Class AA2<E> extends A<E>{} Class AA2<E> extends A<E>{}Copy the code

2. Java generic wildcards?

Wildcard classification

See the Java wildcard for details

? : unbounded wildcard <? Extends T> : refers to "Upper Bounds Wildcards" <? Super T> : Means "Lower Bounds Wildcards"Copy the code

Java generic type erasure

Java generics are valid at the compiler and are removed at run time, which means that all generic parameter types are removed after compilation.

List<String> and List<T> are erased to List. List<String>[] and List<T>[] are erased to List[]. List<? Extends E >, a List <? Super E> deletes the type List<E>. List<T extends Serialzable & Cloneable> Erased to List<Serializable>.Copy the code

4, pecs

PECS principles in Java generics

Producers use extends, and consumers use super.

The upper bound wildcard Plate<? Extends Fruit> covers the blue area in the image below.

The upper bound <? Extends T> Extends T> Extends T> extends T> extends T

Lower bound <? Super T> does not affect storing in, but fetching out can only be placed in Object

reference

Java wildcard solution

Generic type erasure in Java

Java generics and wildcards

What is the difference between extends and super in generics?

JAVA Generic Wildcards (PECS) in three sentences