问题描述
我有一个以下形式的嵌套集合:
I have a nested collection in the form:
HashMap<String, HashMap<String, List<String>>> errorList;
现在,我可以像这样用双花括号内联初始化它
Now I initialize it inline using double braces like this
errorList.put(tempName, new HashMap<String, List<String>>() {{
put("upl", new ArrayList<String>() {{ add("Y"); add("Upload Success"); }});
}});
这位于一个foreach循环中,每次迭代中tempName
的值都会更改.我这样做是因为我无法使用List<String>
或HashMap<String,List<String>>
的实例,因为每次更改该实例中的值时,它都会反映在嵌套的集合中.因此,我被迫创建带有双花括号的新实例初始化.
This lies in a foreach loop with the value of tempName
changing in every iteration.I did this because i couldn't use instances of List<String>
or HashMap<String,List<String>>
because every time i changed the value in that instance it is reflected in the collection it is nested in. So i am forced to create new instances with double brace initialization.
事情是:我想使用列表对象.代替
Thing is: I want to use a list object. Instead of
new ArrayList<String>() {{ add("Y"); add("Upload Success"); }}
我想使用一个变量.
我该怎么做?
推荐答案
代替
new ArrayList<String>() {{ add("Y"); add("Upload Success"); }}
您可以使用
Arrays.asList("Y", "Upload Success")
这将为您提供固定大小的列表.如果希望以后可以添加或删除元素,请将其转换为ArrayList
:
This gives you a fixed-size list. If you want to be able to add or remove elements later, convert it into an ArrayList
:
new ArrayList<>(Arrays.asList("Y", "Upload Success"))
当然,在将其放入地图结构之前,您可以将该列表放入其自己的变量中.
And of course you can put this list into its own variable before putting it into your map structure.
如果您想放置[Y, Upload Success]
或[N, Upload Failed]
并确保列表未在地图条目之间共享,则有以下建议:首先,在循环之外:
If you want to put either [Y, Upload Success]
or [N, Upload Failed]
and make sure the lists aren’t shared between map entries, here’s a suggestion: First, outside your loop:
final List<String> successList = Arrays.asList("Y", "Upload Success");
final List<String> failureList = Arrays.asList("N", "Upload Failed");
然后在循环中
if (wasSuccessful) {
errorList.put(tempName,
Collections.singletonMap("upl", new ArrayList<>(successList)));
} else {
errorList.put(tempName,
Collections.singletonMap("upl", new ArrayList<>(failureList)));
}
您可以将想法更进一步,并在循环之外构建地图.再一次,如果您希望内部地图为HashMap
,只需将其转换为一个:new HashMap<>(Collections.singletonMap("upl", new ArrayList<>(successList)))
.
You may take the idea one step further and build the maps outside the loop. And again, if you want the inner map to be a HashMap
, just convert into one: new HashMap<>(Collections.singletonMap("upl", new ArrayList<>(successList)))
.
我尚未测试代码,希望您能解决打字错误的问题.
I have not tested the code, I hope you can fix if there is a typo.
您注意到,我完全避免了双花括号初始化.虽然简短,但从概念上和性能上来说都有开销.每次您都在创建一个新的匿名子类,我认为这不是必须的.
You notice I have avoided the double brace initialization completely. While it’s brief, it has an overhead both conceptually and performancewise. You are creating a new anonymous subclass each time, which I don’t find warranted.
这篇关于双括号初始化的替代方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!