泛型

    技术2023-08-30  116

    泛型

    定义和使用含有泛型的类定义和使用一个不使用泛型的类定义和使用一个含有泛型的类 定义和使用含有泛型的方法定义和使用含有泛型的接口

    定义和使用含有泛型的类

    1.定义一个含有泛型的类,模拟Arraylist集合。 2.泛型可以是一个未知的数据类型,当我们不确定什么数据类型的时候,可以使用泛型。 3.泛型可以接收任意的数据类型,可以使用String、Integer、Student… 4.创建对象的时候确定泛型的数据类型。

    定义和使用一个不使用泛型的类

    确定使用的数据类型为String

    public class GenericClass { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } public class Demo02Generic { public static void main(String[] args) { GenericClass gc = new GenericClass(); gc.setName("zr"); Object name = gc.getName(); } }

    当我们不确定是什么数据类型的时候,就可以使用泛型,在创建对象的时候确定泛型的数据类型。

    定义和使用一个含有泛型的类

    public class GenericClass<E> { private E name; public E getName() { return name; } public void setName(E name) { this.name = name; } } public class Demo01Generic { public static void main(String[] args) { //不写泛型就默认为Object类型 GenericClass gc = new GenericClass(); gc.setName("zhangran"); Object obj = gc.getName(); //泛型使用Integer类型 GenericClass<Integer> gc2 = new GenericClass<>(); gc2.setName(1); Integer name = gc2.getName(); //泛型使用String类型 GenericClass<String> gc3 = new GenericClass<>(); gc3.setName("ryan"); String name2 = gc3.getName(); } }

    在使用泛型的时候不写泛型就默认为Object类型。

    定义和使用含有泛型的方法

    格式: 修饰符 <泛型> 返回值类型 方法名 (参数列表(使用泛型)){ 方法体; }

    含有泛型的方法,在调用的时候确定泛型的数据类型,传递什么类型的参数,泛型就是什么类型。

    public class GenericMethod { public <M> void method01(M m){ System.out.println(m); } public static <S> void method02(S s){ System.out.println(s); } }

    测试含有泛型的方法,传递什么类型,泛型就是什么类型。

    public class Demo03GenericMethod { public static void main(String[] args) { GenericMethod gm = new GenericMethod(); gm.method01(1); gm.method01("abc"); gm.method01(1.1); gm.method01(true); //静态方法,通过类名.方法名(参数)可以直接使用 GenericMethod.method02("静态方法"); GenericMethod.method02(1); } }

    定义和使用含有泛型的接口

    定义一个含有泛型的接口

    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对象。

    public class Demo01GenericInterface { public static void main(String[] args) { GenericInterfaceImpl1 gi1 = new GenericInterfaceImpl1(); gi1.method("字符串"); } }

    含有泛型的接口第二种使用方式:接口使用什么泛型,实现类就使用什么泛型,类跟着接口走;相当于定义了一个含有泛型的类,创建的时候确定泛型的类。

    public class GenericInterfaceImpl2<I> implements GenericInterface<I> { @Override public void method(I i) { System.out.println(i); } }

    测试含有泛型的接口,创建GenericInterfaceImpl2对象。

    public class Demo02GenericInterface { public static void main(String[] args) { //创建GenericInterfaceImpl2对象 GenericInterfaceImpl2<Integer> gi1 = new GenericInterfaceImpl2<>(); gi1.method(2); GenericInterfaceImpl2<Double> gi2 = new GenericInterfaceImpl2<>(); gi2.method(2.3); } }

    参考视频2019IDEA版黑马Java视频

    Processed: 0.009, SQL: 9