In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
Editor to share with you what is the use of generics in Java, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's learn about it!
Java added generics in 5. 0, and experts are said to have spent about five years on it (it doesn't sound easy). With generics, especially the use of collection classes, it becomes more standardized.
Look at the following simple code.
ArrayListlist=newArrayList (); list.add (Silence II); Stringstr=list.get (0); but what do you do before you have generics?
First, we need to use the Object array to design the Arraylist class.
ClassArraylist {privateObject [] objs;privateinti=0;publicvoidadd (Objectobj) {objs [iTunes +] = obj;} publicObjectget (inti) {returnobjs [I];}} then we access the data to Arraylist. Arraylistlist=newArraylist (); list.add (Silent King II); list.add (newDate ()); Stringstr= (String) list.get (0); have you found two problems:
Arraylist can hold any type of data (both strings and dates can be mixed) because all classes inherit from the Object class.
Type casting is required when fetching data from Arraylist, because the compiler is not sure whether you are fetching a string or a date.
By comparison, you can clearly feel the advantages of generics: the use of type parameters solves the uncertainty of elements-collections with a parameter type of String are not allowed to store other types of elements, and there is no need to cast when fetching data.
Second brother, how to design generics?
Third sister, as long as you know how to use generics, you still want to design generics? However, since you want to know, then I am duty-bound.
First, let's redesign the Arraylist class according to the standard of generics.
ClassArraylist {privateObject [] elementData;privateintsize=0;publicArraylist (intinitialCapacity) {this.elementData=newObject [initialCapacity];} publicbooleanadd (Ee) {elementData [size++] = eTrue;} EelementData (intindex) {return (E) elementData [index];}}
A generic class is a class that has one or more type variables. The type variable introduced by the Arraylist class is E (Element, the first letter of the element), enclosed in angle brackets and placed after the class name.
We can then instantiate the generic class by replacing the type variable with a specific type, such as a string.
Arraylistlist=newArraylist (); list.add (Silent King III); Stringstr=list.get (0)
The Date type is also available.
Arraylistlist=newArraylist (); list.add (newDate ()); Datedate=list.get (0)
Second, we can also define generic methods in a non-generic class (or generic class).
ClassArraylist {publicT [] toArray (T [] a) {return (T []) Arrays.copyOf (elementData,size,a.getClass ());}}
To be honest, however, the definition of generic methods looks a little obscure. Take a picture (note: at least one method return type and method parameter type are required).
Now, let's call the generic method.
Arraylistlist=newArraylist (4); list.add ("Shen"); list.add ("silent"); list.add ("Wang"); list.add ("II"); String [] strs=newString [4]; strs=list.toArray (strs); for (Stringstr:strs) {System.out.println (str);}
Finally, let's talk about the qualifier extends for generic variables. Before explaining this qualifier, let's assume that there are three classes, and the definition between them is like this.
ClassWanglaoer {publicStringtoString () {return "Wang er";}} classWangerextendsWanglaoer {publicStringtoString () {return "Wang er";}} classWangxiaoerextendsWanger {publicStringtoString () {return "Wang er";}}
Let's use the qualifier extends to redesign the Arraylist class.
ClassArraylist {}
When we add the Wanglaoer element to Arraylist, the compiler prompts an error: Arraylist only allows the addition of Wanger and its subclass Wangxiaoer object, not its parent class Wanglaoer.
Arraylistlist=newArraylist (3); list.add (newWanger ()); list.add (newWanglaoer ()); / / Themethodadd (Wanger) inthetypeArraylistisnotapplicableforthearguments// (Wanglaoer) list.add (newWangxiaoer ())
That is, the qualifier extends narrows the type range of generics.
Second brother, I heard that virtual machines are not generic?
Third sister, you have done your homework well, even the virtual machine knows it. I can answer you with certainty that there is no generics in virtual machines.
Say a word. The Java code we write (that is, source code with a .java suffix) is not directly recognized by the operating system and needs to be compiled to generate .class files (that is, bytecode files). The Java virtual machine (JVM) then acts as a translator, translating the bytecode into a language that the operating system can understand and telling it what to do.
How can I be sure that the virtual machine is not generic? We need to decompile the bytecode of generic classes-- the hypergod decompiler Jad is highly recommended!
Now, type the following code on the command line (decompile Arraylist's bytecode file Arraylist.class).
JadArraylist.class
After the command is executed, an Arraylist.jad file is generated, which is opened with a text editing tool as follows.
/ / DecompiledbyJadv1.5.8g.Copyright2001PavelKouznetsov.//Jadhomepage: http://www.kpdus.com/jad.html//Decompileroptions:packimports(3)//SourceFileName:Arraylist.javapackagecom.cmower.java_demo.fanxing;importjava.util.Arrays;classArraylist{publicArraylist(intinitialCapacity){size=0;elementData=newObject[initialCapacity];}publicbooleanadd(Objecte){elementData[size++]=e;returntrue;}ObjectelementData(intindex){returnelementData[index];}privateObjectelementData[];privateintsize;}
The type variable disappears and is replaced by Object!
In that case, what happens if the generic class uses the qualifier extends? Let's first take a look at the source code of Arraylist2.
The result of classArraylist2 {privateObject [] elementData;privateintsize=0;publicArraylist2 (intinitialCapacity) {this.elementData=newObject [initialCapacity];} publicbooleanadd (Ee) {elementData [size++] = eTrue;} EelementData (intindex) {return (E) elementData [index];}} bytecode file Arraylist2.class decompiled using Jad is as follows. / / DecompiledbyJadv1.5.8g.Copyright2001PavelKouznetsov.//Jadhomepage: http://www.kpdus.com/jad.html//Decompileroptions:packimports(3)//SourceFileName:Arraylist2.javapackagecom.cmower.java_demo.fanxing;//Referencedclassesofpackagecom.cmower.java_demo.fanxing://WangerclassArraylist2{publicArraylist2(intinitialCapacity){size=0;elementData=newObject[initialCapacity];}publicbooleanadd(Wangere){elementData[size++]=e;returntrue;}WangerelementData(intindex){return(Wanger)elementData[index];}privateObjectelementData[];privateintsize;}
The type variable is missing and E is replaced with Wanger.
As illustrated by the above two examples, the Java virtual machine erases the type variable of the generic type and replaces it with a qualified type (if there is no qualification, use Object).
Second brother, is there a problem with type erasure?
Third sister, don't say that there are really some "problems" in type erasure.
Let's take a look at this code.
PublicclassCmower {publicstaticvoidmethod (Arraylistlist) {System.out.println ("Arraylistlist");} publicstaticvoidmethod (Arraylistlist) {System.out.println ("Arraylistlist");}}
At a shallow level of consciousness, we take it for granted that Arraylist list and Arraylist list are two different types, because String and Date are different classes.
However, due to type erasure, the above code will not be compiled-- the compiler will prompt an error (which is the "problem" caused by type erasure):
Erasure of method method (Arraylist) is the same as another method in type
Cmower
Erasure of method method (Arraylist) is the same as another method in type
Cmower
The rough meaning is that the parameter types of the two methods are the same after erasing.
That is, method (Arraylist list) and method (Arraylist list) are methods of the same parameter type and cannot exist at the same time. The type variables String and Date automatically disappear after erasing, and the actual argument to the method method is Arraylist list.
As the saying goes, "it is better to hear than to see", but even if you see it, it may not be true-the erasure of generics can well support this view.
Second brother, I heard that generics have wildcards?
Third sister, I suddenly feel that you are very suitable to be a lovely female programmer! You've done your homework so well that you know it even with the wildcard.
Wildcards are represented by the English question mark (?). When we create a generic object, we can use the keyword extends to qualify the subclass or the keyword super to qualify the parent class.
In order to better interpret wildcards, we need to make some improvements to Arraylist.
ClassArraylist {privateObject [] elementData;privateintsize=0;publicArraylist (intinitialCapacity) {this.elementData=newObject [initialCapacity];} publicbooleanadd (Ee) {elementData [size++] = eTrue;} publicEget (intindex) {return (E) elementData [index];} publicintindexOf (Objecto) {if (o==null) {for (inti=0;i)
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.