Java generics, basic understanding of "parameterized parameters"

Java introduced the new feature of generics in JDK1.5. The essence of generics is a parameterized type, that is to say, the data type can be specified as a parameter, and this parameter type can be used in the creation of classes, interfaces, and methods . Generics are widely used in the Java language Collection. For example, List allows any type of object to be inserted, and more types such as List and List can be declared in the program.

So, what is a parameterized type? In fact, the parameter is an external variable. For a method, its parameters are passed in from the outside, so, is the type of the parameter also used as a parameter, which is determined at runtime? The answer is yes, generics can do this.

Generics bring many programming benefits to programmers, specifically the following two points:
1) Simple and safe. On the one hand, since type checking is performed during compilation, security is improved. On the other hand, errors can be reported during the compilation phase, thereby reducing the programmer's debugging workload.
2) Performance improvement. Take the container as an example. When there is no generic type, since the type returned by the container is of the Object type, the return value needs to be cast to the desired type according to the actual situation. After the introduction of generics, since the type stored in the container can be determined at the time of declaration, the operation of the container does not require type conversion. The advantage of this is that it enhances the readability of the code and reduces the error of the program. Possibility, on the other hand, also improves the efficiency of program operation.

Generics provide the following functions:
1) Avoid coercive type conversion in the code.
2) Limited type. An additional type check is provided at compile time to prevent incorrect values ​​from being stored in the container.
3) Realize some special programming skills. For example: Provide a method for copying an object, and make the return value type consistent with the method parameter type without providing additional method parameters.

Guess you like

Origin blog.csdn.net/qq_41885819/article/details/110923008