[英]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.