zoukankan      html  css  js  c++  java
  • JAVA高级复习-自定义泛型类、泛型接口的注意点

    1. 静态方法中不能使用泛型

    2. 泛型数组的正确写法

    public class Student<T> {
        private T studentT;
    
        //静态方法中不能使用泛型
    //    public static void show(T studentT) {
    //        System.out.println(studentT);
    //    }
    
        public void read() {
            //泛型数组的错误写法,编译不通过,报错(Type parameter 'T' cannot be instantiated directly)
    //        T[] arr = new T[10];
    
            //泛型数组的正确写法,编译通过
            T[] objects = (T[]) new Object[10];
        }
    }
    

    3. 泛型不同的引用,不能相互赋值,否则报错(Incompatible types)

    4. 异常类不能是泛型的,编译报错(Generic class may not extend 'java.lang.Throwable')

    /**
     * 自定义泛型类、泛型接口的注意点
     */
    public class GenericTest4 {
    
        @Test
        public void test01() {
            List<Integer> list1 = new ArrayList<>();
            List<String> list2 = new ArrayList<>();
            //泛型不同的引用,不能相互赋值,否则报错(Incompatible types)
    //        list1 = list2;
    
        }
    
    }
    
    /**
     * 异常类不能是泛型的,编译报错(Generic class may not extend 'java.lang.Throwable')
     */
    //class MyException<T> extends RuntimeException {
    //
    //}
    
  • 相关阅读:
    harbor docker
    dns服务器
    k8s
    frps
    svn 搭建
    phpstrom 破解 转载https://www.jianshu.com/p/e71361b3bfee
    公开课
    k8s
    rsync各种备份
    定时任务
  • 原文地址:https://www.cnblogs.com/elnimo/p/13654052.html
Copyright © 2011-2022 走看看