创建集合对象,使用泛型,如果不使用泛型,就会有出现多态的弊端(无法使用子类特有的方法),除非进行向下转型。
#使用泛型的优点:
1.避免了类型转换的麻烦,存储的是什么类型,取出的就是什么类型
2.把运行期异常(代码运行之后会抛出的异常),提升到了编译期(写代码的时候会报错)
定义含有泛型的类:
1.定义一个含有泛型的类,模拟ArrayList集合
2.泛型是一个未知的数据类型,当我们不确定什么数据类型的时候,可以使用泛型
3. 泛型可以接收任意的数据类型,可以使用Integer,String,Student…
4. 创建对象的时候确定泛型的数据类型
public class GenericClass<E> {
private E name;
public E getName() {
return name;
}
public void setName(E name) {
this.name = name;
}
}
//不写泛型默认为Object类型
GenericClass gc = new GenericClass();
gc.setName("只能是字符串");
//创建GenericClass对象,泛型使用Integer类型
GenericClass<Integer> gc2 = new GenericClass<>();
gc2.setName(1);
//创建GenericClass对象,泛型使用String类型
GenericClass<String> gc3 = new GenericClass<>();
gc3.setName("小明");
定义含有泛型的方法:
含有泛型的方法,在调用方法的时候确定泛型的数据类型,即传递什么类型的参数,泛型就是什么类型
public class GenericMethod {
//定义一个含有泛型的方法
public <M> void method01(M m){
System.out.println(m);
}
//定义一个含有泛型的静态方法
public static <S> void method02(S s){
System.out.println(s);
}
}
//创建GenericMethod对象
GenericMethod gm = new GenericMethod();
gm.method01(10);
gm.method01("abc");
//静态方法
GenericMethod.method02("静态方法");
GenericMethod.method02(1);
定义含有泛型的接口:
public interface GenericInterface<I> {
public abstract void method(I i);
}
使用带泛型的接口有两种方式:
1.定义接口的实现类,实现接口,并指定接口的泛型
public class GenericInterfaceImpl1 implements GenericInterface<String>{
@Override
public void method(String s) {
System.out.println(s);
}
}
2.接口使用什么泛型,实现类就使用什么泛型,类跟着接口走。就相当于定义了一个含有泛型的类,创建对象的时候确定泛型的类型(第二种方式更加灵活)
public class GenericInterfaceImpl2<I> implements GenericInterface<I> {
@Override
public void method(I i) {
System.out.println(i);
}
}
带泛型接口实现类的使用:对第一种因为定义时已经确定泛型类型了,所以在new对象时无须指定泛型类型。而第二种在创建对象时需要指定泛型类型。
//创建GenericInterfaceImpl1对象
GenericInterfaceImpl1 gi1 = new GenericInterfaceImpl1();
gi1.method("字符串");
//创建GenericInterfaceImpl2对象
GenericInterfaceImpl2<Integer> gi2 = new GenericInterfaceImpl2<>();
gi2.method(10);
GenericInterfaceImpl2<Double> gi3 = new GenericInterfaceImpl2<>();
gi3.method(8.8);
泛型通配符:
泛型的通配符: ? 代表任意的数据类型
使用方式:
1.不能创建对象使用
2.只能作为方法的参数使用,作为方法的传参的接收
注意:泛型没有多态的概念,所以不能指定泛型为object类型来接收所有类型
举例:有两个ArrayList集合,泛型分别指定为Interger和String,现在要求写一个方法来遍历这两个集合,方法的参数是一个ArrayList。当我们不知道ArrayList集合使用什么数据类型来遍历两个,可以泛型的通配符?来接收数据类型。
泛型通配符限定:
同样只能在作为接收参数时使用
1.泛型的上限限定: ? extends E 代表使用的泛型只能是E类型的子类/本身
2.泛型的下限限定: ? super E 代表使用的泛型只能是E类型的父类/本身