2

Java 7 改进了菱形运算符

在 Java 6 中

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

在 Java 7 中

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

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

                    -

 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

我的想法背后的逻辑:-正如我们已经定义的那样,地图将在 LHS 上使用 Map myMap 将字符串作为键和对象。有了这个编译器有足够的信息。那么,如果您完全错过了钻石运算符,为什么它会发出警告呢?我确信这背后一定有原因,但我不明白?

4

1 回答 1

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.

于 2014-03-23T13:21:01.743 回答