127. Generic

1. What is generic? Why use it?

Deferring the type-specific work until the object is created or the method is called to specify the special type

Parameterized type:

  • Pass the type as a parameter

  • <数据类型> Can only be reference types

Why use generics?

When there is no generic type, any type can be added to the collection, causing type insecurity. Objects read from String type objects need to be forced: cumbersome may have ClassCastException

 

With generics:

  • The code is more concise [no forced conversion]

  • The program is more robust [As long as there is no warning during compilation, then there will be no ClassCastException exception during runtime]

  • Readability and stability [When writing a collection, the type is limited]

2. What are the types of generics? T, <> are more common

E-Element (used in a collection, because the collection is an element)

T-Type (Java class) K-Key (key)

V-Value N-Number (number type)

? -Represents uncertain java types ------- "Wildcard S, U, V-2nd, 3rd, 4th types

Guess you like

Origin blog.csdn.net/weixin_43206161/article/details/113001830