• Java泛型方法定义及泛型类型推断


    泛型的推断

        @Test
        public void test3(){
            //类型推断时使用两个类型的最小公倍数
            int x1 = add(3,4);
            Number x2 = add(3.5,4);
            Object obj = add(3,"abc");
        }
        //在返回类型前加上<T>
        public <T> T add(T x,T y){
            return x;
        }

    传入一个数组,交换其中的两项:

        @Test
        public void test4(){
            String[] result = swap(new String[]{"abc","xyz","999"}, 1, 2);
            for(String s:result){
                System.out.println(s);
            }
            Book[] bs = swap(new Book[]{new Book("三国演义","罗贯中"),new Book("水浒传","施耐庵"),new Book("红楼梦","曹雪芹")}, 0, 2);
            for(Book b:bs){
                System.out.println(b.getName()+","+b.getAuthor());
            }
            //以下做法错误,T不可以为基本类型
            //int[] arr = swap(new int[]{1,2,3},1,2);
        }
        //在返回类型前加上<T>
        public <T> T[] swap(T[] a,int i,int j){
            T temp = a[i];
            a[i] = a[j];
            a[j] = temp;
            return a;
        }

    定义泛型时限定类型:

        @Test
        public void test4(){
            String[] result = swap(new String[]{"abc","xyz","999"}, 1, 2);
            for(String s:result){
                System.out.println(s);
            }
            Book[] bs = swap(new Book[]{new Book("三国演义","罗贯中"),new Book("水浒传","施耐庵"),new Book("红楼梦","曹雪芹")}, 0, 2);
            for(Book b:bs){
                System.out.println(b.getName()+","+b.getAuthor());
            }
            //以下做法错误,T不可以为基本类型
            //int[] arr = swap(new int[]{1,2,3},1,2);
        }
        //在返回类型前加上<T>
        public <T extends Object> T[] swap(T[] a,int i,int j){
            T temp = a[i];
            a[i] = a[j];
            a[j] = temp;
            return a;
        }

    上面代码要求T要是Object的子类,这其实是废话,如果把Object改为Number则编译时上面的两个方法都会报错,因为String和Book类都不是Number的子类。

  • 相关阅读:
    PowerDesigner执行SQL生成模型
    IBM,ORACLE 文档
    JAAS 自定义登陆模块
    JAAS 使用windos登陆示例
    IFRAME跨域
    JAVA RSA 数字签名
    JAVA数字证书
    搭模型时常用的numpy公式,不定时更新~
    Failed to connect to github.com port 443: Timed out
    linux和colab上安装torch_geometric踩坑记录,安装过程
  • 原文地址:https://www.cnblogs.com/lenve/p/4518001.html
Copyright © 2020-2023  润新知