泛型使用过程中不要在新代码中使用原生态类型

public class Generic {

    public static void main(String[] args) {

        // 原生态类型
        List list = new ArrayList<>();
        list.add(1);
        list.add(2L);

        System.out.println(list.get(0));
        // System.out.println((Integer) list.get(1));
        // Exception in thread "main" java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer
        // at com.atguigu.springbootbase.effective.E01.main(E01.java:22)

        // 添加泛型
        List<Integer> list2 = new ArrayList<>();
        /* list2.add(1);
        // Required type:Integer Provided:long
        list2.add(2L);*/

        // 参数传递的时候把泛型去掉了
        odd(list2, 1);
        oddNew(list2, 3);
        odd(list2, 2L);
        // oddNew(list2, 2L); // 提前报错,提前处理
        oddNew(list2, 4); // 提前报错,提前处理
        System.out.println(list2);

        // Exception in thread "main" java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer
        // at com.atguigu.springbootbase.effective.E01.main(E01.java:37)
        // System.out.println((Integer) list2.get(1));

        System.out.println((Integer) list2.get(3));
    }

    // 参数传递的时候把泛型去掉了
    public static void odd(List list, Object o) {
        list.add(o);
    }

    // 参数传递的时候把泛型加上
    public static void oddNew(List<Integer> list, Integer o) {
        list.add(o);
    }
}
上一篇:Java注解


下一篇:20220210 java.lang.Iterable