为什么在Java 7中使用菱形运算符进行类型推理? [英] Why diamond operator is used for Type Inference in Java 7?

查看:155
本文介绍了为什么在Java 7中使用菱形运算符进行类型推理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

列表与LT;字符串> list = new ArrayList(); 将导致编译器警告。

List<String> list = new ArrayList(); will result in compiler warning.

但是,以下示例编译时没有任何警告: List< String> list = new ArrayList<>();

However the following example compiles without any warning: List<String> list = new ArrayList<>();

我很好奇为什么需要引入钻石操作符。如果不存在类型参数,为什么不在构造函数上进行类型推断(因为它已经在java中为静态方法完成并被像google guava这样的集合库利用)

I'm curious why introducing of diamond operator is needed at all. Why not just have type inference on constructor if type argument is absent (as its already done for static methods in java and exploited by collection libraries like google guava)

编辑 :使用millimoose答案作为起点,我查看了实际上是什么类型的擦除,而不只是删除所有类型信息。编译器实际上做了一些(从官方文档复制):


  • 如果类型参数是无界的,则用泛型或对象替换泛型类型中的所有类型参数。因此,生成的字节码仅包含普通的类,接口和方法。

  • 如有必要,插入类型转换以保持类型安全。

  • 生成桥保留扩展泛型类型中多态性的方法。

推荐答案

明确答案必须来自设计该功能的人,但我假设要将其与使用原始类型区分开来,这使得编译器为了兼容性而完全不同。其中包含原始类型的表达式巧妙处理与涉及泛型的表达式不同,在此SO问题中找到了一个示例:通用搞砸非相关集合

The definitive answer would have to come from someone who designed that feature, but I'm assuming it's to distinguish this from using raw types, which make the compiler do something different altogether for the sake of compatibility. An expression with a raw type in it is processed subtly differently than one that involves generics, an example is found in this SO question: Generic screws up non-related collection

这篇关于为什么在Java 7中使用菱形运算符进行类型推理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆