为什么在Java 7中,右侧没有错过Diamond操作符? [英] Why Diamond operator was not missed from Right hand side in Java 7?

查看:83
本文介绍了为什么在Java 7中,右侧没有错过Diamond操作符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java 7改进了钻石运算符在Java 6中,b

映射< String,String> myMap = new HashMap< String,String>(); 

在Java 7中

 地图< String,String> myMap = new HashMap<>(); 

Java 7类型已从右侧的钻石运算符(RHS)中删除。我的问题是为什么不从RHS中删除完整的钻石。
我知道它会抛出警告,但是java 7也可以删除警告。

   -  

类型安全性:类型HashMap的表达式需要未经检查的转换以符合
Map< String,String>
- HashMap是一个原始类型。对泛型类型HashMap的引用< K,V>应该参数化

逻辑背后我认为: - 因为我们已经定义了map将字符串作为键并用LHS上的Map myMap对象。
这个编译器有足够的信息。那么为什么它会抛出警告,如果你完全错过钻石经营者?我确定必须有理由
在后面,但我没有得到它吗?

解决方案

以下代码编译并运行没有错误。

  SoftReference< String> ref = new SoftReference(new Integer(1)); 
Object o = ref.get();
System.out.println(o); //打印1

原始实例 SoftReference 被创建。 原始意味着没有泛型类型检查,这是允许将泛型与预泛型代码混合所需的。



通过使钻石操作符隐含,您可以打破它。


Java 7 has improved the diamond operator

In Java 6

Map<String, String> myMap = new HashMap<String, String>();

In Java 7

  Map<String, String> myMap = new HashMap<>();

In Java 7 Types have been removed from diamond operator on Right hand side(RHS). My question why don't remove complete diamond operate from RHS. I know it will throw the warning, But java 7 could have removed the warning also.

                    -

 Type safety: The expression of type HashMap needs unchecked conversion to conform to 
 Map<String,String>
- HashMap is a raw type. References to generic type HashMap<K,V> should be parameterized

Logic behind my think :- As we have already defined that map will have string as key and object with Map myMap on LHS. With this compiler has sufficient info. So why it throws warning if you miss diamond operator altogether ? I am surethere must be reason behind it but i am not getting it?

解决方案

The following code compiles and runs without error.

SoftReference<String> ref = new SoftReference(new Integer(1));
Object o = ref.get();
System.out.println(o); // prints "1"

A raw instance of SoftReference is created. "Raw" means that there is no generic type checking, which is required to allow to mix generics with pre-generics code.

By making the diamond operator implicit, you would break it.

这篇关于为什么在Java 7中,右侧没有错过Diamond操作符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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