Reputation: 34424
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 the diamond operator on the right-hand side(RHS). My question why don't remove the complete diamond operator from RHS? I know it will throw the warning, but Java 7 could have removed the warning too.
- 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
The logic behind my thinking:
As we have already defined the map will have a string as a key and an object with Map<String, String> myMap on LHS.
With this compiler has sufficient info. So why does it throw a warning if you miss the diamond operator altogether?
I am sure there must be a reason behind it but I am not getting it.
Upvotes: 2
Views: 718
Reputation: 15145
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.
Upvotes: 1