Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the purpose of Java generics

2025-01-20 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Most people do not understand the knowledge points of this article "what is the role of Java generics", so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "what is the role of Java generics" article.

Brief introduction

The function of generics is to parameterize types, that is, what we often call type parameters.

The parameters of the common method that we usually come into contact with, such as public void fun (String s); the type of parameter is String, which is fixed

Now the function of generics is to define String as a variable parameter, that is, to define a type parameter T, such as public static void fun (T t). In this case, the type of parameter is the type of T, which is not fixed.

Judging from the String and T above, generics have a strong taste of polymorphism, but in fact, generics are different from polymorphisms.

In essence, polymorphism is a feature and a concept in Java, and generics are real types.

Most of the examples in the text are introduced by taking generics in the collection as examples, because they are used more and are familiar to everyone.

What are type parameters in the body?

The type parameter is the type of the parameter, which accepts the class as the actual value

In vernacular terms, you can think of type parameters as formal parameters and the actual passed classes as arguments.

For example, the type parameter E in ArrayList is regarded as a formal parameter, and the class String in ArrayList is regarded as an argument.

If you have learned the factory design pattern, you can think of the ArrayList here as a factory class, and then pass in the corresponding type parameters for what type of ArrayList you need.

For example, input Integer is the ArrayList class

For example, input String is the ArrayList class

Why should there be generics?

Mainly to improve the readability and security of the code.

Specifically, we should start with the evolution history of generics.

The evolution of generics

In a broad sense, generics have existed for a long time, but they exist implicitly.

For example, List list = new ArrayList (); / / is equivalent to List list = new ArrayList ()

But generics at this time are fragile, with poor readability and security (collections during this period are not very advantageous over arrays)

First, there is no type checking when populating the data, so it is possible to put Cat into the Dog collection

Second, type conversion is required when fetching, and if you are lucky enough to put the object in the wrong collection (possibly intentionally), the runtime will report an error conversion exception (but the compilation can pass)

However, when it comes to JDK1.5, there are true generics (type parameters, represented by angle brackets)

For example, in the List collection class, E is the type parameter of the generic type. Because all the stored elements in the collection are Element, they are replaced by the E letter (similarly, there is also Tepagne, Kremlin, keymor, VMI value).

At this time, the robustness of the program is improved, readability and security are also very high, and you can see at a glance what is being put in it (the advantages of collections in this period are obvious over arrays).

Now take List list = new ArrayList (); as an example.

First, when populating the data, the compiler itself does type checking to prevent Cat from being put into the Dog

Second, when fetching data, there is no need for us to do the type conversion manually, the compiler will do the type conversion itself.

If you are careful, you may have found that now that you have generics, what I put in is Dog, but shouldn't I also take out Dog? Why does the compiler need type conversion?

This leads to the concept of type erasure.

Type erase

What is type erasure?

Type erasure means that when you assign a value to a type parameter, the compiler erases the argument type to Object (assuming there is no qualifier here, which will be discussed below)

So we need to understand one thing here: there is no concept of generic type objects in the virtual machine, and in its eyes, all objects are ordinary objects.

For example, the following code

Before erasure

Public class EraseDemo {private T t; public static void main (String [] args) {} public T getT () {return t;} public void setT (T t) {this.t = t;}}

After erasing

Public class EraseDemo {private Object t; public static void main (String [] args) {} public Object getT () {return t;} public void setT (Object t) {this.t = t;}}

As you can see, T has become Object.

The raw type after the generic class is erased is generally called the primitive type. For example, the primitive type after EraseDemo erasure is EraseDemo.

Accordingly, if you have two array lists, ArrayList and ArrayList, the compiler will erase both to ArrayList.

You can test it with the code.

ArrayList list1 = new ArrayList (); ArrayList list2 = new ArrayList (); System.out.println (list1.getClass () = = list2.getClass ()); / / true will be printed here

What is the qualifier mentioned above?

Qualifiers are used to define boundaries. If generics have set boundaries, for example, when erasing, the first boundary Animal class is erased instead of the Object class.

Let's take the above code as an example to show the comparison before and after erasure

Before erasing:

Public class EraseDemo {private T t; public static void main (String [] args) {} public T getT () {return t;} public void setT (T t) {this.t = t;}}

After erasing:

Public class EraseDemo {private Animal t; public static void main (String [] args) {} public Animal getT () {return t;} public void setT (Animal t) {this.t = t;}}

Does the extends symbol here mean inheritance?

No, the extends here just means that the former is a subclass of the latter and can be inherited or implemented.

Extends is used only because this keyword is already built into Java and is more contextual

If you create your own keyword, such as sub, it may cause problems with some old code (such as code that uses sub as a variable)

Why erase it?

In fact, it is not a question of whether or not to erase, but a question that has to be erased.

Because the old code has no concept of generics, the main purpose of erasing here is to be compatible with the old code, so that the old code and the new code can call each other.

Application scenarios of generics

In the general direction:

Used in classes: called generic classes, followed by class names, such as ArrayList

Used in a method: it is called a generic method, and the return value of the method is added before, for example: public void fun (T obj)

Do you think of abstract classes and abstract methods?

There is still a difference. Abstract classes and abstract methods are interrelated, but there is no connection between generic classes and generic methods.

Focus on the class direction: generics are often used in collection classes, such as ArrayList

If it is custom generics, the generic method is recommended for two reasons:

Use it separately from generic classes to make the code clearer (you don't have to generalize the entire class for a small function)

In generic classes, static methods cannot use type parameters; but static generic methods can

Wildcard qualification

The main introduction here is: this belongs to an infinitely fixed wildcard, that is, it doesn't know what type to put in it, so it doesn't let you add it at all, you can only get it (this is similar.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report