adding multiple entries to a HashMap at once in one statement(在一个语句中一次向 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 添加多个条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在一个语句中一次向 HashMap 添加多个条目


基础教程推荐
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13