Reference: https://www.cnblogs.com/wzy330782/p/5339180.html
If we need to produce multiple objects, the logic for each object is exactly the same, except that the member variables within the object are of different types. So how do we do that?
① Create multiple class files and set the specified data type for the member variables in each class;
Disadvantages: This approach leads to class bloat and poor reuse;
Create a class file and set the Object data type to the member variables of this class.
Disadvantages: Normal at compile time, but may be abnormal at run time;
Generic classes solve both of these problems;
Introduction of generic
Generics are the most important feature in JDK4.5.
(2) Generics can be recompiled to check type safety, and all casts are automatic and implicit;
③ The principle of generics is “parameterization of types”, that is, treating types as parameters. That is, the data type being manipulated is treated as a parameter, just as the formal parameters of a method are placeholders for values passed at run time;
(4) Simply put, a type variable plays the role of a parameter that provides information to the compiler for type checking.
(5) Generics can improve the extensibility and reuse of code;
Summary: The so-called generic, namely through the parameterized type to realize the operation of multiple data types in the same piece of code, generic programming is a programming paradigm, it uses the “parameterized type” to abstract the type, so as to achieve more flexible reuse;
Examples of generic classes:
T stands for type, like Integer, String
Use generic classes to solve these problems
Usage of generics
① Generic parameter types can make generic classes;
(2) Generic classes can set multiple type parameters at the same time;
③ Generic classes can inherit from generic classes;
(4) Generic classes can realize generic interfaces;