带钻石操作员的双括号初始化

带钻石操作员的双括号初始化

本文介绍了带钻石操作员的双括号初始化(匿名内部类)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么第二个映射声明(使用菱形运算符)在第一个声明时没有编译。编译错误:

代码:

 地图< String,String> map1 = new HashMap< String,String>(){//编译罚款

{
put(abc,abc);
}
};

地图< String,String> map2 = new HashMap<>(){//不编译

{
put(abc,abc);
}
};

编辑

感谢您的回答 - 我应该更好地阅读编译错误。
我在 JLS


这里没有静态关键字 static 完全缺失)。

基本上你创建了一个新的 HashMap 的匿名子类,并在这里定义了实例初始化块。顺便说一句,这只适用于 HashMap 不是最终的。



因为你会得到一个匿名的 HashMap 菱形运算符在这里不起作用,因为子类将被编译为就像编写了 ... extends HashMap< Object,Object> ,这显然与 Map< String,String> 不兼容。


I am wondering why the second map declaration (using the diamond operator) does not compile when the first one does. Compilation error:

Code:

    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");
        }
    };

EDIT
Thanks for your answers - I should have read the compilation error better.I found the exaplanation in the
JLS

解决方案

You don't have a static initializer here (the keyword static is missing altogether).

Basically you create a new anonymous subclass of HashMap and define the instance intializer block here. Btw, this only works since HashMap is not final.

Since you'll get an anonymous subclass of HashMap the diamond operator doesn't work here, since the subclass would then be compiled as if you wrote ... extends HashMap<Object, Object> and this clearly isn't compatible to Map<String, String>.

这篇关于带钻石操作员的双括号初始化(匿名内部类)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 15:56