01 自定义泛型类
定义一个含有泛型的类,模拟ArrayList集合
-
泛型是一个未知的数据类型,我们不确定什么数据类型的时候,可以使用泛型
-
泛型可以接收任意的数据类型,可以使用Integer,String,Student…
-
创建对象的时候确定泛型的数据类型
代码如下:
package com.Generic;
/*
定义一个含有泛型的类,模拟ArrayList集合
泛型是一个未知的数据类型,我们不确定什么数据类型的时候,可以使用泛型
泛型可以接收任意的数据类型,可以使用Integer,String,Student...
创建对象的时候确定泛型的数据类型
*/
public class GenericClass<E> {
private E name;
public E getName() {
return name;
}
public void setName(E name) {
this.name = name;
}
}
使用含有泛型的类
package com.Generic;
public class Demo02GenericClass {
public static void main(String[] args) {
//不写泛型默认为Object类型
GenericClass gc = new GenericClass();
gc.setName("只能是字符串");
Object obj = gc.getName();
//创建GenericClass对象,泛型使用Integer类型
GenericClass<Integer> gc2 = new GenericClass<>();
gc2.setName(2);
Integer name = gc2.getName();
System.out.println(name); //2
//创建GenericClass对象,泛型使用String类型
GenericClass<String> gc3 = new GenericClass<>();
gc3.setName("老王");
String name1 = gc3.getName();
System.out.println(name1);//老王
}
}
02 自定义含有泛型的方法
定义含有泛型的方法:泛型定义再方法的修饰符和返回值类型之间
格式:
修饰符 <泛型> 返回值类型 方法名(参数列表(使用泛型)){
方法体
}
含有泛型的方法,在调用方法的时候确定泛型的数据类型
传递什么类型的参数,泛型就是什么类型
package com.Generic;
/*
定义含有泛型的方法:泛型定义再方法的修饰符和返回值类型之间
格式:
修饰符 <泛型> 返回值类型 方法名(参数列表(使用泛型)){
方法体
}
含有泛型的方法,在调用方法的时候确定泛型的数据类型
传递什么类型的参数,泛型就是什么类型
*/
public class GenericMethod {
//定义一个含有泛型的方法
public <M> void method01(M m){
System.out.println(m);
}
//定义含有泛型的静态方法
public static <S> void method02(S s){
System.out.println(s);
}
}
测试含有泛型的方法
package com.Generic;
/*
测试含有泛型的方法
*/
public class Demo03GenericMethod {
public static void main(String[] args) {
//创建GenericMethod对象
GenericMethod gm = new GenericMethod();
/*
调用含有泛型的方法method01()
传递什么类型,泛型就是什么类型
*/
gm.method01("dfg");
gm.method01(223);
gm.method01(5.20);
gm.method01(true);
gm.method02("静态方法,不建议创建对象使用");
//静态方法,通过类名.方法名(参数)可以直接使用
GenericMethod.method02("静态方法");
GenericMethod.method02(223);
}
}