【问题标题】:Looped elements ArrayList of ArrayLists elements being changed to last looped value循环元素 ArrayLists 元素的 ArrayList 被更改为最后一个循环值
【发布时间】:2015-01-13 15:47:37
【问题描述】:

我无法弄清楚为什么作为 ArrayList 的 ArrayList 的“ALofcompoundedPrimeAL”中的每个元素都以相同的元素结束。因此,虽然 ArrayList "theNewPrimeFactorsAL" 看起来是正确的,但 for 循环的每次迭代似乎都会将 ALofcompoundedPrimeAL 的所有元素更改为最新迭代的元素;也就是说 ALofcompoundedPrimeAL 没有索引唯一元素,而是将每个元素更改为最后一次循环迭代的值。另外,我会使用正确的工具来存储套装吗?重要的是,我可以计算每次迭代的素因子数量,因此不能只用可能的新素因子创建一个新集合。

我发现了这个:link,它显然有效,但似乎无法让循环不更新 ALofcompoundedPrimeAL 中的每个元素成为最后一次迭代的值。

public ArrayList<ArrayList<Integer>> CompoundDivisors(
        ArrayList<Set<Integer>> SetofallPrimeFactorsAL) {

    Set<Integer> PrimeFactorsSET;
    ArrayList<Integer> theNewPrimeFactorsAL = new ArrayList<Integer>();
    ArrayList<ArrayList<Integer>> ALofcompoundedPrimeAL = new ArrayList<ArrayList<Integer>>();

    ArrayList<Integer> thePrimeFactorsAL;
    for (int k = 0; k < SetofallPrimeFactorsAL.size(); k++) {
        PrimeFactorsSET = SetofallPrimeFactorsAL.get(k);
        // PrimeFactorsAL takes the set of Prime Factors (in
        // PrimeFactorsSET) and outputs an arraylist of them.
        thePrimeFactorsAL = new ArrayList<Integer>(PrimeFactorsSET);
        // theNewPrimeFactorsAL.addAll just adds all of the new elements to
        // the theNewPrimeFactorsAL ArrayList.
        theNewPrimeFactorsAL.addAll(thePrimeFactorsAL);
        // ALofcompoundedPrimeAL is supposed to add theNewPrimeFactorsAL to
        // each index.
        ALofcompoundedPrimeAL.add(theNewPrimeFactorsAL);
    }
    return (ALofcompoundedPrimeAL);
}

感谢您的任何见解。

【问题讨论】:

  • 这是什么语言?
  • 看起来像 Java。我添加了“java”标签。

标签: java arraylist multidimensional-array


【解决方案1】:

您似乎只是在复制引用。例如,在您将theNewPrimeFactorsAL 添加到ALofcompoundedPrimeAL 之后,您在下一个循环中继续到addAll 到相同的theNewPrimeFactorsAL。最后,ALofcompoundedPrimeAL 包含 n 对同一 theNewPrimeFactorsAL 的引用,它包含在循环的任何迭代中添加到它的所有元素。

您需要创建新列表才能拥有新列表。

【讨论】:

    猜你喜欢
    • 2019-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-19
    • 2016-02-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多