Java provides generics (Java genertics) after JDK5, allowing the use of types as parameters when defining classes. Generics are widely used in various collections. This article describes it and its usage.
1. A common mistake
In the following example, a parameter of type list<object> is used to receive list<string>.
public class Main { public static void main (string[] args) throws IOException {ArrayList <String> al = new Arrayl Ist<string> (); Al.add ( "a" "B" public static void Accept (Arraylist<object> al) { for (Object o:al) System.out.println (o); }}
It seems that object is the parent of string, and there is no problem. However, the compile time is not passed. The error is as follows:
for < String >)
2, list<object> vs list<string>
The reason is that the Java type Erasure mechanism is not compiled by the compiler to compile object and string type information when it is translated into class files. Therefore, in order to prevent errors, the compiler found that they are inconsistent at compile time will be error.
3. Wildcard and unbounded wildcard characters
Unbounded wildcard list<?> can receive any type
Public Static voidMain (String args[]) {ArrayList<Object> Al =NewArraylist<object>(); Al.add ("ABC"); Test (AL); } Public Static voidTest (arraylist<?>al) { for(Object E:al) {//no matter what type, it would be ObjectSystem.out.println (e);//in the This method, because we don't know what type? are, we can not add anything to al. } }
Wildcard characters
list< Object >-List can contain object or it ' s subtypelist<? Extends number >- List can contain number or its subtypes. list<? Super Number >-List can contain number or its supertypes.
Java type erase (Java Erasure mechanism)