我想知道为什么第二个使用钻石操作符的 map 声明无法编译,而第一个可以。编译错误:
error: cannot infer type arguments for HashMap; Map map2 = new HashMap<>() { reason: cannot use '<>' with anonymous inner classes where K,V are type-variables: K extends Object declared in class HashMap V extends Object declared in class HashMap
代码:
Map<String, String> map1 = new HashMap<String, String>() { //compiles fine
{
put("abc", "abc");
}
};
Map<String, String> map2 = new HashMap<>() { //does not compile
{
put("abc", "abc");
}
};
编辑
感谢您的回答-我应该更好地阅读编译错误。
我在JLS中找到了解释。
如果使用“<>”形式为类的类型参数声明匿名类,则这是一个编译时错误。
EnumMap
的匿名内部类。我猜想这是意外发生的。 - biziclop