Java generics

What is generics?

The generic type is jdk1 5 newly added to solve the security problem of data types. Its main principle is to use an identifier to represent the type of an attribute in the class or the return value and parameter type of a method when declaring the class. In this way, when declaring or instantiating a class, you only need to specify the specific type you need.

Why generics?

Java generics can ensure that ClassCastException exceptions will not be generated at runtime if the program does not issue a warning at compile time. At the same time, the code is more concise and robust.

Generics in Java are only valid at compile time. In the compilation process, after the generic results are correctly verified, the generic related information will be wiped out, and the methods of type checking and type conversion will be added at the boundary between the object and the method. That is, generic information will not enter the run-time phase.

For example: after declaring a collection using generics, for example, list < string > List = new ArrayList < string > (); List. In progress add(1); You will be prompted: the method add (int, string) in the type list < string > is not applicable for the arguments (int), which is still in the compilation stage.

@H_ 403_ 21 @ how do I use generics?

1. Generic class

2. Generic interface

3. Generic methods

4. Wildcard?

Restricted wildcards:

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>