开发者

How to use an instance initializer with a generic HashMap?

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:

someMetho开发者_如何转开发dThatTakesAHashMap(new HashMap(){{put("a","value-a"); put("c","value-c");}}); 


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜