Double brace initialisation (anonymous inner class) with diamond operator

后端 未结 4 1533
轻奢々
轻奢々 2020-12-10 13:44

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

error: cannot

4条回答
  •  再見小時候
    2020-12-10 14:16

    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 and this clearly isn't compatible to Map.

提交回复
热议问题