简体   繁体   English

推断的泛型类型和 JDK7 中的反引号

[英]Inferred generic types and the backtick in JDK7

I have been making my way through the Java Tutorial and have been reading about generic type inference in JDK7 .我一直在阅读Java 教程,并且一直在阅读 JDK7 中的泛型类型推断

I came across the following syntax...我遇到了以下语法...

class MyClass<X> {
    <T> MyClass(T t) {
        // ...
    }
}

MyClass<Integer> myObject = new <String`> MyClass<>("");

...which is a little confusing. ...这有点令人困惑。 I understand the 'diamond' operator and how generic types can be inferred based on the context.我了解“钻石”运算符以及如何根据上下文推断泛型类型。

I'm not sure why you'd use the diamond operator to infer the type passed to the constructor whilst explicitly specifying the type "String`" as well?我不确定您为什么要使用菱形运算符来推断传递给构造函数的类型,同时还明确指定类型“String`”? Nor do I understand why the backtick is involved!我也不明白为什么涉及反引号!

Also, is there a difference between the following?另外,以下有区别吗?

MyClass<Integer> myObject1 = new <String> MyClass<>(""); // JDK7 only
MyClass<Integer> myObject2 = new MyClass<>(""); // JDK7 only
MyClass<Integer> myObject3 = new <String> MyClass<Integer>("");
MyClass<Integer> myObject = new <String> MyClass<>("");

is just只是

MyClass<Integer> myObject = new <String> MyClass<Integer>("");

that is, you are 1. creating an instance of MyClass<Integer> 2. invoking the constructor with String as a type parameter:也就是说,您是 1. 创建 MyClass<Integer> 的实例 2. 使用 String 作为类型参数调用构造函数:

<String> MyClass(String t) {
    // ...
}

The diamond operator has nothing to do with the constructor, as it does not "infer the type passed to the constructor" yet it infers the type passed to the whole class.菱形运算符与构造函数无关,因为它不会“推断传递给构造函数的类型”,而是推断传递给整个 class 的类型。

Oh, and I think the backtick in the tutorial example is probably a typographic error.哦,我认为教程示例中的反引号可能是印刷错误。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM