1. Introduction of generics:
(1) First, let's take a look at the following code, as follows:
1 Packagecn.itcast_01;2 3 Importjava.util.ArrayList;4 ImportJava.util.Iterator;5 6 7 Public classGenericdemo {8 Public Static voidMain (string[] args) {9 //CreateTenarraylist<string> array =NewArraylist<string>(); One A //adding elements -Array.add ("Hello"); -Array.add ("World"); theArray.add ("Java"); - //Array.add (new Integer); -Array.add (10);//Auto-boxing after JDK5 - //equivalent to: Array.add (integer.valueof (Ten)); + - //Traverse +Iterator<string> it =array.iterator (); A while(It.hasnext ()) { at //classcastexception - //string s = (string) it.next (); -String s =It.next (); - System.out.println (s); - } - in } -}
Run the above program as follows:
(2) Introduction of generics:
We wrote the procedure in the normal way, and the result was wrong.
for what ?
Because when we started to store it, we stored string and integer two types of data.
And in the traversal, we treat them as a string type, do the conversion, so the error.
However, it did not tell us during the compilation .
So, I think this design is not good.
Recall that our array:
1 New String[3]; 2 Strarray[0] = "Hello"; 3 STRARRAY[1] = "World"; 4 STRARRAY[2] = 10; Error
Collections also mimic the practice of arrays, which specify the data type of an element when creating an object. This is not going to be a problem, and This technique is known as: Generics .
2. Overview and use of generics:
(1) Overview of generics:
Generics are a special type of explicit work that is deferred until the object is created or when the method is called. A parameterized type that passes a type as a parameter.
(2) The format of the generic type:
< data types >
Note: The data type here can only be a reference type .
(3) Benefits of generics:
• Advance the run-time issue to the compile time
• Forced type conversions are avoided
• Optimized program design to solve the yellow warning line
3. Use generics to improve the code of 1, as follows:
1 Packagecn.itcast_01;2 3 Importjava.util.ArrayList;4 ImportJava.util.Iterator;5 6 7 Public classGenericdemo {8 Public Static voidMain (string[] args) {9 //CreateTenarraylist<String> array =Newarraylist<String>(); One A //adding elements -Array.add ("Hello"); -Array.add ("World"); theArray.add ("Java"); - //Array.add (new Integer); - //Array.add (ten);//Auto-boxing after JDK5 - //equivalent to: Array.add (integer.valueof (Ten)); + - //Traverse +iterator<String> it =array.iterator (); A while(It.hasnext ()) { at //classcastexception - //string s = (string) it.next (); -String s =It.next (); - System.out.println (s); - } - in } -}
The results are as follows:
A collection framework for the reinforcement of Java Fundamentals Note 30: Generic Overview and basic use of collections