我想知道为什么第二个 map 声明(使用菱形运算符)在第一个 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 中找到了解释
It is a compile-time error if a class instance creation expression declares an anonymous class using the "<>" form for the class's type arguments.
最佳答案
这里没有static 初始值设定项(关键字static 完全缺失)。
基本上你创建了一个新的匿名子类 HashMap
并在此处定义实例初始化程序 block 。顺便说一句,这只适用于 HashMap
不是最终的。
因为您将获得 HashMap
的匿名子类菱形运算符在这里不起作用,因为子类将被编译为就好像您编写了 ... extends HashMap<Object, Object>
这显然与 Map<String, String>
不兼容.
关于java - 使用菱形运算符的双括号初始化(匿名内部类),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9773733/