2013-10-02 86 views
2

我想写一个Java中的程序,将计算一个整数数组(包含5个元素)中的元素的所有组合,并将这些组合输出到一个ArrayList。我已经在下面包含了我的代码。Java:麻烦添加项目ArrayList <ArrayList <Integer>>

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

尝试将每个组合保存到“主”ArrayList时出现问题。如果您运行下面的代码,printf函数将显示组合构建正确。但是,一旦我要求它被“添加”到“主”,它似乎不会被追加到“主”的末尾。相反,所有“主人”都被刚刚构建的组合的副本覆盖。因此,例如,如果我在[1,2,3,4,5]上调用函数,那么我的“主”数组最终会成为[副本1,2,3,4,5]的31个副本(其中,第31组合被发现)。

我想这与使用嵌套数组列表有关,还有更好的方法来实现我想要的。但是我也犯了一些其他的新手错误。清楚了()method.from为loop.after每次迭代明确()从ArrayList中移除 值

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); 
    } 
} 

回答

1

移动循环

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); 
    } 
} 
+0

谢谢!并感谢大家的答案,现在它可以工作,并且我明白我做错了什么。 – lexipenia

0

删除把你的ArrayList创建里面的。

+0

没有,清晰是必须的。在循环内用新的替换清除。 – Aubin

0

内的新举措的writeitem建设中的for循环。你不想重新使用相同的数组。

0

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

master.add(writeitem.clone()); 
+0

否,克隆返回此LinkedList的浅表副本。 – Aubin

0

你得到31份的原因是因为你通过for循环运行,擦writeitem阵列每次清洗,加入到它,并打印出来,同时仍然在for循环,这然后重复30次以上,直到我打32

删除writeitem.clear();,看你怎么得到与

+0

不,下一个循环继续添加到先前分配的列表中... – Aubin

+0

谢谢。这澄清了我的错误。我没有意识到,一旦“writeitem”输出到“master”,它仍然被称为“writeitem”WITHIN“master”,并且每次都进行修改。 – lexipenia

相关问题