Java generic
The generic mechanism is a feature introduced by 1.5 and is essentially a parameterized type. In the definition of classes, interfaces, and methods, the Data Type of the operation is specified by the input parameter.
Can be used in the class, can be used in the method, can be used in the Set ......
1. Application of generics in collections
Java generic mechanism is widely used in the collection framework. All set types have parameters, so that the object type can be specified when a set is created.
// List list = new ArrayList (); // you can specify any type.
List <String> list = new ArrayList <String> ();
// Now, only strings can be specified. You do not need to create a shape when obtaining the image.
List. add ("s ");
For (int I = 0; I <list. size (); I ++ ){
String str = list. get (I); // No styling is required because it is not an Object
System. out. println (str );
}
/*
* If an iterator is used, we also need generics.
*/
Iterator <String> it = list. iterator ();
While (it. hasNext ()){
String string = it. next ();
}
// Or
For (Iterator <String> ite = list. iterator (); ite. hasNext ();){
String string = ite. next ();
}
1) The generic type is defined after the class name;
2) The wildcard can be a combination of letters and numbers, but the first character must be a letter;
3) Separate multiple generics with commas;
4) generics can constrain attributes, method parameters, and return types of methods.
Class Point <E> {
Private E x;
Private E y;
Public Point (E x, E y ){
This. x = x;
This. y = y;
}
Public E getX (){
Return x;
}
Public void setX (E x ){
This. x = x;
}
}
// Point p = new Point (1, 2 );
// System. out. println (p );
// Specify the exact type when using it.
Point <Double> p = new Point <Double> (1.2, 20.2 );
System. out. println (p );
// You can specify more than one type as follows:
Class Point1 <E, Y> {
Private E x;
Private Y y;
Public Point1 (E x, Y y Y ){
This. x = x;
This. y = y;
}
}
When using a class that supports generics, if we do not specify the generic type, the generic type specifies the Object by default.
This article from the "beautiful life needs to carefully record" blog, please be sure to keep this http://huing.blog.51cto.com/1669631/1295004