2017-10-30 22:47:11
Java 泛型(generics)是 JDK 5 中引入的一个新特性, 泛型提供了编译时类型安全检测机制,该机制允许程序员在编译时检测到非法的类型。
泛型的本质是参数化类型,也就是说所操作的数据类型被指定为一个参数。
泛型是一种把类型的明确工作推迟到创建对象或者调用方法的时候才去明确的特殊类型。
注意:类型参数只能代表引用型类型,不能是原始类型(像int,double,char的等)。
泛型出现的原因
早期的时候,使用Object来代表任意类型。但是这样在向上转型的是没有问题的,但是在向下转型的时候存在类型转换的问题,这样的程序其实是不安全的。所以Java在JDK5之后提供了泛型来解决这个问题。
泛型应用
~ 泛型类
格式:public class 类名{}
public class ObjectTool
{
private T obj;
public void setObj(T obj) {
this.obj = obj;
}
public T getObj() {
return obj;
}
}
public static void main(String[] args) {
ObjectTool obj = new ObjectTool<>();
obj.setObj("Hello World.");
System.out.println(obj.getObj());
}
~ 泛型方法
格式:public 返回值 方法名(T a){}
public void show(E s)
{
System.out.println(s);
}
public static void main(String[] args) {
ObjectTool obj = new ObjectTool<>();
obj.show("Hello world.");
obj.show(120);
}
~ 泛型接口
格式:public interface 接口名{}
public interface Inter {
public void show(T s);
}
/**
* 有两种情况
* 一是实现类中已经知道了具体类型(不常见)
* 一是实现类中不知道具体的实现类型,这时候需要在实现类后也跟上泛型
* @param
*/
//public class InterImpl implements Inter {
//
// @Override
// public void show(T s) {
// System.out.println(s);
// }
//}
public class InterImpl implements Inter {
@Override
public void show(String s) {
System.out.println(s);
}
}
public static void main(String[] args) {
//第一种情况,不知道类型,所以在实现类后也要跟上泛型
//Inter inter=new InterImpl<>();
//inter.show("Hello world.");
//第二种情况,实现类已经知道了具体类型,此时实现类中就不需要添加泛型了
Inter inter = new InterImpl();
inter.show("Hello world.");
}
泛型通配符
>:类型通配符一般是使用?代替具体的类型参数。例如 List> 在逻辑上是List,List 等所有List的父类。
//泛型如果明确的写的时候,前后类型必须一致
Collection c1 = new ArrayList();
Collection c2 = new ArrayList(); //报错
Collection c3 = new ArrayList(); //报错
//?表示任意类型都是可以的
Collection c4 = new ArrayList();
Collection c5 = new ArrayList();
Collection c6 = new ArrayList();
extends E>:向下限定,只能是E及其子类
Collection extends Animal> c1 = new ArrayList(); //报错
Collection extends Animal> c2 = new ArrayList();
Collection extends Animal> c3 = new ArrayList();
Collection extends Animal> c4 = new ArrayList();
super E>:向上限定,只能是E及其父类
Collection super Animal> c1 = new ArrayList();
Collection super Animal> c2 = new ArrayList();
Collection super Animal> c3 = new ArrayList(); //报错
Collection super Animal> c4 = new ArrayList(); //报错