【问题标题】:Create an ArrayList of ArrayList<Integer>创建 ArrayList<Integer> 的 ArrayList
【发布时间】:2012-02-25 17:11:02
【问题描述】:

我正在尝试使用下面的代码来创建多维 ArrayList。我的代码很好地填充了内部 ArrayList(localSolutions),但是当我尝试将该 ArrayList 添加到外部 ArrayList(解决方案)时,出现问题,它会添加空 ArrayLists。

public class MathCapstone {

public static void main(String[] args) {
    ArrayList<ArrayList<Integer>> list = entireList(10);

    for(int q = 0;q<list.size();q++) {
        System.out.println(list.get(q));
    }

public static ArrayList<ArrayList<Integer>> entireList(int max) {
    ArrayList<ArrayList<Integer>> solutions = new ArrayList<ArrayList<Integer>>();
    ArrayList<Integer> localSolutions = new ArrayList<Integer>();

    for(int i = 1; i <= max; i++) {
        for(int j = 1; j < i; j++) {
           //System.out.println(j + "mod" + i + "=" + (j*j)%i);
            if ((j*j)%i == 1) {
                localSolutions.add(j);
            }
        }
        //System.out.println(localSolutions.toString());
        solutions.add(localSolutions);
        localSolutions.clear();
    }
    return solutions;
}

最后一点:使用 ArrayLists 的 HashMap 会更好吗(最终我将创建 CDF 的最大值约为 10k)?

【问题讨论】:

  • 如果您要使用的索引都是介于 0 和某个值之间的数字,则使用 HashMap&lt;Integer, Whatever&gt; 与 ArrayList&lt;Whatever&gt; 相比没有任何好处,并且您会损失一点性能。如果您需要非整数键,或者索引的分布很稀疏,则 HashMap 会更好。
  • 也可以考虑List&lt;List&lt;Integer&gt;&gt; solutions = new ArrayList&lt;List&lt;Integer&gt;&gt;()。
  • @aclear16 我拒绝了您对我的回答的编辑,因为我所做的是故意的,并且是修复的一部分。请不要在没有充分理由(例如测试代码更改)的情况下更改其他用户答案的​​语义——如果您认为自己发现了一个错误,最好在不确定时添加评论。

标签: java multidimensional-array arraylist


【解决方案1】:

您正在清除 localSolutions 列表。

在 Java 中,您仅按值复制对 Object 的引用,而不是实际的对象本身。因此,当您在 solutions 列表中添加 localSolutions 列表时,localSolutions 引用和 solutions 的第一个条目> 列表,指向同一个对象。

因此,当您清除 localSolutions 列表时,您实际上清除了 solutions 列表中的第一个条目。

【讨论】:

    【解决方案2】:

    你在做:

    localSolutions.clear();
    

    将列表添加到另一个列表不会添加列表的副本,它会添加相同的列表对象。您的代码在外循环中所做的是用元素填充相同的列表,将其清空,然后将其添加到solutions。 solutions 包含 max 对同一个空列表的引用。

    你想做的是:

    ArrayList<ArrayList<Integer>> solutions = new ArrayList<ArrayList<Integer>>();
    for(int i = 1; i <= max; i++) {
        ArrayList<Integer> localSolutions = new ArrayList<Integer>();
        for(int j = 1; j < i; j++) {
           //System.out.println(j + "mod" + i + "=" + (j*j)%i);
            if ((j*j)%i == 1) {
                localSolutions.add(j);
            }
        }
        //System.out.println(localSolutions.toString());
        solutions.add(localSolutions);
    }
    

    【讨论】:

      猜你喜欢
      • 2021-11-20
      • 1970-01-01
      • 2013-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-05
      • 1970-01-01
      相关资源
      最近更新 更多