What are Generics?

Generics are a parameterized type mechanism introduced in JDK5

Why generics

  1. Advance type checking to compile time
  2. Avoid type conversions (avoid runtime classcastExceptions)
  3. Improve code reuse (container classes)

The use of generics in Java

  1. A generic class

    public class Box<T>{ private T obj; public void setObj(T t){ obj = t; } public T getObj(){ return obj; }}Copy the code
  2. A generic interface

    public interface Animal<T>{
    	String makeSound(T t);
    }
    Copy the code
  3. Generic method

    public<T> void print(T t){
    	System.out.print(t);
    }
    Copy the code

Note:

  • Whether or not you have a generic method has nothing to do with whether or not your class is generic
  • To determine if a method is generic, see if it has one

Talk about PESC

producer-extens , consumer -super.

If you want to read data of type T from the collection and cannot write to it, you can use? Extends wildcard; (Producer Extends)

If you want to write data of type T from a collection and do not need to read, you can use? Super wildcard; (Consumer Super)

Type Erasure

  • JVM virtual machines do not support generics
  • A List < String > and List < Integer >Same type at run time
  • After the generics are erased, the overloading produces the same type signature, and the following code does not compile
    public class UseList<T,W>{
    void f(List<T> v){}
    void f(List<W> v){}
    }
    Copy the code
  • A catch statement cannot catch exceptions of generic types, and generic classes cannot inherit directly or indirectly from Throwable

Wildcards for generics

  1. ? Extend XXX (can read data, cannot add data)
  2. ? Super XXX (can add data, cannot read data)
  3. ? (Uncertain type)

Limitations of generics

  1. Basic data types are not supported
  2. The static keyword cannot be used
  3. Clone cannot be used
  4. Arrays not supported
  5. It’s not covariant,Integer extend Number,List<Integer> and List<Number>There is no inheritance
  6. You can’t usearg instanceOf T
  7. You can’t useT var = new T();
  8. You can’t useT[] array = new T[10];