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

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

public class Test {
    public static void main(String[] args) {
        GenericInterfaceImpl genericInterface = new GenericInterfaceImpl();
        genericInterface.method("哈哈哈哈哈哈String");
    }
}


/**
 * 定义含有泛型的接口,第一种使用方式:定义接口的实现类,实现接口指定接口的泛型
 */
interface GenericInterface<E>{
    void method(E i);
}

class GenericInterfaceImpl implements GenericInterface<String>{

    @Override
    public void method(String s) {
        System.out.println(s);
    }
}
/**
 * 含有泛型接口第二种使用方式:接口使用什么泛型实现类就用什么泛型,类跟着接口走
 * 就相当于定义了一个含有泛型的类,创建对象的时候确认泛型的类型
 */
class GenericInterfaceImpl<I> implements GenericInterface<I>{

    @Override
    public void method(I i) {
        System.out.println(i);
    }
}


public class Test {
    public static void main(String[] args) {
        GenericInterfaceImpl<Integer> integerGenericInterface = new GenericInterfaceImpl<>();
        integerGenericInterface.method(5);

        GenericInterfaceImpl<String> stringGenericInterface = new GenericInterfaceImpl<>();
        stringGenericInterface.method("String");


    }
}

泛型通配符

当使用泛型类或者接口的时候,传递的数据中,泛型类型不确定,可以通过通配符<?>表示。但是一旦使用泛型的通配符之后,只能使用Object类中的共性方法,集合中元素自身方法无法使用

通配符基本使用

泛型的通配符:不知道使用什么类型来接受的时候,此时可以使用?,?表示未知通配符
此时只能接受数据,不能往该集合中存储数据
举例:

public class Test {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("a");
        list.add("b");
        list.add("c");


        ArrayList<Integer> list1 = new ArrayList<>();
        list1.add(1);
        list1.add(2);
        list1.add(3);

        printArray(list);

        printArray(list1);
    }



    /**
     *  定义一个方法,能遍历所有类型的ArrayList集合
     *  这时候我们不知道ArrayList集合使用什么数据类型,就可以使用泛型通配符
     */

    public static void printArray(ArrayList<?> list){
        list.forEach(o -> System.out.println(o ));
    }
}

posted @   我滴妈老弟  阅读(23)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示