有 Java 编程相关的问题?

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

Diamond不编译Java 7

我已经定义了以下泛型类,但当我在类对象上使用它时,它不会编译。构造函数不接受其他对象

class Pair<T,V> {

    T one;
    V two;


    public Pair(T one, V two) {
        this.one = one;
        this.two = two;
    }


}
public static void main(String[] args) {

    String hamza = "Hamza";
    Integer soufiane = 0;

    Pair<Object,Object> pairOne = new Pair<>(hamza, soufiane);
    Pair<Object,Object> pairTwo = new Pair<Object, Object>(soufiane, hamza);

}

错误消息:

incompatible types: Pair<String,Integer> cannot be converted to Pair<Object,Object>

为什么第一个没有编译,第二个编译

编辑:它是在Java 8上编译的


共 (1) 个答案

  1. # 1 楼答案

    代码失败是因为java 7编译器找不到正确的推断类型;另一方面,Java8可以很好地编译和工作。(tl;dr:java7不能正确处理所有钻石,这在java8中得到了改进)

    JEP 101: Generalized Target-Type Inference

    Smoothly expand the scope of method type-inference to support (i) inference in method context and (ii) inference in chained calls.

    这意味着java 8将能够使用diamond操作符确定您的呼叫类型

    编辑:似乎有人在thread中抢先回答了我,并比我解释得更清楚;看一看