定义一个含有泛型的类,模拟ArrayList集合
泛型是一个未知的数据类型,当我们不确定使用什么类型的时候,可以使用泛型
泛型可以接收任意的数据类型,可以使用Integer,String,Student...
创建对象的时候确定泛型的数据类型
注意:不写泛型默认为Object类型
例如:
public class GenericClass<E>{
private E name;
//自动生成Getter/Setter
public E getName(){return name;}
public void setName(E name){
this.name = name;}}
main方法:
// 创建GenericClass对象,泛型使用Integer类型
GenericClass<Integer> gc2 = new GenericClass<>();
gc2.setName(1);
含有泛型的方法
定义含有泛型的方法:泛型定义在方法的修饰符和返回值类型之间
格式:
修饰符 <泛型> 返回值类型 方法名(参数列表(使用泛型)){
方法体;}
含有泛型的方法,在调用方法的时候确定泛型的数据类型
传递什么类型的参数,泛型就是什么类型
例如:
public class GenericMethod {
//定义一个含有泛型的方法
public <M> void method01(M m){
System.out.println(m);}
//定义一个含有泛型的静态方法
public static <S> void method02(S s){
System.out.println(s);}}
main方法:
GenericMethod gm = new GenericMethod();
gm.method01(10);
gm.method01("abc");
// 调用含有泛型的方法method01 传递什么类型,泛型就是什么类型
// 静态方法,通过类名.方法名(参数)可以直接使用
GenericMethod.method02("静态方法")
注意:静态方法,不建议创建对象使用
含有泛型的接口
定义含有泛型的接口
public interface GenericInterface<I>{
public abstract void method(I i);}
含有泛型的接口,第一种使用方式:定义接口的实现类,实现接口,指定接口的泛型
public class GenericInterfaceImpl1 implements GenericInterface<String>{
@Override
public void method(String s){
System.out.println(s);}}
测试含有泛型的接口
GenericInterfaceImpl1 gi1 = new GenericInterfaceImpl1();
gi1.method("字符串");
含有泛型的接口第二种使用方式:接口使用什么泛型,实现类就使用什么泛型,类跟着接口走
就相当于定义了一个含有泛型的类,创建对象的时候确定泛型的类型
public class GenericInterfaceImpl2<I> implements GenericInterface<I>{
@Override
public void method(I i){
System.out.println(i);}}
测试含有泛型的接口
GenericInterfaceImpl2<Integer> gi2 = new GenericInterfaceImpl2<>();
gi2.method(10);
泛型通配符?
泛型的通配符:
?:代表任意的数据类型
使用方式:
不能创建对象使用 // ArrayList<?> list01 = new ArrayList<?>(); // 错误写法
只能作为方法的参数使用 public static void printArray(ArrayList<?> list){}
泛型的上下限限定
泛型的上限限定:? extends E 代表使用的泛型只能是E类型的子类/本身
泛型的下限限定:? super E 代表使用的泛型只能是E类型的父类/本身
类与类之间的继承关系
Integer extends Number extends Object
String extends Object
例如:
main方法:
Collection<Integer> list1 = new ArrayList<Integer>();
Collection<String> list2 = new ArrayList<String>();
Collection<Number> list3 = new ArrayList<Number>();
Collection<Object> list4 = new ArrayList<Object>();
getElement1(list1);
// getElement1(list2);//报错
getElement1(list3);
// getElement1(list4);//报错
//泛型的上限:此时的泛型?,必须是Number类型或者Number类型的子类
private static void getElement1(Collection<? extends Number> coll){}
含有泛型的类定义一个含有泛型的类,模拟ArrayList集合泛型是一个未知的数据类型,当我们不确定使用什么类型的时候,可以使用泛型泛型可以接收任意的数据类型,可以使用Integer,String,Student...创建对象的时候确定泛型的数据类型注意:不写泛型默认为Object类型例如:public class GenericClass<E> { private E name; //自动生成Getter/Setter public E