Overview of Java generics

1. What is generics?

1) Concept

Java generics is a new feature introduced in JDK5. Generics provides a compile time type safety monitoring mechanism, which allows us to detect illegal type data structures at compile time. The essence of generics is parameterized type, that is, the data type operated on is specified as a parameter

2) Benefits

  • Type checking during compilation. Type safety
  • Elimination of cast type conversion

3) Type

  • E - Element (used in a collection because the collection holds elements)
  • T - Type (represents Java classes, including basic classes and our custom classes)
  • K - Key (indicates key, such as key in Map)
  • V - Value
  • N - Number (indicates the value type)
  • ? - (represents an indeterminate java type)
  • S,U,V - 2nd,3rd,4th types

2. Generic classes, interfaces

1) Generic class

  • Use syntax
    Class name < specific data type > object name = new class name < specific data type > ();
  • After Java 1.7, the specific data types in < > can be omitted
    Class name < specific data type > object name = new class name < > (); Diamond grammar
//Class name < specific data type > object name = new class name < specific data type > ();
ArrayList<String> al = new ArrayList<String>();
//After Java 1.7, the following types can be omitted. Diamond grammar
ArrayList<String> al = new ArrayList<>();

2) Generic class considerations

  • Generic class. If no specific data type is specified, the operation type is Object
  • The type parameter of a generic type can only be a class type, not a basic data type. For example, it can be Integer, but not int
  • A generic type can logically be regarded as several different types, but they are actually the same type
//There is a generic < T > class
Generic<String> strGeneric = new Generic<String>;
Generic<Integer> intGeneric = new Generic<Integer>;
intGeneric.getClass() == strGeneric.getClass();//The result is true. They are all Generic classes

3) Subclasses derived from generic classes

  • Subclasses are also generic classes. The generic types of subclasses and parent classes should be consistent
//T before and after
class ChildGeneric<T> extends Generic<T>
  • The child class is not a generic class, and the parent class should specify the generic data type
//Type to be specified for parent class: String
class ChildGeneric extends Generic<String>

4) Generic interface

//Define syntax
interface Interface name <Generic ID, generic ID> {
    Generic identity method name();
    .....
}

5) Use of generic interfaces

  • Implementation classes are also generic classes. The generic types of implementation classes and interfaces should be consistent
public class Pair<T,E> implements Generator<T>{}
  • The implementation class is not a generic class, and the interface should specify the data type
public class Apple implements Generator<String> {)

3. Generic method

1) Usage

  • Generic methods indicate the specific type of a generic when calling a method

2) Grammar

// Modifier < T, e,... > return value type method name (formal parameter list) {method body...}
public <E> E getProduct(ArrayList<E> list){} //At this time, E is independent of the type of generic class
public class MyArrayList<T>{//Generic class: type T
    // Generic method: type E. Independent of class type T
    public <E> E randomE(ArrayList<E> list){  
        Random random = new Random(); 
        return list.get(random.nextInt(list.size()));
    } 
}
//Even if the class type T is Integer, it will not affect the type of generic method. The method type E can be String, Double, Float, etc

3) Explain

  • Between public and return value = = < E > = = is very important. It can be understood as declaring this method as a generic method
  • Only declared methods are generic methods. Member methods in generic classes that use generics are not generic methods
  • < T > indicates that the method will use generic type T. only then can generic type t be used in the method
  • Like the definition of generic classes, T here can be written as any identifier. Common parameters such as T, E, K, V, etc. are often used to represent generics.

4) Variable parameters

public <E> void print(E... e){
    for (E e1 : e) {
        System.out.println(e);
    }
}

5) Summary

  • Generic methods enable methods to change independently of classes
  • If static methods want to use generic capabilities, they must be made generic
public static <T,E,K> void printType(T t, E e, K k) {
    System.out.println(t + "\t" + t.getClass().getSimpleName()); 
    System.out.println(e + "\t" + e.getClass().getSimpleName()); 
    System.out.println(k + "\t" + k.getClass().getSimpleName());
}

4. Type wildcard

1) What are type wildcards?

  • Type wildcards are generally used? Replace specific type arguments
  • Type wildcards are type arguments, not type parameters

2) Upper limit of type wildcard

  • Syntax:
    Class / interface <? Extensions argument type >
    The type required for this generic type can only be an argument type or a subclass type of an argument type
public class MyArrayList<? extends Number>{}// ?  It can only be Number, or subclasses of Number, such as Integer, Double, etc., but not String

3) Lower bound of type wildcard

  • Syntax:
    Class / interface <? Super argument type >
    The type required for this generic type can only be an argument type or a parent type of an argument type
public class MyArrayList<? super Integer>{}// ?  It can only be Integer or the parent class of Integer, such as Integer, Number, etc., but not String

5. Type erase

1) Concept

Generics is a concept introduced in Java version 1.5. Before that, there was no generics, but the generic code can be well compatible with the code of previous versions. That's because the generic information only exists in the code compilation stage. Before entering the JVM, the generic related information will be erased, which we call - type erasure.

2) Unlimited type erase

3) Limited type erase

4) Parameters defined by type in erase method

5) Bridging method

6. Generics and arrays

Creation of generic arrays

  • Array references with generics can be declared, but array objects with generics cannot be created directly
//Wrong method. Cannot compile
ArrayList<String>[] astr = new ArrayList<String>[5];

//Correct method: (not recommended)
ArrayList<String>[] arrayList; //Declaring generic arrays
ArrayList[] astr = new ArrayList[5]; //Define a normal array
arrayList = astr; //Assign values to generic arrays

//Combination: (recommended)
ArrayList<String>[] arrayList1 = new ArrayList[5];
  • T [] array can be created through = = newInstance(Class,int) = = of java.lang.reflect.Array
public class Fruit<T> {
    private T[] array;//Declare object variables

    public Fruit(Class<T> clz, int length){
        //Create a generic array through Array.newInstance
        array = (T[])Array.newInstance(clz, length);//T [] type forced transfer
    }
}

7. Generics and reflection

  • Reflection common generic classes
    Class
    Constructor
public class Person {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
/**
 * Generics and reflection
 */
public class Test11 {
	public static void main(String[] args) throws Exception {
	     Class<Person> personClass = Person.class;
	     Constructor<Person> constructor = personClass.getConstructor();
	     Person person = constructor.newInstance();
	 }
}

Tags: Java

Posted on Fri, 26 Nov 2021 18:49:16 -0500 by PunjabHaker