On Generics

There are generics in Java. One advantage of using generics is that we can avoid complicated type coercion. Here is an example, the List collection we usually use, we can put various types of objects into it. When fetching, we can use type coercion. When the collection stores all elements of one type, there is no problem, but when the collection has classes of this and that, a cast doesn't make it all work, and it's written in There is no problem at compile time, but the forced conversion fails at runtime and a ClassCastException error is reported. Because when the object is put into the collection, the collection will not remember the type of the object, and it is recognized as the Object type at compile time, but the object type at runtime is itself.

Using generics when defining a domain can inform the compiler in advance that this type of value is stored in this domain. If you try to use coercion again, the compiler will report an error. Doing so can also prevent the compiler from storing the wrong type in the field, which will cause a compilation error. If no errors are reported at compile time, this also ensures that no errors are reported at runtime. That's the benefit of generics.

The following are specific generic usage methods. For example, when defining a collection, use List to define it. By reading the source code, you can see that the add and get methods in the interface both return E, which is String here. Therefore, when trying to add an Integer to the List at this time, an object type compilation error will occur.

Let's go a step further. Join We created a generic class ourselves and generated two different class instances, that is, the incoming generic arguments are not the same. But at this time, through the test, we will see that these two classes are actually the same as the original basic classes. What is the reason for this? Because Java's concept of generics only stays in the compiler stage, after compiling into a .class file, the generic information has been correctly checked out, then the generic information will be erased, and after successful compilation The .class file will not contain any generic information, that is to say, the generic information will not enter the running phase.

Another way to use generics is to use type wildcards. There are two types here, which are the upper limit of type wildcards and the lower limit of type wildcards. For example, when we define a method, there is a further restriction on the actual parameters of the type, which is Box<? extends Number>used . This will only accept the Number class and its subclasses. Otherwise, use ? super Number.

All in all, Generics, the most important thing is to understand the purpose of Java, the ideas in it.

Reference: Java Summary Series: Java Generics

Guess you like

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