What are Generics?
Generics are a parameterized type mechanism introduced in JDK5
Why generics
- Advance type checking to compile time
- Avoid type conversions (avoid runtime classcastExceptions)
- Improve code reuse (container classes)
The use of generics in Java
-
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
-
A generic interface
public interface Animal<T>{ String makeSound(T t); } Copy the code
-
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
- ? Extend XXX (can read data, cannot add data)
- ? Super XXX (can add data, cannot read data)
- ? (Uncertain type)
Limitations of generics
- Basic data types are not supported
- The static keyword cannot be used
- Clone cannot be used
- Arrays not supported
- It’s not covariant,
Integer extend Number,List<Integer> and List<Number>
There is no inheritance - You can’t use
arg instanceOf T
- You can’t use
T var = new T();
- You can’t use
T[] array = new T[10];