繁体   English   中英

Java:将项目添加到ArrayList时遇到麻烦 <ArrayList<Integer> &gt;

[英]Java: trouble adding items to ArrayList<ArrayList<Integer>>

我正在尝试用Java编写一个程序,该程序将计算整数数组(包含5个元素)中元素的所有组合,并将这些组合输出到ArrayList。 我在下面包含了我的代码。

我使用按位运算来查找组合。 每个组合都构造为ArrayList(Integer),称为“ writeitem”。 然后,我想将它们存储在另一个名为“ master”的ArrayList中,该数组必须具有ArrayList(ArrayList(Integer))的形式。 [出于格式化原因,必须将<>替换为(); 他们否则不会出现...]

尝试将每个组合保存到“主” ArrayList时出现问题。 如果运行下面的代码,printf函数将显示该组合的构造正确。 但是,一旦我要求将其“添加”到“母版”,它似乎就不会附加到“母版”的末尾。 而是,所有“主”都被刚刚构造的组合的i个副本覆盖。

因此,例如,如果我在[1,2,3,4,5]上调用该函数,那么我的“主”数组最终将是[1,2,3,4,5]的31个副本(第31个组合被发现)。

我想这与使用嵌套数组列表有关,并且有一种实现我想要的更好的方法。 但是同样有可能我犯了其他一些新手错误。

static ArrayList<ArrayList<Integer>> master = new ArrayList<ArrayList<Integer>>();
public static void generatecombs(int[] x){

    ArrayList<Integer> writeitem = new ArrayList<Integer>(); //empty list to construct each comb

    for(int i=1;i<32;i++){

        writeitem.clear(); //clear before constructing next combination

        if((i & 1)>0){          //check if each element is present in combination
            writeitem.add(x[0]);
        }
        if((i & 2)>0){
            writeitem.add(x[1]);
        }
        if((i & 4)>0){
            writeitem.add(x[2]);
        }
        if((i & 8)>0){
            writeitem.add(x[3]);
        }
        if((i & 16)>0){
            writeitem.add(x[4]);
        }

        System.out.printf("The %dth combination is %s\n", i,writeitem);
        master.add(writeitem); //output constructed element
        System.out.printf("The collection so far is: %s\n", master);
    }
}

在循环内移动新的

static ArrayList<ArrayList<Integer>> master = new ArrayList<ArrayList<Integer>>();

public static void generatecombs(int[] x){

    for(int i=1;i<32;i++){

        ArrayList<Integer> writeitem = new ArrayList<Integer>(); // new list to construct each comb
        if((i & 1)>0){          //check if each element is present in combination
            writeitem.add(x[0]);
        }
        if((i & 2)>0){
            writeitem.add(x[1]);
        }
        if((i & 4)>0){
            writeitem.add(x[2]);
        }
        if((i & 8)>0){
            writeitem.add(x[3]);
        }
        if((i & 16)>0){
            writeitem.add(x[4]);
        }

        System.out.printf("The %dth combination is %s\n", i,writeitem);
        master.add(writeitem); //output constructed element
        System.out.printf("The collection so far is: %s\n", master);
    }
}

每次迭代后,clear()从arraylist中删除值,然后在其中进行arraylist创建。

在for循环内移动writeitem的构造。 您不想重复使用相同的数组。

另一种解决方案是在清除writeItem之前将其添加到父列表时进行克隆。

master.add(writeitem.clone()); 

获得31份副本的原因是因为您正在遍历for循环,每次将writeitem数组擦拭干净,添加到其中,然后在仍处于for循环中将其打印出来,然后重复执行30次,直到我打32。

删除writeitem.clear(); 看看你如何继续

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM