【问题标题】:reason: inferred type does not conform to upper bound(s)原因:推断类型不符合上限
【发布时间】:2015-12-12 17:27:43
【问题描述】:

我试图寻找类似的答案,但我还没有得到/找到解决方案,然后我直接要求公开我的案例

我有一个静态函数validate

    private static void validate(AiNode pNode) {
        ...
            for (AiNode child : pNode.mChildren) {
                doValidation(child.mMeshes, child.mMeshes.length, "a", "b");
            }
        }
    }

pNode.mChildrenAiNode 的数组。

这是我的doValidation

private static <T> void doValidation(T[] pArray, int size, String firstName, String secondName) {

        // validate all entries
        if (size > 0) {

            if (pArray == null) {

                throw new Error("aiScene." + firstName + " is NULL (aiScene." + secondName + " is " + size + ")");
            }
            for (int i = 0; i < size; i++) {

                if (pArray[i] != null) {

                    validate(parray[i]);
                }
            }
        }
    }

但我不断收到此错误

method doValidation in class ValidateDataStructure cannot be applied to given types;
  required: T[],int,String,String
  found: int[],int,String,String
  reason: inferred type does not conform to upper bound(s)
    inferred: int
    upper bound(s): Object
  where T is a type-variable:
    T extends Object declared in method <T>doValidation(T[],int,String,String)
----
(Alt-Enter shows hints)

我认为这与 java 中原始类型的数组扩展 Object[] 的事实有关,实际上,如果我将 T[] 切换到 T 它可以工作,但是我不能再循环它了......我不'不知道如何解决它或哪种解决方案最适合我的情况。

想法是基于数组T 类型有不同的validate(T[] array)

【问题讨论】:

  • 消息说明了一切。 int 不能是 T
  • 使用 Integer[] 代替 int[]
  • 顺便说一下T在这里是不必要的;你可以声明它private static void doValidation(Object[] pArray, int size, String firstName, String secondName)
  • 天哪,你是对的..!谢谢

标签: java arrays generics java-8


【解决方案1】:

您的数组是int[],而不是Integer[]。要将其转换为Integer[],请使用

for (AiNode child : pNode.mChildren) {
    Integer[] meshes = Arrays.stream(child.mMeshes).boxed().toArray(Integer::new);
    doValidation(meshes, child.mMeshes.length, "a", "b");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-04
    • 1970-01-01
    • 1970-01-01
    • 2015-06-23
    • 1970-01-01
    • 2019-04-25
    • 2019-07-26
    相关资源
    最近更新 更多