概述
(1) 是一种把类型明确的工作提前到创建对象或者调用方法的时候就去明确的一种数据类型。
(2) 参数化类型,把类型作为参数一样传递。
(3) 格式:<数据类型>,数据类型只能是引用类型
(4) 好处:
- 把运行期异常提前到了编译期
- 避免了类型转换
- 减少部分警告
(5) 泛型是jdk1.5 之后才有的
泛型的应用
(1) 看API,如果发现类,接口,方法上有类似,这样的内容,就表示可以使用泛型,一般来说用的最多的地方是集合。
(2) 泛型类
格式:public class 类名<泛型类型,…>{}
public class ObjectTools<T> {
private T obj;
public T getT() {
return obj;
}
public void setT(T obj) {
this.obj = obj;
}
public static void main(String[] args) {
ObjectTools<String> tools = new ObjectTools<>();
tools.setT("111");
String t = tools.getT();
}
}
(3) 泛型方法
格式:public<泛型类型> 返回值类型 方法名(泛型类型,…){}
(4) 泛型接口
格式:public interface 接口名<泛型类型,…>{}
//实现的时候知道是什么类型
public class InterImp1 implements Inter<String>{
@Override
public void show(String s) {
System.out.println(s);
}
}
//实现的时候依然不知道类型
public class InterImp2<T> implements Inter<T>{
@Override
public void show(T t) {
System.out.println(t);
}
}
泛型高级通配符
(1) 泛型通配符 <?>
任意类型,如果没有明确,那么就是Object和子类
(2) <? extends E>
向下限定,E以及E的子类都可以
(3) <? super E>
向上限定,E以及E的父类都可以
public class demo{
//泛型类型如果是明确的,前后必须一致
//Collection<Object> c1 = new ArrayList<Object>();
/* Collection<Object> c2 = new ArrayList<Animal>();
Collection<Object> c3 = new ArrayList<Cat>();
Collection<Object> c4 = new ArrayList<Dog>();*/
/* Collection<?> c1 = new ArrayList<Object>();
Collection<?> c2 = new ArrayList<Animal>();
Collection<?> c3 = new ArrayList<Cat>();
Collection<?> c4 = new ArrayList<Dog>();*/
/* Collection<? extends Animal> c1 = new ArrayList<Object>();
Collection<? extends Animal> c2 = new ArrayList<Animal>();
Collection<? extends Animal> c3 = new ArrayList<Cat>();
Collection<? extends Animal> c4 = new ArrayList<Dog>();*/
/* Collection<? super Animal> c1 = new ArrayList<Object>();
Collection<? super Animal> c2 = new ArrayList<Animal>();
Collection<? super Animal> c3 = new ArrayList<Cat>();
Collection<? super Animal> c4 = new ArrayList<Dog>();*/
}