The example in this article summarizes the usage of generics in Java. Share to everyone for your reference. Specifically as follows:
1 Basic use
Public interface List<e> {
void Add (E);
Iterator<e> iterator ();
}
2 Generics and subclasses
The child is a subclass of Parent,list<child> but not a list<parent> subclass.
therefore:list<object> List = new arraylist<string> () is wrong.
If the above is correct, then:
list<string> ls = new arraylist<string> (); 1
list<object> lo = ls;//2
lo.add (New Object ());//3
String s = ls.get (0);//4, converting Object to String will fail.
3 wildcards
Because of the 2 reason, the following implementations are not available for the output of the wildcard collection.
void Printcollection (collection<object> c) {for
(Object o:c) {
//do Something
}
}
Therefore, wildcard characters are required:
void Printcollection (collection<?> c) {for
(Object o:c) {//1
/do Something
}
}//OK
The type is unknown, but any objects are object, so 1 of the example above is correct. But the following example is wrong:
void Add (collection<. extends myclass> c) {
C.add (new MyClass ());//Wrong
}//OK
The reason is clear, too? Extends MyClass description type is a subclass of MyClass, but does not know the specific type
4. Generic method
The example above can be implemented as:
<T> Add (collection<t> C, T t) {
c.add (t);
}
The compiler will help with the conversion of the type in the premise of guaranteeing semantics.
5. Comparison of generic run-time
list<string> L1 = new arraylist<string> ();
list<integer> L2 = new arraylist<integer> ();
System.out.println (l1.getclass () = = L2.getclass ()); True
Because the generic class runs as always.
6 generic Array (may cause type insecurity)
Copy Code code as follows:
list<string>[] LSA = new arraylist<string>[10]; Error
If you can, it may cause type insecurity. Such as:
Object o = LSA;
Object []oa = (object[]) o;
list<integer> li = new arraylist<integer> ();
Li.add (New Integer (3));
Oa[1] = li;
String s = lsa[1].get (0); Runtime error
I hope this article will help you with your Java programming.