Research on the Limitations of java Generics and Summary of Knowledge Points

  • 2021-10-15 10:42:33
  • OfStack

Introduction to Generics

1. Why use generics?

1 is used on the collection, for example, now put a value of string type into the collection. At this time, after this value is put into the collection, it loses its own type and can only be object type. At this time, if you want to type the value, it is easy to have type conversion errors. How to solve this problem, you can use generics to solve it.

2. Write an object in generic type. String cannot write a basic data type such as int. Write a wrapper class corresponding to the basic data type

基本数据类型 对应包装类 基本数据类型 对应包装类
byte Byte short   Short
int Integer long Long
float Float double Double
char Character boolean Boolean

Research on the Limitations of java Generics

1. Type variables are invalid in the static context of generic classes.


// Type variables cannot be referenced in static fields or methods 
private static T instance;
// Static method   As long as it is a generic method itself 
private static <T> T getInstance(){
}

2. Type variables cannot be instantiated.


// public Restrict() {
// this.data = new T();
// }

3. You cannot instantiate generic parameters with primitive types.


// NormalGeneric<double> normalGeneric = new NormalGeneric<>();
NormalGeneric<Double> normalGeneric = new NormalGeneric<>();

4. You cannot create an array of parameterized types.


Restrict<Double>[] restrictArray;
Restrict<Double>[] restricts = new Restrict<Double>[10];

Related articles: