【问题标题】:Adding elements to arrays with different names using a loop使用循环将元素添加到具有不同名称的数组
【发布时间】:2014-09-10 20:46:01
【问题描述】:

我有以下 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 循环来做到这一点?我目前的方法似乎效率低下。

【问题讨论】:

  • 等等为什么你想这样做?
  • 添加为空的HashMap效率低

标签: java arrays loops hashmap


【解决方案1】:

试试这样的。没测试过。

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

【讨论】:

    【解决方案2】:

    就效率而言,像您发布的展开循环将比任何循环构造更快。如果您对简洁性更感兴趣并且有两个以上的变量,则可以考虑声明 ArrayListList&lt;Map&lt;Integer, Integer&gt;&gt; 而不是单独的变量。我还建议您 program to an interface(将所有变量声明为接口类型 [例如,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&lt;Map&lt;Integer, Integer&gt;&gt;,但仍想消除单个变量,则将外部结构声明为 Map&lt;String, List&lt;Map&lt;Integer, Integer&gt;&gt; 并按名称添加元素。但这些都不会让事情变得更高效,只是(也许)更容易编程。

    【讨论】:

    • 谢谢 Ted,我会试试这个并回复你。
    猜你喜欢
    • 2023-03-02
    • 2019-12-12
    • 2019-03-31
    • 1970-01-01
    • 1970-01-01
    • 2012-09-29
    • 1970-01-01
    • 2018-01-27
    相关资源
    最近更新 更多