In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article is to share with you about what is Generics in Java. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
one。 What is Generics?
Generics can be called a parameter type (parameterized types), and the compiler verifies the mechanism for passing a type from the client to an object. Such as Java.util.ArrayList
The compiler can use Generics to ensure type safety.
Before we delve into Generics, let's take a look at the current java Collection Framework (Collection). The Root Interface of all collections in j2SE1.4 is Collection
Collections example without genericity: Example 1
1 protected void collectionsExample () {
2 ArrayList list = new ArrayList ()
3 list.add (new String ("test string"))
4 list.add (new Integer (9)); / / purposely placed here to create a runtime ClassCastException
5 inspectCollection (list)
6}
seven
eight
9 protected void inspectCollection (Collection aCollection) {
10 Iterator I = aCollection.iterator ()
11 while (i.hasNext ()) {
12 String element = (String) i.next ()
13}
14}
The above sample program contains two methods, the collectionExample method establishes a simple collection type ArrayList, and adds a String and an Integer object to ArrayList. In the inspecCollection method, we iterate over the ArrayList to Cast with String. When we look at the second method, there is a problem. Collection uses Object internally, and when we want to extract objects from Collection, we need to do Cast, then the developer must Cast with the actual type, like this downward modeling, the compiler has no
Method, so we run the risk of throwing ClassCastException while the code is running. When we look at the inspecCollection method, there is no problem at compile time, but a ClassCastException exception is thrown at run time. So we have to stay away from this big runtime error.
two。 Use Generics
From the exception of CassCastException in the previous chapter, we expect to be able to catch it when the code is compiled, so let's use the paradigm to modify the sample program in the previous chapter.
/ / Example 2
1 protected void collectionsExample () {
2 ArrayList
List = new ArrayList ()
3 list.add (new String ("test string"))
4 / / list.add (new Integer (9)); this no longer compiles
5 inspectCollection (list)
6}
seven
eight
9 protected void inspectCollection (CollectionaCollection) {
10 Iteratori = aCollection.iterator ()
11 while (i.hasNext ()) {
12 String element = i.next ()
13}
14}
From line 2 above, we used the new syntax when creating the ArrayList, and all the Collection in the JDK1.5 added the Generics declaration. Example:
/ / Example 3
1 public class ArrayListextends AbstractList {
2 / / details omitted...
3 public void add (E element) {
4 / / details omitted
5}
6 public Iteratoriterator () {
7 / / details omitted
8}
9}
This E is a type variable, and there is no specific type definition for it. It is just a type placeholder when defining ArrayList. In Example 2, we are defining the reality of ArrayList.
For example, we use String to bind to E, and when we use the add (E element) method to add objects to ArrayList, it is written like the following: public void add (String element); because in ArrayList all methods will use String instead of E, whether it is the method parameter or the return value. At this point we are looking at the fourth line in Example 2, and the compilation will reflect the compilation error.
So the main purpose of adding Generics to java is to increase type safety.
From the simple example above, we can see that the benefits of using Generics are:
1. Collection is type-safe when the type does not change.
two。 The internal type conversion is better than the external artificial modeling.
3. Makes the Java interface stronger because it adds types.
4. Type matching errors can be caught at compile time, not when the code is running.
Constrained type variable
Although many Class are designed as Generics, type variables can be limited
Public class C1 {}
Public class C2 {}
The first T variable must inherit Number, and the second T must inherit Person and implement Comparable
III. Generics method
Like Generics classes, methods and constructors can have type parameters. The return values of the parameters of the method can all have type parameters for Generics.
/ / Example 4
1 publicT max (T T1, T T2) {
2 if (t1.compareTo (T2) > 0)
3 return t1
4 else return t2
5}
Here, the parameter type of the max method is a single T type, and the T type inherits the same superclass as the parameter and return value of Comparable,max. Example 5 below shows several constraints of the max method.
/ / Example 5
1 Integer iresult = max (new Integer, new Integer)
2 String sresult = max ("AA", "BB")
3 Number nresult = max (new Integer, "AAA"); / / does not compile
In line 1 of Example 5, the arguments are all Integer, so the return value is also Integer. Notice that the return value is not styled.
In line 2 of Example 5, the arguments are all String, so the return value is also String. Note that the return value is not styled. The above all call the same method.
The following compilation error was generated on line 3 of Example 5:
Example.java:10: incompatible types
Found: java.lang.Object&java.io.Serializable&java.lang.Comparable
Required: java.lang.Number
Number nresult = max (new Integer, "AAA")
This error occurs because the compiler cannot determine the return type because both String and Integer have the same superclass Object. Note that even if we correct the third line, this line of code will still report an error when running because different objects are compared.
four。 Backward compatibility
When any new feature comes out in the new version of JDK, our first concern is how to be compatible with previously written code. In other words, the Example 1 program we wrote can run without any changes, but the compiler will give a "ROW TYPE" warning. How the code written in JDK1.4 is fully compatible with JVM1.5, we need to do one manually: the Type erasure process.
five。 Wildcard character
/ / Example 6
ListstringList = new ArrayList (); / / 1
ListobjectList = stringList; / / 2
ObjectList .add (new Object ()); / / 3
String s = stringList. Get (0); / / 4
At first glance, Example
6 is correct. But stringList is meant to store ArrayList of type String, and any object can be stored in objectList. When processing on line 3, stringList cannot guarantee that it is an ArrayList of type String. At this time, the compiler does not allow this to happen, so line 3 will not compile.
/ / Example 7
Void printCollection (Collectionc)
{for (Object e: C) {
System.out.println (e)
}}
The original intention of Example 7 is to print all Collection objects, but as Example 6 said, the compilation will report an error, so you can use the wildcard "?" To modify Example 7
/ / Example 8
Void printCollection (Collection c)
{for (Object e: C) {
System.out.println (e)
}}
All Collection types in Example 8 can be printed easily.
Bounded wildcard (upper bound) (lower bound)
six。 Create your own model
The following code is from http://www.java2s.com/ExampleCode/Language-Basics
1. Generics of a parameter
/ / Example 9 (no paradigm is used)
Class NonGen {
Object ob; / / ob is now of type Object
/ / Pass the constructor a reference to
/ / an object of type Object
NonGen (Object o) {
Ob = o
}
/ / Return type Object.
Object getob () {
Return ob
}
/ / Show type of ob.
Void showType () {
System.out.println ("Type of ob is" +
Ob.getClass () .getName ()
}
}
/ / Demonstrate the non-generic class.
Public class NonGenDemo {
Public static void main (String args []) {
NonGen iOb
/ / Create NonGen Object and store
/ / an Integer in it. Autoboxing still occurs.
IOb = new NonGen (88)
/ / Show the type of data used by iOb.
IOb.showType ()
/ / Get the value of iOb.
/ / This time, a cast is necessary.
Int v = (Integer) iOb.getob ()
System.out.println ("value:" + v)
System.out.println ()
/ / Create another NonGen object and
/ / store a String in it.
NonGen strOb = new NonGen ("Non-Generics Test")
/ / Show the type of data used by strOb.
StrOb.showType ()
/ / Get the value of strOb.
/ / Again, notice that a cast is necessary.
String str = (String) strOb.getob ()
System.out.println ("value:" + str)
/ / This compiles, but is conceptually wrong!
IOb = strOb
V = (Integer) iOb.getob (); / / runtime error!
}
}
/ / Example 10 (use paradigm)
Class Example1 {
Private T t
Example1 (to) {
This.t=o
}
T getOb () {
Return t
}
Void ShowObject () {
System.out.println ("the type of object is:" + t.getClass () .getName ())
}
}
Public class GenericsExample1 {
/ * *
* @ param args
, /
Public static void main (String [] args) {
/ / TODO Auto-generated method stub
Example1examplei=new Example1 (100)
Examplei.ShowObject ()
System.out.println ("object is:" + examplei.getOb ())
Example1examples=new Example1 ("Bill")
Examples.ShowObject ()
System.out.println ("object is:" + examples.getOb ())
}
}
Let's see that Example 9 doesn't use paradigms, so we need styling, while Example 10 we don't need any styling.
two。 Generics with two parameters
/ / Example 11
Class TwoGen {
T ob1
V ob2
/ / Pass the constructor a reference to
/ / an object of type T.
TwoGen (T1, VO2) {
Ob1 = o1
Ob2 = O2
}
/ / Show types of T and V.
Void showTypes () {
System.out.println ("Type of T is" +
Ob1.getClass () .getName ()
System.out.println ("Type of V is" +
Ob2.getClass () .getName ()
}
T getob1 () {
Return ob1
}
V getob2 () {
Return ob2
}
}
Public class GenericsExampleByTwoParam {
/ * *
* @ param args
, /
Public static void main (String [] args) {
/ / TODO Auto-generated method stub
TwoGentgObj =
New TwoGen (88, "Generics")
/ / Show the types.
TgObj.showTypes ()
/ / Obtain and show values.
Int v = tgObj.getob1 ()
System.out.println ("value:" + v)
String str = tgObj.getob2 ()
System.out.println ("value:" + str)
}
}
Hierarchy of 3.Generics
/ / Example 12
Class Stats {
T [] nums; / / array of Number or subclass
/ / Pass the constructor a reference to
/ / an array of type Number or subclass.
Stats (T [] o) {
Nums = o
}
/ / Return type double in all cases.
Double average () {
Double sum = 0.0
For (int item0; I
< nums.length; i++) sum += nums.doubleValue(); return sum / nums.length; } } public class GenericsExampleByHierarchy { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Integer inums[] = { 1, 2, 3, 4, 5 }; Statsiob = new Stats(inums); double v = iob.average(); System.out.println("iob average is " + v); Double dnums[] = { 1.1, 2.2, 3.3, 4.4, 5.5 }; Statsdob = new Stats(dnums); double w = dob.average(); System.out.println("dob average is " + w); // This won't compile because String is not a // subclass of Number. // String strs[] = { "1", "2", "3", "4", "5" }; // Statsstrob = new Stats(strs); // double x = strob.average(); // System.out.println("strob average is " + v); } } 4.使用通配符 //Example 14 class StatsWildCard{ T[] nums; // array of Number or subclass // Pass the constructor a reference to // an array of type Number or subclass. StatsWildCard(T[] o) { nums = o; } // Return type double in all cases. double average() { double sum = 0.0; for (int i = 0; i < nums.length; i++) sum += nums.doubleValue(); return sum / nums.length; } // Determine if two averages are the same. // Notice the use of the wildcard. boolean sameAvg(StatsWildCard ob) { if (average() == ob.average()) return true; return false; } } public class GenericsExampleByWildcard { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Integer inums[] = { 1, 2, 3, 4, 5 }; StatsWildCardiob = new StatsWildCard(inums); double v = iob.average(); System.out.println("iob average is " + v); Double dnums[] = { 1.1, 2.2, 3.3, 4.4, 5.5 }; StatsWildCarddob = new StatsWildCard(dnums); double w = dob.average(); System.out.println("dob average is " + w); Float fnums[] = { 1.0F, 2.0F, 3.0F, 4.0F, 5.0F }; StatsWildCardfob = new StatsWildCard(fnums); double x = fob.average(); System.out.println("fob average is " + x); // See which arrays have same average. System.out.print("Averages of iob and dob "); if (iob.sameAvg(dob)) System.out.println("are the same."); else System.out.println("differ."); System.out.print("Averages of iob and fob "); if (iob.sameAvg(fob)) System.out.println("are the same."); else System.out.println("differ."); } } 5.使用边界通配符 //Example 15 class TwoD { int x, y; TwoD(int a, int b) { x = a; y = b; } } // Three-dimensional coordinates. class ThreeD extends TwoD { int z; ThreeD(int a, int b, int c) { super(a, b); z = c; } } // Four-dimensional coordinates. class FourD extends ThreeD { int t; FourD(int a, int b, int c, int d) { super(a, b, c); t = d; } } // This class holds an array of coordinate objects. class Coords{ T[] coords; Coords(T[] o) { coords = o; } } // Demonstrate a bounded wildcard. public class BoundedWildcard { static void showXY(Coords c) { System.out.println("X Y Coordinates:"); for(int i=0; i < c.coords.length; i++) System.out.println(c.coords.x + " " + c.coords.y); System.out.println(); } static void showXYZ(Coords c) { System.out.println("X Y Z Coordinates:"); for(int i=0; i < c.coords.length; i++) System.out.println(c.coords.x + " " + c.coords.y + " " + c.coords.z); System.out.println(); } static void showAll(Coords c) { System.out.println("X Y Z T Coordinates:"); for(int i=0; i < c.coords.length; i++) System.out.println(c.coords.x + " " + c.coords.y + " " + c.coords.z + " " + c.coords.t); System.out.println(); } public static void main(String args[]) { TwoD td[] = { new TwoD(0, 0), new TwoD(7, 9), new TwoD(18, 4), new TwoD(-1, -23) }; Coordstdlocs = new Coords(td); System.out.println("Contents of tdlocs."); showXY(tdlocs); // OK, is a TwoD // showXYZ(tdlocs); // Error, not a ThreeD // showAll(tdlocs); // Erorr, not a FourD // Now, create some FourD objects. FourD fd[] = { new FourD(1, 2, 3, 4), new FourD(6, 8, 14, 8), new FourD(22, 9, 4, 9), new FourD(3, -2, -23, 17) }; Coordsfdlocs = new Coords(fd); System.out.println("Contents of fdlocs."); // These are all OK. showXY(fdlocs); showXYZ(fdlocs); showAll(fdlocs); } } 6.ArrayList的Generics //Example 16 public class ArrayListGenericDemo { public static void main(String[] args) { ArrayListdata = new ArrayList(); data.add("hello"); data.add("goodbye"); // data.add(new Date()); This won't compile! Iteratorit = data.iterator(); while (it.hasNext()) { String s = it.next(); System.out.println(s); } } } 7.HashMap的Generics //Example 17 public class HashDemoGeneric { public static void main(String[] args) { HashMapmap = new HashMap(); map.put(1, "Ian"); map.put(42, "Scott"); map.put(123, "Somebody else"); String name = map.get(42); System.out.println(name); } } 8.接口的Generics //Example 18 interface MinMax>{
T min ()
T max ()
}
/ / Now, implement MinMax
Class MyClass > implements MinMax {
T [] vals
MyClass (T [] o) {vals = o;}
/ / Return the minimum value in vals.
Public T min () {
T v = vals [0]
For (int iTunes 1; I
< vals.length; i++) if(vals.compareTo(v) < 0) v = vals; return v; } // Return the maximum value in vals. public T max() { T v = vals[0]; for(int i=1; i < vals.length; i++) if(vals.compareTo(v) >0) v = vals
Return v
}
}
Public class GenIFDemo {
Public static void main (String args []) {
Integer inums [] = {3,6,2,8,6}
Character chs [] = {'baked,' rusted, 'paired,' w'}
MyClassiob = new MyClass (inums)
MyClasscob = new MyClass (chs)
System.out.println ("Max value in inums:" + iob.max ())
System.out.println ("Min value in inums:" + iob.min ())
System.out.println ("Max value in chs:" + cob.max ())
System.out.println ("Min value in chs:" + cob.min ())
}
}
Generics of 9.Exception
/ / Example 20
Interface Executor {
Void execute () throws E
}
Public class GenericExceptionTest {
Public static void main (String args []) {
Try {
Executore =
New Executor () {
Public void execute () throws IOException
{
/ / code here that may throw an
/ / IOException or a subtype of
/ / IOException
}
}
E.execute ()
} catch (IOException ioe) {
System.out.println ("IOException:" + ioe)
Ioe.printStackTrace ()
}
}
} Thank you for reading! This is the end of this article on "what is Generics in Java". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!
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.