Java 泛型
棱形语法
List<String> list = new ArrayList<>();
Map<String, List<String>> map = new HashMap<>();
泛型接口、类
// 定义接口是指定泛型形参,命名为E
public interface List<E> extends Collection<E> {
// E作为参数类型使用
boolean add(E e);
Iterator<E> iterator();
// 作为返回类型
E get(int index);
}
public interface Map<K,V> {
V get(Object key);
V put(K key, V value);
Set<K> keySet();
}
类型通配符
public void test(List<?> c){
for (int i = 0; i < c.size(); i ++){
System.out.println(c.get(i));
}
}
这种带通配符的List仅表示它是各种泛型List的父类,并不能把元素加入到其中
设定通配符的上限
public void test(List<? extend Object> c){
// dosth
}
// 多个上限
public class Apple<T extend Number & java.io.Serializable>{
// dosth
}
设定通配符下限
public static <T> T test(Collection<? super T> c){
// dosth
}
即必须为T类型的父类
泛型方法
修饰符 <T,S> 返回值类型 方法名(形参列表){
// 方法体
}
static <T> void from(T[] a, Collection<T> c){
}
泛型构造器
class Foo{
public <T> Foo(T t){
System.out.println(t);
}
}
public class Test{
public static void main(String[] args){
new Foo("A");
// 显式指定T类型
new <String> Foo("B");
}
}
Java9增强棱形语法
参考《疯狂Java讲义》9.1.3