Why Diamond operator was not missed from Right han

2019-02-15 06:29发布

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条回答
姐就是有狂的资本
2楼-- · 2019-02-15 07:02

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.

查看更多
登录 后发表回答