In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces "what are the methods for the use of Java generics". In daily operation, I believe many people have doubts about the use of Java generics. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful for you to answer the doubts about the use of Java generics. Next, please follow the editor to study!
Background
My understanding of java's generics is limited to a superficial level, and I didn't want to record it in detail until I found that there was something I didn't understand when I was learning the design pattern.
This article refers to the detailed explanation of java generics, the method of generics in Java, and the detailed explanation of java generics.
I have sorted out some related books and documents, which can be shared with you for free, just click on the link to join the group!
5 Java generics related learning books
22 Java architect Core Books
Learning routes and materials from 0 to 1Java
1000 + the latest interview questions in 2021
1. Overview
Generics play an important role in java and are widely used in object-oriented programming and various design patterns.
What is generics? Why use generics?
Generics, or "parameterized types". When it comes to parameters, the most familiar thing is to have formal parameters when defining a method, and then pass arguments when you call this method. So how do you understand parameterized types?
As the name implies, the type is parameterized by the original specific type, similar to the variable parameters in the method, and the type is also defined in the form of parameters (which can be called type parameters).
Then pass in the specific type (type argument) when using / calling.
The essence of generics is to parameterize types (the types of specific restrictions on formal parameters are controlled by different types specified by generics without creating new types). That is to say, in the use of generics,
The data type of the operation is specified as a parameter, which can be used in classes, interfaces, and methods, called generic classes, generic interfaces, and generic methods, respectively.
two。 A chestnut.
An example that has been cited countless times:
List arrayList = new ArrayList (); arrayList.add ("aaaa"); arrayList.add (100); for (int I = 0; I < arrayList.size (); iTunes +) {String item = (String) arrayList.get (I); Log.d ("generic Test", "item =" + item);}
There is no doubt that the running result of the program will end in a crash:
Java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
ArrayList can store any type. In the example, a String type is added, an Integer type is added, and the program crashes when it is used in a String way. In order to solve problems like this (which can be solved at compile time), generics emerge as the times require.
Let's change the first line of code that declares that the list is initialized, and the compiler will be able to help us find problems like this during the compilation phase.
List arrayList = new ArrayList ();. / / arrayList.add (100); during the compilation phase, the compiler reports an error of 3. Characteristics
Generics are only valid during the compile phase. Look at the following code:
List stringArrayList = new ArrayList (); List integerArrayList = new ArrayList (); Class classStringArrayList = stringArrayList.getClass (); Class classIntegerArrayList = integerArrayList.getClass (); if (classStringArrayList.equals (classIntegerArrayList)) {Log.d ("generic test", "same type");}
Output: d / generic test: same type.
As can be proved by the above example, the program will take measures to de-generalize after compilation. In other words, generics in Java are only valid during the compile phase. During compilation, after correctly verifying the generic results, the relevant information about the generics is erased, and methods of type checking and type conversion are added at the boundaries where the object enters and leaves the method. That is, generic information does not enter the runtime phase.
This can be summed up in one sentence: generic types are logically regarded as many different types, but in fact they are all the same basic types.
4. The use of generics
Generics can be used in three ways: generic classes, generic interfaces, and generic methods.
4.3 generic classes
Generic types are used in the definition of classes and are called generic classes. Through generics, you can open the same interface to the operation of a set of classes. The most typical are various container classes, such as List, Set, Map.
The most basic way to write a generic class (which may be a little dizzy in this way, which will be explained in more detail in the following example):
Class class name {private generic ID / * (member variable type) * / var;. }}
One of the most common generic classes:
/ / T can be written as any identification here. Common parameters such as T, E, K, V and so on are often used to indicate generics / / when instantiating a generic class, you must specify the specific type of T, public class Generic {/ / key. The type of member variable is TMague T, which is externally specified as private T key. Public Generic (T key) {/ / generic constructor formal parameter key is also of type Tkey; T specified externally by this.key = key;} public T getKey () {/ / generic method getKey the return value type is TMagne T and the type is externally specified return key }} / / the type parameter of a generic type can only be a class type (including a custom class), and cannot be a simple type / / the argument type passed in must be the same as the type parameter type of the generic type, that is, Integer.Generic genericInteger = new Generic (123456); / / the passed argument type should be the same as the type parameter type of the generic type, that is, String.Generic genericString = new Generic ("key_vlaue") Log.d ("generics test", "key is" + genericInteger.getKey ()); Log.d ("generics test", "key is" + genericString.getKey ()); 12-27 0920 genericInteger.getKey 04.432 13063-13063max? D / generics test: key is 12345612-27 009 0432 13063-13063? D / generic test: key is key_vlaue
For a defined generic class, do you have to pass in generic type arguments? This is not the case. If generic arguments are passed in when using generics, restrictions will be made according to the passed generic arguments. Only then will generics play the limiting role that should have been played. A type defined using generic methods or member variables in a generic class can be any type without passing in generic type arguments.
Look at an example:
Generic generic = new Generic ("111111"); Generic generic1 = new Generic (4444); Generic generic2 = new Generic (55.55); Generic generic3 = new Generic (false); Log.d ("generic Test", "key is" + generic.getKey ()); Log.d ("generic Test", "key is" + generic1.getKey ()); Log.d ("generic Test", "key is" + generic2.getKey ()); Log.d ("generic Test", "key is" + generic3.getKey ()) D / generic test: key is 111111D/ generic test: key is 4444D/ generic test: key is 55.55D/ generic test: key is false
Note:
The type parameters of generics can only be class types, not simple types.
You cannot use instanceof operations on exact generic types. If the following operation is illegal, there will be an error during compilation.
If (ex_num instanceof Generic) {}
4.4 generic interface
The definition and use of generic interfaces are basically the same as those of generic classes. Generic interfaces are often used in various types of producers. Take a look at an example:
/ / define a generic interface public interface Generator {public T next ();}
When a generic argument is not passed in to a class that implements a generic interface:
When no generic argument is passed in, the definition of the generic class is the same as that of the generic class. When declaring the class, the declaration of the generic type needs to be added to the class * that is: class FruitGenerator implements Generator {* if the generic type is not declared, such as class FruitGenerator implements Generator, the compiler will report an error: "Unknown class" * / class FruitGenerator implements Generator {@ Override public T next () {return null;}}
When a class that implements a generic interface passes in a generic argument:
/ * when passing generic arguments: * define a producer to implement this API. Although we have only created a generic interface Generator *, we can pass numerous arguments to T to form numerous types of Generator interfaces. * when the implementation class implements the generic interface, if the generic type has been passed into the argument type, all places where the generic type is used should be replaced with the passed argument type * that is, the T in Generator,public T next (); should be replaced with the passed String type. * / public class FruitGenerator implements Generator {private String [] fruits = new String [] {"Apple", "Banana", "Pear"}; @ Override public String next () {Random rand = new Random (); return fruits [rand.nextInt (3)];}} 4.5 generic wildcards
We know that Ingeter is a subclass of Number, and we have verified in the features section that Generic and Generic are actually the same basic type. So the question is, in the method that uses Generic as the formal parameter, can an instance of Generic be passed in? Can logically similar Generic and Generic be regarded as generic types with a parent-child relationship?
To figure this out, let's use the generic class Generic to continue with the following example:
Public void showKeyValue1 (Generic obj) {Log.d ("generic testing", "key value is" + obj.getKey ());} Generic gInteger = new Generic (123); Generic gNumber = new Generic (456); showKeyValue (gNumber); / / showKeyValue this method compiler will report an error for us: Generic// cannot be applied to Generic// showKeyValue (gInteger)
From the prompt, we can see that Generic cannot be regarded as a subclass of ``Generic`. It can be seen that the same generic type can correspond to multiple versions (because the parameter type is uncertain), and different versions of generic class instances are incompatible.
Going back to the above example, how to solve the above problem? You can't deal with classes of type Generic in order to define a new method, which obviously runs counter to the concept of multiple machines in java. So we need a reference type that logically represents both the Generic and Generic parent classes. This type wildcard arises at the historic moment.
We can change the above method:
Public void showKeyValue1 (Generic obj) {Log.d ("generic test", "key value is" + obj.getKey ());}
Type wildcards are generally used? Instead of specific type arguments, note that here'?' Is a type argument, not a type parameter. Say it three times! Here'?' Is a type argument, not a type parameter! Here'?' Is a type argument, not a type parameter! To be more straightforward, what do you mean here? It is a practical type like Number, String and Integer. As the parent of all types. It's a real type.
It can be solved that when the specific type is uncertain, the wildcard is?; when you manipulate the type, you only use the functions in the Object class when you do not need to use the specific functions of the type. So it works? Wildcards to indicate unknown types.
4.6 generic method
In java, the definition of generic classes is very simple, but generic methods are more complex.
In particular, most of the member methods in generic classes we see also use generics, and some even contain generic methods in generic classes, so it is very easy for beginners to misunderstand generic methods.
A generic class indicates the specific type of a generic type when instantiating a class; a generic method specifies the specific type of a generic type when calling a method.
The return value of the generic argument * @ return T passed in by * @ param tClass is of type T * description: * 1) it is very important between the public and the return value, which can be understood as declaring that this method is a generic method. * 2) only declared methods are generic methods, and member methods in generic classes that use generics are not generic methods. * 3) indicates that the method will use the generic type T before you can use the generic type T in the method. * 4) like the definition of a generic class, T can be written as any identification here, and common parameters such as T, E, K, V are often used to represent generics. * / public T genericMethod (Class tClass) throws InstantiationException, IllegalAccessException {T instance = tClass.newInstance (); return instance;} Object obj = genericMethod (Class.forName ("com.test.test")); 4.6.1 basic usage of generic methods
Just looking at the above example, some students may still be very confused. Let's summarize my generics method again through another example.
Public class GenericTest {/ / this class is a generic class. I've already introduced public class Generic {private T key; public Generic (T key) {this.key = key;} / / what I'm trying to say is this. Although generics are used in methods, this is not a generic method. / / this is just a normal member method in a class, but its return value is declaring a generic class that has already been declared. / / so you can continue to use the generics T in this method. The public T getKey () {return key;} / * method is obviously problematic. The compiler will prompt us with the error message "cannot reslove symbol E" * because the generic E is not declared in the class declaration, so the compiler will not recognize it when using E as formal parameters and return value types. Public E setKey (E key) {this.key = keu} * / * * this is a true generic method. * first of all, it is necessary between the public and the return value, which indicates that this is a generic method and declares a generic T * this T can appear anywhere in the generic method. * the number of generics can also be any number * for example: public K showKeyName (Generic container) {* *} * / public T showKeyName (Generic container) {System.out.println ("container key:" + container.getKey ()); / / of course, this example is not appropriate, just to illustrate the characteristics of generic methods. T test = container.getKey (); return test;} / / this is not a generic method, it's just a common method, just using the generic class Generic as a formal parameter. Public void showKeyValue1 (Generic obj) {Log.d ("generic testing", "key value is" + obj.getKey ());} / / this is not a generic method, it is also a common method, but it uses the generic wildcard? / / and it also confirms what is described in the generic wildcard chapter. Is a type argument that can be regarded as the parent class public void showKeyValue2 (Generic obj) {Log.d ("generic test", "key value is" + obj.getKey ()) of all classes such as Number. The method} / * is problematic, and the compiler will prompt us with an error message: "UnKnown class 'E'" * although we have declared that this is a generic method that can handle generic types. * but only the generic type T is declared, not the generic type E, so the compiler does not know what to do with the type E. Public T showKeyName (Generic container) {.} * / / * * this method is also problematic, and the compiler will prompt us with an error message: "UnKnown class 'T'" * for the compiler, the type T is not declared in the project, so the compiler does not know how to compile the class. * so this is not a correct generic method declaration. Generic methods in public void showkey (T genericObj) {} * / public static void main (String [] args) {}} 4.6.2 classes
Of course, this is not the whole story of generic methods, which can be used anywhere and in any scenario. But there is a very special case. When a generic method appears in a generic class, let's look at it through another example.
Public class GenericFruit {class Fruit {@ Override public String toString () {return "fruit";}} class Apple extends Fruit {@ Override public String toString () {return "apple";}} class Person {@ Override public String toString () {return "Person" }} class GenerateTest {public void show_1 (T t) {System.out.println (t.toString ());} / declares a generic method in the generic class, using generic E, which can be of any type. It can be the same as T, or it can be different. / / because generic methods declare generics when they are declared, the compiler can correctly recognize generics identified in generic methods, even if generics are not declared in generic classes. Public void show_3 (E t) {System.out.println (t.toString ());} / declares a generic method in the generic class, using the generic T, note that this T is a completely new type and can be different from the T declared in the generic class. Public void show_2 (T t) {System.out.println (t.toString ());}} public static void main (String [] args) {Apple apple = new Apple (); Person person = new Person (); GenerateTest generateTest = new GenerateTest (); / / apple is a subclass of Fruit, so here you can generateTest.show_1 (apple) / / the compiler will report an error because the generic type argument specifies Fruit and the passed argument class is Person / / generateTest.show_1 (person); / / both methods can be used to successfully generateTest.show_2 (apple); generateTest.show_2 (person); / / both methods can also be used to successfully generateTest.show_3 (apple) GenerateTest.show_3 (person);}} 4.6.3 generic methods and variable parameters
Look at another example of generic methods and variable parameters:
Public void printMsg (T... Args) {for (T t: args) {Log.d ("generic test", "t is" + t);} printMsg ("111,222," aaaa "," 2323.4 ", 55.55); 4.6.4 static methods and generics
One thing to note about static methods is that static methods in a class use generics: static methods cannot access generics defined on the class; if the reference data type of static method operations is uncertain, generics must be defined on methods.
That is, if static methods are to use generics, static methods must also be defined as generic methods.
Public class StaticGenerator {.... .... / * if you define a static method that uses generics in a class, you need to add an additional generic declaration (defining the method as a generic method) * even if the static method is to use generics that have already been declared in the generic class. * for example: public static void show (T t) {..}, the compiler will prompt an error message: "StaticGenerator cannot be refrenced from static context" * / public static void show (T t) {}} 4.6.5 generic method summary
Generic methods can make methods change independently of the class. Here is a basic guiding principle:
Whenever you can do it, you should try to use generic methods. That is, if you use a generic method to generalize the entire class, you should use the generic method. In addition, for a method of static, you cannot access the parameters of a generic type. So if the static method is to use generic capabilities, it must be made generic.
4.6 Upper and lower boundaries of generics
When using generics, we can also impose upper and lower boundaries on incoming generic type arguments, for example, type arguments are only allowed to pass in a certain type of parent class or a certain type of subclass.
Add an upper boundary to the generic type, that is, the type argument passed in must be a subtype of the specified type
Public void showKeyValue1 (Generic
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.