How do I use collection literals in Java 7?

前端 未结 3 1125
离开以前
离开以前 2020-12-16 11:25

I\'ve tried the following line:

Map map={new Character(\'r\'):Color.red,new Character(\'b\'):Color.black};

But Netb

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-16 12:08

    To expand a little on Thomas's answer... Map is an interface, and must be instantiated through one of the associated concrete implementations (HashMap, TreeMap, or LinkedHashMap). It is still good practice; however, to declare your reference variable as the interface implementation rather than the specific concrete, as it provides future flexibility.

    Regarding the code snippet though, I think you do still need the Key-value pairs defined in the assignment side of the declaration. So, I would change:

    Map map = new HashMap<>() {{ 
    

    to

    Map map = new HashMap() {{ 
    

提交回复
热议问题