Why Diamond operator was not missed from Right hand side in Java 7?

点点圈 提交于 2019-12-01 09:33:12

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/22591201/why-diamond-operator-was-not-missed-from-right-hand-side-in-java-7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!