我有一个Integer arraylist。我想在每个中清除它然后再填充它。我的代码是:
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,所以我想要数字数组列表所以这个=&gt;
[[1,2,4,1,2,4][1, 3, 2, 6, 4, 5]...]
但是数字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]]
请帮帮我:(
答案 0 :(得分: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);
}
将sublist
添加到number
后,您需要添加参考; sublist
未已复制。如果您只是致电sublist.clear()
,则每次都会向number
添加一个空列表。
答案 1 :(得分: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);
}
答案 2 :(得分: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);
}