一、自定义泛型
类的声明处增加泛型列表,如:<T,E,V>。此处,字符可以是任何标识符,一般采用这3个字母
- 泛型类的声明
泛型E像一个占位符一样表示“未知的某个数据类型”,我们在真正调用的时候传入这个“数据类型”
class MyCollection<E> {// <E>表示泛型;
Object[] objs = new Object[5];
public E get(int index) {// E:表示泛型;
return (E) objs[index];
}
public void set(E e, int index) {// E:表示泛型;
objs[index] = e;
}
}
- 泛型类的应用
MyCollection<String> mc = new MyCollection<String>();
mc.set("aaa", 0);
mc.set("bbb", 1); //e为"bbb",赋值给下标1
String str = mc.get(1); //加了泛型,直接返回String类型,不用强制转换;
//获取数值,将其赋值给str
System.out.println(str);
二、泛型类在集合中使用
通过阅读源码(Ctrl+鼠标点击List、Set等),Collection、List、Set、Map、Iterator接口都定义了泛型
List<String> list = new ArrayList<String>();
Set<Byte> mans = new HashSet<Byte>();
Map<Integer, String> maps = new HashMap<Integer,String>();