How to use an instance initializer with a generic HashMap?

喜你入骨 提交于 2019-12-13 04:39:22

问题


Can you use an instance initializer with a generic HashMap?

I found this code online, but am having trouble converting it to a generic HashMap instead of a basic HashMap:

someMethodThatTakesAHashMap(new HashMap(){{put("a","value-a"); put("c","value-c");}}); 

回答1:


Here's how:

class Foo {

  static void someMethodThatTakesAHashMap(HashMap<String, String> map) {
    System.out.println(map);  
  }

  public static void main(String[] args) {
    someMethodThatTakesAHashMap(new HashMap<String, String>(){{put("a","value-a"); put("c","value-c");}});
  }
}

Edit: about the suppressing of the serial-ID: yes, you could do that, but I'd rewrite it like this:

public class Foo {

  static void someMethodThatTakesAHashMap(Map<String, String> map) {
    System.out.println(map);  
  }

  public static void main(String[] args) {
    HashMap<String, String> map  = new HashMap<String, String>();
    map.put("a","value-a"); 
    map.put("c","value-c");
    someMethodThatTakesAHashMap(map);
  }
}

No suppressing needed, and much better to read, IMO.



来源:https://stackoverflow.com/questions/1514866/how-to-use-an-instance-initializer-with-a-generic-hashmap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!