无法将元素添加到arraylist

时间:2016-05-24 00:10:32

标签: java arraylist

 public static ArrayList<ArrayList<Integer>> powerSet(ArrayList<Integer> originalList) {
       ArrayList<ArrayList<Integer>> sets = new ArrayList<>();

        ArrayList<Integer> list = new ArrayList<Integer>(originalList);
        int p=2;
            ArrayList<Integer> st=new ArrayList<>();
        while(p<=originalList.size())
        {
            for(int i=0;i<=originalList.size()-p;i++)
            {
            for(int j=0;j<p;j++)
            {
              st.add(list.get(i+j));  
            }
            sets.add(st);//  sets recieves a st that is empty which is not the case
            Iterator it=st.iterator();
                System.out.print("adding it to our sets  ");
            while(it.hasNext())
                    System.out.print(it.next()+" ");// prints the elements contained inside and proves that st is not empty
                System.out.println("");
            st.clear();
            }
            p+=1;
        }
        return sets;
    }

我创建了上面的函数来返回列表中连续元素的powerset,每个集合的大小都大于2.但由于某些未知问题,列表'st'无法添加到arraylists'集'的arraylist中虽然arraylist'st'打印得很好。

3 个答案:

答案 0 :(得分:1)

问题是由行sets.add(st);后跟调用&#39; st.clear()&#39;引起的。由于Java通过引用传递对象,sets包含确切的对象st。这意味着对st的任何后续更改都将更改sets的内容。要避免此问题,请先将st复制到新对象,然后再将其添加到sets。尝试用{替换sets.add(st); sets.add(new ArrayList<Integer>(st));

答案 1 :(得分:0)

试试这个......

public static ArrayList<ArrayList<Integer>> powerSet(ArrayList<Integer> originalList) {
    ArrayList<ArrayList<Integer>> sets = new ArrayList<>();
    int p=2;
    while(p<=originalList.size()) {
        for(int i=0;i<=originalList.size()-p;i++) {
            ArrayList<Integer> st=new ArrayList<>();
            for(int j=0;j<p;j++) {
                st.add(list.get(i+j));
             } sets.add(st);
            Iterator it=st.iterator();
            System.out.print("adding it to our sets ");
            while(it.hasNext())
                System.out.print(it.next()+" ");
            System.out.println("");
        }
       p++;
    }
    return sets;
}

答案 2 :(得分:0)

我会这样实现:

public static ArrayList< ArrayList<Integer> > powerSet( ArrayList<Integer> originalList ) {
   ArrayList< ArrayList<Integer> > sets = new ArrayList<>();

    int p=2;
    while( p <= originalList.size() ){
        ArrayList<Integer> st;  

        for( int i=0 ; i<=originalList.size()-p ; i++ ){
        for( int j=0;j<p;j++ ){
          st = new ArrayList();
          st.add( originalList.get(i+j) );  
        }

        sets.add(st);//  sets recieves a st that is empty which is not the case
        Iterator it=st.iterator();
        System.out.print("adding it to our sets  ");

        while( it.hasNext() )
                System.out.print(it.next()+" ");// prints the elements contained inside and proves that st is not empty
            System.out.println("");
        st.clear();
        }
        p+=1;
    }
    return sets;
}