更好的地图构造函数 [英] Better Map Constructor
本文介绍了更好的地图构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有更精简的方法来执行以下操作?
Is there a more streamlined way to do the following?
Map<String, String> map = new HashMap<String, String>();
map.put("a", "apple");
map.put("b", "bear");
map.put("c", "cat");
我在找更接近这个的地方。
I'm looking for something closer to this.
Map<String, String> map = MapBuilder.build("a", "apple", "b", "bear", "c", "cat");
推荐答案
不,没有,方法做到这一点,受到Objective-C NSDictionary类的启发:
No, there isn't, but I wrote a method to do exactly this, inspired by Objective-C NSDictionary class:
public static Map<String, Object> mapWithKeysAndObjects(Object... objects) {
if (objects.length % 2 != 0) {
throw new IllegalArgumentException(
"The array has to be of an even size - size is "
+ objects.length);
}
Map<String, Object> values = new HashMap<String, Object>();
for (int x = 0; x < objects.length; x+=2) {
values.put((String) objects[x], objects[x + 1]);
}
return values;
}
这篇关于更好的地图构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文