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

How generics are used in Java

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article shows you how generics in Java are used, the content is concise and easy to understand, can definitely brighten your eyes, through the detailed introduction of this article, I hope you can get something.

Generics, in fact, is a relatively difficult grammar in Java. At the beginning, many people have little knowledge of it and are afraid to read the source code with generics. Although the grammar looks very difficult, it will feel very simple when you understand it. In fact, it is just a paper tiger. Next, I will take you to understand it in a very easy-to-understand way. I believe you will gain a lot after reading it carefully, and you will no longer be afraid of it!

one。 Definition of generics

Here, you don't have to look at some definitions on the Internet, because instead of being more academic, you just need to remember that generics can specify a certain type in the program design to make the program design more standardized.

two。 Why use generics?

Now that we know what generics are, let's discuss why we use generics, and what exactly is this syntax for? Don't worry, let me give you an example:

Class Stack {public Object [] objects; public int top; public Stack () {this.objects = new Object [10];} public void push (Object obj) {objects [this.top++] = obj;} public Object get () {return objects [this.top-1];}}

Can you take a look at what this is doing? We write a stack ourselves, and then set the array type in the stack to Object type, so that any type of data in the stack can be stored (Object class is the parent class of any class, no matter what type of data is inserted, it can be transformed upwards)

Next, let's test it.

Public class Test {public static void main (String [] args) {Stack stack=new Stack (); stack.push (1); stack.push (2); stack.push ("123"); String str= (String) stack.get ();}}

As you can see, we can put any type of data, such as shaping, strings, and so on, into the stack we write, but note that we have to cast when fetching the data.

If you write it this way, you can store any type of data in the stack, which is more general, and its advantages can also become disadvantages. It is precisely because it is too general that the code is less normative and looks messy. At this time, we can consider using generics, which can store specific data in classes or in Java collections (generics are generally used when using Java collections. Generics may or may not be used in custom types)

three。 The writing of generics

Take a custom type as an example, write it with angle brackets after the class name and a letter inside (note that any letter can be written here, only to mark the class as a generic class)

Class Stack

In the case of new objects, for example, only shaping can be stored in the stack. The front angle brackets must write the wrapper class corresponding to the basic data type, while the latter angle brackets can not be written. The example is as follows:

Stack stack = new Stack ()

Make up the basic data types in Java and the corresponding wrapper classes:

Therefore, the custom stack we wrote earlier can be written in the following form (take storage shaping as an example):

Class Stack {public T [] objects; public int top; public Stack () {this.objects = (T []) new Object [10];} public void push (T obj) {objects [this.top++] = obj;} public T get () {return objects [this.top-1];}} Stack stack = new Stack (); stack.push (1); stack.push (2) Int ret = stack.get (); System.out.println (ret)

Pay special attention to this: public Stack () {this.objects = (T []) new Object [10];}

It cannot be written as this.objects=new T [10].

Reason:

1. Arrays of generic types that cannot be new

two。 It can also be understood that generics are checked and then compiled, and if an array of new generic types is checked, the compiler does not know what type T is, so it will report an error. On the other hand, the erasure mechanism will only be implemented when compiling, and it will be converted to the Object type.

3. It is precisely because of this erasure mechanism that the array can be cast as a whole (generally, arrays cannot be cast as a whole), because generics only work at compile time, and the actual runtime will be erased to the Object type, that is, there is no concept of generics at the actual runtime, that is, the actual runtime types are all the same, so T is essentially an object type. So this code is equivalent to not casting!

4. The code that specifies generics directly (instead of T) for example: Stack and Stack erase the type in angle brackets directly at run time, and you can see the result printed directly (no type is printed):

Pay attention to understanding here

four。 Example of the use of generics 1. Seek the maximum value

The above is an important knowledge point of generics, but just looking at it is not enough, or we have to use examples to give us a deeper understanding, for example, how to write a generic class to find the maximum value of an array?

The basic framework goes something like this: (cutie who doesn't understand, take a good look at what's said above.)

Class Algorithm {public T findMax (T [] array) {T max = array [0]; for (int I = 1; I < array.length; iTunes +) {if (max < array [I]) {max = array [I];}} return max;}}

But this code if (max < array [I]) will report an error. Why? Because the value passed to T in the future must be a reference type, and the reference type cannot be directly greater or smaller, it should be compared with the method in the Comparable or Comparator interface, because the generics will be erased to the Object type when compiling, but the Object class itself does not implement the Comparable or Comparator interface, so we have to control it not to erase the Object class, so we need to specify a boundary for the generics.

It is written as follows:

Class Algorithm {public T findMax (T [] array) {T max = array [0]; for (int I = 1; I < array.length; iTunes +) {/ / max < array [I] if (max.compareTo (array [I]) < 0) {max = array [I];}} return max;}} class Algorithm

Note that extends is called the upper bound, and this code means that the generic class T will be erased to the place where the Comparable interface is implemented. In other words, this T type must implement the Comparable interface.

Similarly: this code public class MyArrayList {...} represents a subclass of Number or Number itself.

Let's use it next:

Algorithm algorithm1 = new Algorithm (); Integer [] integers = {1, algorithm1.findMax, 2, 13, 4, 5}; Integer ret = algorithm1.findMax (integers); System.out.println (ret)

The running results are as follows:

Succeed!

two。 Optimize

Through the above efforts, we have written a generic class to find the maximum value of an array, but the above example is an integer array, so can we store other types in the array to compare? The answer is yes, but we also have to new an object, for example: Algorithm algorithm2 = new Algorithm (); this is troublesome. But we can set the maximum method to static class Algorithm2, because it is static and does not need a new object, so there is no process of specifying generics in the new object, so there is no need to add angle brackets to the method, but after removing it, the code will be wrong again:

We can modify it as follows:

Class Algorithm2 {public static T findMax (T [] array) {T max = array [0]; for (int I = 1; I < array.length; iTunes +) {if (max.compareTo (array [I]) < 0) {max = array [I];}} return max;}}

This method public static T findMax (T [] array) {} is called a generic method.

Let's continue to bring you to use it:

Public static void main (String [] args) {Integer [] integers = {1 Integer [] 5}; / / the type parameters of the whole generic type Integer ret = Algorithm2.findMax (integers); System.out.println (ret); Integer ret2 = Algorithm2.findMax (integers); System.out.println (ret2);}

Note that ret1 is written in the same way as ret2, both are fine

The print result is as follows:

five。 Wildcard character 1. Basic writing method

Wildcards are also a kind of generics, so let's write a generic method to print the elements in the collection.

Class Test {public static void print (ArrayList list) {for (T t: list) {System.out.println (t);}}

This is a very simple way to write, as mentioned above, so let's try it:

Public static void main (String [] args) {ArrayList list = new ArrayList (); list.add (1); list.add (2); list.add (3); Test.print (list);}

The printed results are as follows:

In addition to the above writing, we can also change it to wildcard writing and give you the code first:

/ /? Represents the wildcard erasure mechanism Object public static void print2 (ArrayList list) {for (Object t: list) {System.out.println (t);}

Here for (Object t: list) must be written this way, because wildcards also have an erasure mechanism and Object types are programmed in the compiler.

two。 Upper bound

Syntax:

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