[英]Java adding ArrayList<Integer> to ArrayList<ArrayList<Integer>> replaces all elements of the ArrayList of ArrayLists
[英]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.