[英]Adding elements to arrays with different names using a loop
我有以下ArrayLists。
ArrayList<HashMap<Integer, Integer>> RP1 = new ArrayList<HashMap<Integer, Integer>>();
ArrayList<HashMap<Integer, Integer>> RP2 = new ArrayList<HashMap<Integer, Integer>();
我想在循环中向每个ArrayList添加一个HashMap。 目前,我正在像这样添加它们:
RP1.add(new HashMap<Integer, Integer>());
RP1.add(new HashMap<Integer, Integer>());
RP2.add(new HashMap<Integer, Integer>());
RP2.add(new HashMap<Integer, Integer>());
有没有办法用for循环来做到这一点? 我当前的方法似乎效率低下。
就效率而言,像您发布的展开循环将比任何循环构造都快。 如果您对简洁性更感兴趣并且具有两个以上的变量,则可以考虑声明List<Map<Integer, Integer>>
的ArrayList
而不是单独的变量。 我还建议您对接口进行编程 (将所有变量声明为接口类型[例如, List
]而不是实现类型[ ArrayList
]):
List<List<Map<Integer, Integer>>> RPs = new ArrayList<>();
for (int i = 0; i < NUMBER_OF_ARRAYLISTS; i++) {
List<Map<Integer, Integer>> list = new ArrayList<>();
for (int j = 0; j < NUMBER_OF_MAPS_PER_LIST; j++) {
list.add(new HashMap<Integer, Integer>());
}
RPs.add(list);
}
如果确实需要按名称访问每个List<Map<Integer, Integer>>
,但仍要消除各个变量,则将外部结构声明为Map<String, List<Map<Integer, Integer>>
并添加以这种方式命名元素。 但是,这一切都不会使事情变得更有效率,只是(也许)易于编程。
尝试这样的事情。 没有测试。
example(RP1,RP2);
/* or example(RP1,RP1,RP2,RP2) */
public static void example(ArrayList<HashMap<Integer, Integer>> ... arrays){
for (int i = 0; i < arrays.length; i++)
arrays[i].add(new HashMap<Integer, Integer>());
}
更多信息: https : //today.java.net/article/2004/04/13/java-tech-using-variable-arguments
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.