本文介绍了在一条语句中添加多个条目一个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);
}};

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

10-20 09:24