泛型详解(Java1.5新特性)

一. 思维导图

在这里插入图片描述

二. 示例代码

  1. 泛型类
//泛型类
public class ClassDemo<T> {
    private T key;

    public T getKey() {
        return key;
    }

    public void setKey(T key) {
        this.key = key;
    }
}
  1. 泛型接口
//泛型接口
public interface InterfaceDemo<T> {
    public T hello();
}
//实现泛型接口
public class InterfaceDemoImpl implements InterfaceDemo<Integer>{
    @Override
    public Integer hello() {
        return 5;
    }
}
  1. 泛型方法
public class MethodDemo {
    public <T> void method(T t) {
        System.out.println(t);
    }
}
  1. 通配符
public class WildcardDemo {
    //上界通配符
    public static void top(List<? extends Number> list) {

    }

    //下届通配符
    public static void bottom(List<? super Integer> list) {

    }
}
  1. 测试类
public class Main {
    public static void main(String [] args) throws Exception {
        //泛型类
        ClassDemo<String > classDemo = new ClassDemo<String>();
        classDemo.setKey("你好,java");
        System.out.println(classDemo.getKey());

        //泛型接口
        InterfaceDemoImpl interfaceDemo = new InterfaceDemoImpl();
        int a = interfaceDemo.hello();
        System.out.println(a);

        //泛型方法
        MethodDemo methodDemo = new MethodDemo();
        methodDemo.method(2);
        methodDemo.method("0");

        //上界通配符
        List<Integer> integers = new ArrayList<>();
        WildcardDemo.top(integers);
        
        //下届通配符
        List<Number> numbers =  new ArrayList<>();
        WildcardDemo.bottom(numbers);
    }
}
发布了25 篇原创文章 · 获赞 1 · 访问量 439

猜你喜欢

转载自blog.csdn.net/qq_44837912/article/details/103549350
今日推荐