【问题标题】:Java ArrayList populatingJava ArrayList 填充
【发布时间】:2012-06-25 16:31:26
【问题描述】:

所以我正在创建一种对一组数字进行洗牌的方法,我的想法是创建这些数字的总体。 所以我创建了一个循环,它对数字进行洗牌,然后将其添加到数组列表中,但是经过一些调试语句后,我发现它确实对数字进行了洗牌,但只将最后一次洗牌添加到了数组列表中。谁能帮我弄清楚为什么?

solutionList 是一个数组列表,如果有人想知道的话,代码会更进一步

for(int k =0;k <100; k++){
        Collections.shuffle(solutionList);
        population2.add(new Object[]{solutionList}) ;
        System.out.println("In the loop  " + solutionList);

    }

    for(Object[] row : population2){
        System.out.println("Row = " + Arrays.toString(row));
    }

【问题讨论】:

    标签: java multidimensional-array arraylist


    【解决方案1】:

    population2 的每个元素都是一个数组,其中引用了 same ArrayList。如果您想要不同的列表,则需要为每次迭代创建一个新列表。

    例如,为了避免每次都使用正确的数字填充列表,您可以将solutionList 随机排列,然后添加对副本的引用:

    for (int k = 0; k < 100; k++) {
        Collections.shuffle(solutionList);
        List<Integer> copy = new ArrayList<Integer>(solutionList);
        population2.add(new Object[]{ copy });
    }
    

    【讨论】:

      【解决方案2】:
      population2.add(new Object[]{solutionList}) ;
      

      创建一个包含单个元素的 Object 数组。该元素恰好是一个列表。

      【讨论】:

        【解决方案3】:

        您正在创建 100 个数组,每个数组都包含对同一列表的引用。我认为您想要的是创建 100 个数组,每个数组都包含列表元素的副本:

        for(int k =0;k <100; k++){
            Collections.shuffle(solutionList);
            population2.add(solutionList.toArray()) ;
        }
        

        但我建议完全避免使用数组,并始终使用集合:

        for(int k =0;k <100; k++){
            Collections.shuffle(solutionList);
            population2.add(new ArrayList<Something>(solutionList));
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-07-18
          • 2013-08-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-01-27
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多