通用方法引发数字数组的编译器错误要怎么处理

来源:爱站网时间:2021-11-26编辑:网友分享
最近有不少朋友问爱站技术小编通用方法引发数字数组的编译器错误要怎么处理,今天小编就用一篇文章给大家说说这方面的资料。希望能帮助到大家,喜欢的朋友可以收藏起来。

问题描述


我正在尝试调用一个返回通用数组标识的方法,并提供intdouble的数组作为测试数据。我输入的参数应该实现Comparable接口,但是编译器似乎在抱怨:

method identity in class com.me.Test cannot be applied to given types;
  required: T[]
  found:    int[]
  reason: inference variable T has incompatible bounds
    equality constraints: int
    lower bounds: java.lang.Comparable

我是Java的新手,所以我可能缺少一些东西。有什么想法吗?

代码:

public class Main {

    public static void main(String[] args) {
        int[] arr1 = {1};
        double[] arr2 = {1.0};
        System.out.println(Test.identity(arr1));
        System.out.println(Test.identity(arr2));
    }
}

public class Test {
    public static > T[] identity(T[] x) {
        return x;
    }
}

思路:


您可以执行以下操作(但没有原始元素类型,因为泛型无法使用它们):

public class Main {

    public static  Class> identity(T[] array) {
    return array.getClass().getComponentType();
}

    public static void main(String[] args) {
        Integer[] arr1 = new Integer[]{1};
        Double[] arr2 = new Double[] {1.0};
        System.out.println(identity(arr1));
        System.out.println(identity(arr2));
    }
}

 以上内容就是爱站技术频道小编为大家分享的通用方法引发数字数组的编译器错误要怎么处理,看完以上分享之后,大家应该都知道怎么处理了吧。

上一篇:PyLucene的Make和Make安装麻烦

下一篇:为什么括号应与toString一起使用

您可能感兴趣的文章

相关阅读

热门软件源码

最新软件源码下载