-1

我有一个整数数组列表。我想在每个 for 中清除它,然后再次填充它。我的代码是:

private static int myMethod(int prim){

    ArrayList<ArrayList<Integer>> number = new ArrayList<ArrayList<Integer>>();
    ArrayList<Integer> sublist = new ArrayList<Integer>();
    ArrayList<Integer> temp = new ArrayList<Integer>();

    for (int x = 2; x < prim; x++ ){

        for (int power = 0; power < prim - 1; power++){ 
            // in this loop sublist 
            //will be fill
            int i=(int)((Math.pow(x, power))%prim);
            sublist.add(i);     
        }

        number.add(sublist);

    }
}

prim 是例如 7,所以我想要数字数组列表,所以这个 =>

[[1,2,4,1,2,4][1, 3, 2, 6, 4, 5]...] 

但是 number arraylist 具有这种形式:

[[1,2,4,1,2,4,1, 3, 2, 6, 4, 5][1,2,4,1,2,4,1, 3, 2, 6, 4, 5]]

请帮我 :(

4

3 回答 3

3

你不能只是清除sublist;您必须sublist每次通过循环创建一个新的。

for (int x=2;x<prim;x++ ){
    sublist = new ArrayList<Integer>();
    for (int power=0;power<prim-1;power++){ // in this loop sublist //will be fill
        int i=(int)((Math.pow(x, power))%prim);
        sublist.add(i);     
    }

    number.add(sublist);

}

添加sublistnumber时,添加参考sublist不被复制。如果您只是调用,则每次都sublist.clear()将添加一个空列表。number

于 2013-01-31T18:05:23.780 回答
0

在 for 循环中创建列表...

ArrayList<ArrayList<Integer>>  number=new ArrayList<ArrayList<Integer>>();
       for (int x=2;x<prim;x++ ){
    // create sublist rather than outside the loop
    ArrayList<Integer> sublist = new ArrayList<Integer>();
            for (int power=0;power<prim-1;power++){ // in this loop sublist //will be fill
                int i=(int)((Math.pow(x, power))%prim);
                sublist.add(i);     
            }

            number.add(sublist);

            }
于 2013-01-31T18:05:32.033 回答
0
ArrayList<ArrayList<Integer>>  number=new ArrayList<ArrayList<Integer>>();
    ArrayList<Integer> sublist=null;
    ArrayList<Integer> temp=new ArrayList<Integer>();

    for (int x=2;x<prim;x++ ){
     sublist=new ArrayList<Integer>();
        for (int power=0;power<prim-1;power++){ // in this loop sublist //will be fill
             int i=(int)((Math.pow(x, power))%prim);
            sublist.add(i);     
        }

        number.add(sublist);

        }
于 2013-01-31T18:06:16.087 回答