你好啊!泛型

为什么要用泛型

我们在编写程序时,经常遇到两个模块的功能非常相似,只是一个是处理int型数据,另一个是处理String类型数据,或者其它自定义类型数据,但是我们没有办法,只能分别写多个方法处理每种数据类型,因为方法的参数类型不同。泛型的出现就是专门解决这个问题的。

基于方法的泛型
public class GenericDemo{
    public static void main(String[] args) {
        GenericDemo genericDemo = new GenericDemo();
        genericDemo.print("luo");
        genericDemo.print(90);
    }
    //通常在返回值前跟泛型修饰符,T 不是固定的,可以随意取
    public<T> void print(T t){
        System.out.println(t);
    }
}
//可以同时支持多个泛型
public interface Function<T, R> {
    R apply(T t);
}
基于类的泛型

在类中多次用到同一个泛型,就可以定义在类上

public class GenericDemo<T>{
    public static void main(String[] args) {
        GenericDemo<Integer> genericDemo = new GenericDemo<>();
        Integer[] array = {1,1,2,5};
        genericDemo.printArray(array);
    }

    public void printArray(T[] t){
        Stream.of(t).forEach(System.out::println);
    }
    public void add(T t){
        System.out.println(t);
    }
}

注意:静态方法不能使用泛型类上定义的泛型

基于接口的泛型
public interface MyInterface<T> {
    public void add(T t);
}
public class MyInterfaceImpl<T> implements MyInterface<T> {
    @Override
    public void add(T t) {
	
    }
}

public class Test01 {
    public static void main(String[] args) {
        MyInterfaceImpl<Integer> integerMyInterface = new MyInterfaceImpl<>();
        MyInterfaceImpl<String> integerMyInterface2 = new MyInterfaceImpl<>();
        integerMyInterface.add(32);
        integerMyInterface2.add("luo");
    }
}

注意:泛型的类型只能是引用类型或自定义类型

泛型的高级应用

<? extends E> :向下限定,E及其子类

<? extends E> :向上限定,E及其父类

<?> :任意类型


public class Animal {}
public class Cat extends Animal{}
public class Dog extends Animal {}

public class Test01 {
    public static void main(String[] args) {
        Collection <? extends Animal> collection1 = new ArrayList<Dog>();
        Collection <? extends Animal> collection2 = new ArrayList<Cat>();
        Collection <? extends Animal> collection3 = new ArrayList<Animal>();
        Collection <? super Animal> collection4 = new ArrayList<Object>();
        Collection <? super Animal> collection5 = new ArrayList<Animal>();
        Collection <?> collection6 = new ArrayList<Integer>();
        Collection <?> collection7 = new ArrayList<String>();
        Collection <?> collection8 = new ArrayList<Object>();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_42224683/article/details/107543493