有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java泛型类型不匹配

class GenMethDemo {
    static <T, V extends T> boolean isIn(T x, V[] y) {
        for (int i = 0; i < y.length; i++)
            if (x.equals(y[i]))
                return true;
        return false;
    }

    /*when compiled in java 7 it producing an error and compiling in java 8 without error */
    public static void main(String args[]) {
        Integer nums[] = {1, 2, 3, 4, 5};
        String s[] = {"one", "two", "three"};
        System.out.println(isIn("fs", nums));
      /*
      when compiled in java 7 it producing an error and compiling in java 8 without error */
    }
}

共 (2) 个答案

  1. # 1 楼答案

    在Java7中,类型推断将看到T = StringV = Integer,这将不满足V extends T

    但是,Java 8的JLS声明这将起作用:

    List<Number> ln = Arrays.asList(1, 2.0);
    

    因此,在您的情况下,这将被解析为T = V = Object

  2. # 2 楼答案

    这是由于Java8中对通用目标类型推断的改进。事实上,我上周回答了一个类似的问题Java 8 call to generic method is ambiguous

    问题Java 8: Reference to [method] is ambiguous的第一个答案也很好

    Java8能够推断传递给泛型方法的参数类型。正如@Thomas在他的评论中所说,类型T被推断为Object,而V被推断为扩展Object的对象,因此Integer。在Java7中,这只会抛出一个错误,因为Integer显然没有扩展String