Double brace initialisation (anonymous inner class) with diamond operator

后端 未结 4 1540
轻奢々
轻奢々 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 13:57

    Diamond inference doesn't work for instantiating anonymous classes, which is what you're doing here.

    Try this:

    Map map1 = new HashMap<>();
    
    {
        map1.put("abc", "abc");
    }
    

提交回复
热议问题