Generic and inner classes
- Non-static inner classes automatically inherit the enclosing class generic parameters for non-static inner classes, without having to declare generic parameters again
- Static inner classes do not automatically inherit the enclosing class generic parameter (in fact, Node
The generic parameter 与MyLinkedList Medium manner There is no link, but here the same symbol T only) - Generic parameter declaration of a generic class dominated, such as the parameters for a generic class declaration
, The generic parameters should also be generic interface ; - When the parameter is a generic class declaration
When the parameters generic interface You can not write;
/**
* 泛型类声明的泛型参数占主导地位,如泛型类声明的参数为<T>,则泛型接口的泛型参数也应为<T>;
* 当泛型类声明的参数为<T>时,泛型接口的参数<T>可以不写;
* @param <T>
*/
public class LinkedList<T> implements Iterable {
@Override
public Iterator iterator() {
return null;
}
@Override
public void forEach(Consumer action) {
}
@Override
public Spliterator spliterator() {
return null;
}
}
Generic method
public class GenericMethods{
public <T> void f(T x) {
System.out.println(x.getClass().getName());
}
}
Generic erased
In the generic internal code, you can not get any information off generic parameter type
ListAnd List In fact, running the same type are List Generic type parameter to erase its first boundary
The reason for using erasure to implement generic, for migration compatibility
Generic border
- Generic extends to the upper limit has been restricted namely T must be Comparable <? super T> subclass, then <? super T> represents Comparable <> type in the lower limit for the T!
Create an object or a generic type of data
- new T () can not be achieved in java, by passing a factory object to create a new instance, or their own display factory
class ClassAsFactory<T>{
T x;
public ClassAsFactory(Class<T> kind){
try {
x = kind.newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
- Generic array creation, nor can use Object [] a strong turn as type erasure to the first border, the border is not necessarily the object
public class ZwbHeap<T extends Comparable<? super T>> {
private T[] nodes;
private int size;
private int capacity = 16;
public ZwbHeap() {
// 这样转换会失败
//nodes = (T[])new Object[capacity+1];
// 必须这样写
nodes = (T[])new Comparable[capacity+1];
}
}