在一个语句中一次向 HashMap 添加多个条目 [英] adding multiple entries to a HashMap at once in one statement

查看:29
本文介绍了在一个语句中一次向 HashMap 添加多个条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要初始化一个常量 HashMap,并希望在一行语句中完成.避免这样的事情:

I need to initialize a constant HashMap and would like to do it in one line statement. Avoiding sth like this:

  hashMap.put("One", new Integer(1)); // adding value into HashMap
  hashMap.put("Two", new Integer(2));      
  hashMap.put("Three", new Integer(3));

与目标 C 中的类似:

similar to this in objective C:

[NSDictionary dictionaryWithObjectsAndKeys:
@"w",[NSNumber numberWithInt:1],
@"K",[NSNumber numberWithInt:2],
@"e",[NSNumber numberWithInt:4],
@"z",[NSNumber numberWithInt:5],
@"l",[NSNumber numberWithInt:6],
nil] 

看了这么多,我还没有找到任何例子来说明如何做到这一点.

I have not found any example that shows how to do this having looked at so many.

推荐答案

可以使用双大括号初始化,如下图:

Map<String, Integer> hashMap = new HashMap<String, Integer>()
{{
     put("One", 1);
     put("Two", 2);
     put("Three", 3);
}};

作为一个警告,请参考线程 Efficiency of Java Double Brace"初始化" 可能对性能产生影响.

As a piece of warning, please refer to the thread Efficiency of Java "Double Brace Initialization" for the performance implications that it might have.

这篇关于在一个语句中一次向 HashMap 添加多个条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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