在集合中,可以引用任意数据类型。集合会将其强转成Object类,即忽略其数据类型。
泛型则是规定了某个集合只能存取指定数据类型的数据。泛型用于编译时期,确保类型的安全。运行时会将泛型去掉,生成的class文件中不包含泛型,这就是泛型的擦除。
在程序中,只要用到了带<>的类或者接口,就要明确传入的具体数据类型。
此外,泛型中不能使用基本数据类型,要将其转化为包装类。如(int转化为Integer,long转化为Long,boolean转化为Boolean)。
1.泛型类
先自定义工具类Tool
public class Tool<Tl> {
private Tl t;
public Tl getT() {
return t;
}
public void setT(Tl t) {
this.t = t;
}
在使用Student数据类型时,要先声明。当数据类型不匹配时,编译失败。
public class GenericDemo1 {
public static void main(String[] args) {
Tool<Student> tool = new Tool<Student>();
tool.setT(new Student("jiaody",22));
Student stu = tool.getT();
System.out.println(stu.toString());
}
}
2.泛型方法
在Tool工具类中添加一个非静态泛型方法show:
public <W> void show(W w)
{
System.out.println("show..."+w.toString());
}
在主函数中可直接调用W类型的数据。
但是,当方法静态时,不能访问类上定义的泛型。此时必须将泛型定义在方法上。
注释:将泛型定义于返回值(void)前,修饰符(static)后。
以下代码为在Tool中添加静态泛型方法method:
public static <Y> void method(Y y)
{
System.out.println("method:"+y);
}
在主函数中直接可调用Y类型的数据:
如Tool.method("jiaody");
3.泛型接口
顾名思义,将泛型定义在接口上。
4.泛型通配符
? extends E:限定接收类型。只能接收E及其子类。(上限)
? super E: 只能接收E及其父类(下限)。
public class GenericDemo2 {
public static void main(String[] args) {
ArrayList<String> al1 = new ArrayList<String>();
al1.add("a");
al1.add("b");
printColl(al1);
ArrayList<Integer> al2 = new ArrayList<Integer>();
al2.add(12);
al2.add(23);
printColl(al2);
}
public static void printColl(ArrayList<?> al1) {
Iterator it = al1.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
}
}
在打印时将数据类型置为?,可接受任意数据类型。
若想添加自定义数据类型,在打印时设置为 ? extends 父类
public class GenericDemo2 {
public static void main(String[] args) {
ArrayList<Student> al1 = new ArrayList<Student>();
al1.add(new Student("jiaody",22));
al1.add(new Student("jack",21));
printColl(al1);
ArrayList<Worker> al2 = new ArrayList<Worker>();
al2.add(new Worker("joe",20));
al2.add(new Worker("john",111));
printColl(al2);
}
public static void printColl(ArrayList<? extends Person> al1) {
Iterator<? extends Person> it = al1.iterator();
while(it.hasNext())
{
Person p = it.next();
System.out.println(p.getName()+","+p.getAge());
}
}
}
其中,Student和Worker是Person的子类。