A summary of the usage of generics in Java
- 2020-04-01 03:55:40
- OfStack
This example summarizes the use of generics in Java. Share with you for your reference. The details are as follows:
1 basic use
public interface List<E> {
void add(E);
Iterator<E> iterator();
}
Generics and subclasses
Child is a Child of Parent, List< Child> But not List< Parent> The 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 That will be object convert string Will fail.
3 wildcards
For 2 reasons, the following implementation does not work for coordinating the output of the set
void printCollection(Collection<Object> c) {
for (Object o: c) {
// do something
}
}
Therefore, you need the wildcard ? :
void printCollection(Collection<?> c) {
for (Object o: c) { // 1
// do something
}
} // ok
Here the & # 63; The type is unknown, but any Object is an Object, so the 1 in the above example is correct. But the following example is wrong:
void add(Collection<? extends MyClass> c) {
c.add(new MyClass()); // wrong
} // ok
The reason is also clear, ? Extends MyClass indicates that the type is a subclass of MyClass, but the type is not known
4. Generic methods
The above example can be implemented as:
<T> add(Collection<T> c, T t) {
c.add(t);
}
The compiler will help with the translation of the type without compromising the semantics.
5. Generic runtime comparison
List<String> l1 = new ArrayList<String>();
List<Integer> l2 = new ArrayList<Integer>();
System.out.println(l1.getClass() == l2.getClass()); // true
Because generic classes always run the same.
6 generic array (may cause type insecurity)
List<String>[] lsa = new ArrayList<String>[10]; // error
If possible, this can lead to 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 has been helpful to your Java programming.