为什么不应用类型推断?

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

在这种情况下,类型推断按预期工作,

T
类型参数同时处理
Integer
String
:

public class A {
    public static <T> void func(T obj1, T obj2) {}
    public static void main(String[] args) {
        A.func(1, "One");
    }
}

但是,这似乎不适用于以下示例,因为出现了编译错误

class Test<T> {
    private T object;
    public Test(T object) {
        this.object = object;
    }
}

public class A {
    public static <T> void func(Test<T> one, Test<T> two) {}
    public static void main(String[] args) {
        Test<Integer> one = new Test<>(1);
        Test<String> two = new Test<>("Two");
        A.func(one, two);  //compilation error
        //A.<Object>func(one, two);
    }
}

尽管 (例如)

Test<Object>
可以处理
Test<Integer>
Test<String>
,但
T
类型参数不是 推断的。为什么会出现这种情况?

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

func
要求两个测试具有相同类型(名为 T),但其中一个和两个具有不同的类型。

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