1 泛型类型省略
ArrayList<String> files = new ArrayList<>();
2 泛型类定义
public class Pair<T> {...}
3 泛型方法定义
public <T> T get(T... a) {...}
4 泛型参数约束
<T extends Comparable&Serializable> //多个约束
<T super Parent>
- 不能使用基本类型作为类型参数
- 不能创建参数化数组,如
Pair<String>[] table = new Pair<String>[10]
- 类型变量不能实例化
- 泛型类中不能包含静态类型变量
5 类型擦除
- java中的泛型是伪泛型,会进行类型擦除,与C#中不同
- 桥方法用来合成来保持多态
6 赋值
Pair<Parent> p = new Pair<Child>(); //不合法
Parent[] p = new Child[10]; //合法
7 通配符类型
<? extends Parent>
<? super Child>
一段示例代码说明通配符限定问题:
package com.rayspy.java;
import java.util.ArrayList;
import java.util.List;
/**
* Created by jingang on 2017/05/27.
*/
public class ExtendSuperTest {
public static void run()
{
}
public static class Parent{}
public static class ChildA extends Parent{}
public static class ChildB extends Parent{}
private static void test1()
{
/*
* la中的每一个元素一定是Parent的子类,但具体是那一个子类对象无法确定
* Error:向其添加一个子类元素
* Right:获取其中的元素,获取的元素一定可以赋值给Parent
* */
List<? extends Parent> la = new ArrayList<ChildA>(){{add(new ChildA());}};
Parent first = la.get(0);
/*
* lb中的元素一定是ChildA本身或其父类
* Error: 一个类的父类可能有多个,因此无法添加某个特定的父类对象
* Right: 向lb中添加ChildA对象或其子类对象, 这是因为对于lb的每一个元素,一定可以安全的引用子类对象
* */
List<? super Parent> lb = new ArrayList<Parent>(){{add(new Parent());}};
lb.add(new ChildA());
lb.add(new ChildB());
}
private static void test2(List<? extends Parent> la)
{
for (Parent a: la)
{
//do something
}
}
private static void test3(List<? super Parent> lb)
{
List<Parent> lc = new ArrayList<>();
for (Parent c :lc)
{
lb.add(c);
}
}
}