谁能告诉我为什么类型推断失败?

问题描述 投票:3回答:1

当我在构造函数中使用与类相同的类型参数时,类型推断似乎失败。

public class GenericConstructor<T>{
    T x;
    <T> GenericConstructor(T t){

    }
    public static void main(String[] args) {
        //error, I want to ask this question
        GenericConstructor<Integer> gc1 = new GenericConstructor<>(3.14);  //error,cannot infer augument
        //succeed
        GenericConstructor<Integer> gc2 = new GenericConstructor<Integer>(3.14); //succeed
    }
}

但是当我在构造函数中更改类型参数时,它会成功

public class GenericConstructor<T>{
    T x;

    <X> GenericConstructor(X t){
    }
    public static void main(String[] args) {
        //succeed
        GenericConstructor<Integer> gc1 = new GenericConstructor<>(3.14);  //succeed
        //succeed
        GenericConstructor<Integer> gc2 = new GenericConstructor<Integer>(3.14); //succeed
    }
}

它使我感到困惑。通常,可以省略<>中的“整数”。

java constructor type-inference
1个回答
0
投票

您在这里有2个问题。第一个是类型变量范围的简单问题。第二个问题是您要传递一个double参数,该参数应为Integer

在此构造函数代码中

<T> GenericConstructor(T t) {
    this.x = t;
}

<T>重新声明一个类型变量,该类型变量hide具有相同名称的类级变量。这意味着该类中的T x与构造函数中的T t类型不同。

您应该对不同的事物使用不同的类型变量。但是,对于您而言,似乎根本不需要通用构造函数,因为您要使用类级别类型T

的值。
class GenericConstructor<T> {
    T x;

    GenericConstructor(T t) {
        this.x = t;
    }

    public static void main(String[] args) {
        GenericConstructor<Integer> gc1 = new GenericConstructor<>(3);
        GenericConstructor<Integer> gc2 = new GenericConstructor<>(3);
    }
}

[对于第二个问题,我必须从new GenericConstructor<>(3.14)更改为new GenericConstructor<>(3),因为当3.14T时,根据类型Integer,作为两倍的GenericConstructor<Integer>是无效的参数(导致编译器错误)。

构造函数使用T(在您的声明中为Integer,所以参数不能为双精度。

© www.soinside.com 2019 - 2024. All rights reserved.