The role and benefits of java generics

Reprinted in: https://blog.csdn.net/u012760183/article/details/52092692

When I participated in the interview before, the interviewer asked about the role of generics, and I just said my understanding.

Reprint and record here to deepen your impression

Generics benefits:

Generics are easy to use

The main goal of type-safe generics is to achieve type-safety in java. Generics allow the compiler to know what the qualified type of an object is, so that the compiler can verify the type to a high degree

Elimination of casts makes the code more readable and reduces the chance of many errors

The advantage of introducing generics in the Java language is that it is safe and simple. The benefit of generics is that type safety is checked at compile time, and all casts are automatic and implicit, improving code reuse.

Generic implementation principle

The implementation of generics is based on type erasure technology. Type erasure is completed at compile time, that is, at compile time, the compiler will erase the type parameters of the generic type to its qualified type, and if not, it will be erased to the object type. Then cast the type to the corresponding type when you get it. There is no information about generics at runtime, so there is no optimization.

Generics do not consider inheritance

Is a List type assignable to a List type?
The answer is no.
Although it is said that the String type can be used as an Object type after assignment, there will still be problems.
Suppose the following code

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325382415&siteId=291194637
Recommended