【问题标题】:ArrayList add() function overwrites all the elements (processing/java) [duplicate]ArrayList add() 函数覆盖所有元素(处理/java)[重复]
【发布时间】:2019-05-12 21:10:11
【问题描述】:

所以我试图在 for 循环中将相同的 ArrayList(结)洗牌 50 次,并将洗牌后的列表添加到另一个 ArrayList(gen0)。但是每次我添加一个新的 ArrayList 时,它都会将所有现有的 ArrayList 元素覆盖到我刚刚添加的同一个 ArrayList 中,有人可以告诉我为什么吗?

ArrayList<ArrayList> seed(ArrayList<PVector> knots) {

  ArrayList<ArrayList> gen0 = new ArrayList<ArrayList>();
  for(int i=1; i<=50; i++) {

    Collections.shuffle(knots);

    gen0.add(knots);    
  }

  return gen0;
}```

【问题讨论】:

  • 您只是向 gen0 添加了一个对象,即同一个 ArrayList。您需要创建一个新的数组列表 -- gen0.add(new ArrayList(knots)); 才能工作。
  • 工作,非常感谢:)

标签: java arraylist processing shuffle


【解决方案1】:

您每次都在改组对同一 ArrayList 的引用。相反,请考虑在每次迭代时复制ArrayList

ArrayList<PVector> newList = new ArrayList<>(knots); // creates a copy
Collections.shuffle(newList);
gen0.add(newList);

【讨论】:

    猜你喜欢
    • 2012-11-11
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 2011-06-11
    • 1970-01-01
    • 2013-04-20
    • 1970-01-01
    • 2011-01-27
    相关资源
    最近更新 更多