Reason for introduction:
/*
* ArrayList store strings and traverse
*
* We write this procedure in the normal way, and the result is wrong.
* For what?
* As we start to store, we store a string and an integer of two types of data.
* While traversing, we treat them as string types, and do the conversion, so we get an error.
* But it didn't tell us during the compilation.
* So, I think this design is not good.
* Recall that our array
* string[] Strarray = new String[3];
* Strarray[0] = "Hello";
* Strarray[1] = "World";
* Strarray[2] = 10;
* Collections also mimic the practice of arrays, defining the data type of an element when creating an object. So that's not going to be a problem.
* And this technique is called: generics.
*
* Generics: It is a special type of explicit type that is deferred until the object is created or the method is called. A parameterized type that passes a type as a parameter.
Format
* < data type >
* The data Type here can only be a reference type.
Benefits
* A: Advance the run-time issue to the compile period
* B: Forced type conversions are avoided
* C: Optimized the program design, solved the yellow warning line
*/
public class Genericdemo {
public static void Main (string[] args) {
Create
arraylist<string> array = new arraylist<string> ();
adding elements
Array.add ("Hello");
Array.add ("World");
Array.add ("Java");
//Array.add (new Integer);
//array.add (Ten);//JDK5 after the automatic boxing, so write will not error, because generics are not written on, there is no restriction on the type of collection. Write directly 10, will not be the cause of the error, is automatic boxing, can be compiled by anti-compilation query source code: integer.valueof (ten);
Equivalent to: Array.add (integer.valueof (10));
Traverse
Iterator<string> it = Array.iterator ();
while (It.hasnext ()) {
ClassCastException
//String s = (string) it.next (); //Mark Red Place, will be abnormal, because the collection has an integer and stirng two types of reference, while traversing, just stirng, so to traverse the integer will be error
String s = it.next ();
System.out.println (s);
}
Look at the code below.
string[] Strarray = new String[3];
Strarray[0] = "Hello";
STRARRAY[1] = "World";
STRARRAY[2] = 10;
}
}
Introduction and case of generics