一、泛型概述:
1.来源:1.5jdk出现的新特性;用于解决安全问题,是一个安全机制;
//下面代码,编译不报错,运行报错,加上泛型给与集合类型限定;
2.好处:减少运行时的问题,在编译时体现;避免强制转换的麻烦;
3.关键字:
public classTest {public static voidmain(String[] args) {
ArrayList arrayList= newArrayList();
arrayList.add("1");
arrayList.add(1);for (Iterator iterator =arrayList.iterator(); iterator.hasNext(); ) {
String next=(String) iterator.next();
}
}
}
二、泛型用法:
1)泛型类:class类名
class Base{privateT t;publicT getT() {returnt;
}public voidsetT(T t) {this.t =t;
}
}public classTest {public static voidmain(String[] args) {
Base s = new Base();
s.setT("s");
System.out.println(s.getT());
}
}
2)泛型方法:修饰符 返回值类型 方法名(T t){};
classDemo {public voidshow(T t){
System.out.println(t);
}
}public classTest {public static voidmain(String[] args) {
Demo demo= newDemo();
demo.show("string");
demo.show(123);
}
}
3)静态泛型方法:
//普通方法可以访问类上定义的泛型,但是静态方法不行,静态方法只能自己定义;
//格式;修饰符 static 返回值类型 方法名(T t){}; 千万不能放在static前头;
4)泛型接口:interface 接口名
interface Inter{voidshow(T t);
}class InterImpl implements Inter{
@Overridepublic voidshow(String s) {
System.out.println(s);
}
}public classTest {public static voidmain(String[] args) {
InterImpl inter= newInterImpl();
inter.show("s");
}
}
三、泛型限定:
1、通配符:?;也可以理解为占位符;
2、用法:
1)?extends E:上限;可以接收E类型或者E的子类型;
2)?super E:下限;可以接收E类型或者E的父类型;
三、示例:
import java.util.*;
class Person{
private String name;
public Person(String name) {this.name = name;}
public String getName() { return name;}
}
class Student extends Person{
public Student(String name) {super(name); }
}
public class Test {
public static void main(String[] args) {
ArrayList al1=new ArrayList();
al1.add(new Person("张三"));
al1.add(new Person("李四"));
al1.add(new Person("王五"));
ArrayList al2=new ArrayList();
al2.add(new Student("刘一"));
al2.add(new Student("刘二"));
al2.add(new Student("刘三"));
printAll(al1);
printAll(al2);
}
public static void printAll(ArrayList extends Person> al){
Iterator extends Person> it=al.iterator();
while (it.hasNext()){
System.out.println(it.next().getName());
}}}