如何使用具有泛型HashMap的实例初始值设定项? [英] How to use an instance initializer with a generic HashMap?

查看:122
本文介绍了如何使用具有泛型HashMap的实例初始值设定项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你可以使用一个具有泛型HashMap的实例初始化器吗?

Can you use an instance initializer with a generic HashMap?

我在线找到了这个代码,但是很难将它转换为泛型HashMap而不是基本的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");}}); 


推荐答案

以下是操作方法:

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");}});
  }
}

编辑:关于压缩serial-ID:是的,你可以这样做,但我会重写它:

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);
  }
}

不需要压缩,更好读取,IMO 。

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

这篇关于如何使用具有泛型HashMap的实例初始值设定项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆