带钻石操作员的双括号初始化(匿名内部类) [英] Double brace initialisation (anonymous inner class) with diamond operator

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

问题描述

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


错误:无法推断出HashMap的类型参数;
Map map2 = new HashMap<>(){
原因:不能对'匿名内部类使用'<>'
其中K,V是类型变量:
K extends在类HashMap中声明的对象
V extends类HashMap中声明的对象

代码:

 地图< 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:

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

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

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.

解决方案

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>.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆