JDK7 中推断的泛型类型和反引号
我一直在学习 Java 教程,并且阅读 JDK7 中的泛型类型推断。
我遇到了以下语法......
class MyClass<X> {
<T> MyClass(T t) {
// ...
}
}
MyClass<Integer> myObject = new <String`> MyClass<>("");
这有点令人困惑。我了解“钻石”运算符以及如何根据上下文推断泛型类型。
我不确定为什么您要使用菱形运算符来推断传递给构造函数的类型,同时还显式指定类型“String`”?我也不明白为什么要涉及反引号!
另外,以下有区别吗?
MyClass<Integer> myObject1 = new <String> MyClass<>(""); // JDK7 only
MyClass<Integer> myObject2 = new MyClass<>(""); // JDK7 only
MyClass<Integer> myObject3 = new <String> MyClass<Integer>("");
I have been making my way through the Java Tutorial and have been reading about generic type inference in 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? 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>("");
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
就是
这样,你就是的实例;
1. 创建 MyClass
2. 使用 String 作为类型参数调用构造函数:
菱形运算符与构造函数无关,因为它不会“推断传递给构造函数的类型”,但它推断传递给整个类的类型。
哦,我认为 教程示例中的反引号 可能是一个印刷错误。 :)
is just
that is, you are
1. creating an instance of MyClass<Integer>
2. invoking the constructor with String as a type parameter:
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.
Oh, and I think the backtick in the tutorial example is probably a typographic error. :)