[英]Remove an int from ArrayList<Integer> using index but treated as Object java
I am trying to remove an int from an ArrayList containing [9, 0, 0, 6, 2, 3, 0, 0, 0] using the following code 我正在尝试使用以下代码从包含[9,0,0,6,2,2,3,0,0,0]的ArrayList中删除一个int
static void appendRow(ArrayList<ArrayList<Integer>> ans) {
int ind = 0;
while(yolo.size() < 81) {
for(int x = 0; x < ans.size(); x++) {
ArrayList<Integer> an = ans.get(x);
for(int i = ind; i < ind+3; i++) {
yolo.add(an.get(i));
}
for(int y = 0; y < 3; y++) {
an.remove(y);
}
}
ind+=3;
}
System.out.println(yolo);
}
What happened here is that after I add the first 3 ints from ans, I will delete them. 这里发生的是,当我从ans中添加前三个int之后,将删除它们。 There are more than one items that will be passed into the appendRow function but I only need the first three and the next function only needs the rest (ie [6, 2, 3, 0, 0, 0]). 将有多个项传递到appendRow函数中,但我只需要前三个,而下一个函数仅需要其余项(即[6,2,3,0,0,0])。
The problem is that when y = 2, an.remove(y) does not remove the 0 with index of 2, instead it removes 2 so the list becomes [0, 6, 3, 0, 0, 0], which is totally wrong. 问题是,当y = 2时,an.remove(y)不会删除索引为2的0,而是会删除2,因此列表变为[0,6,3,0,0,0],这完全是错误。
Reverse the direction of your for
loop. 反转您的for
循环的方向。 Change 更改
for (int y = 0; y < 3; y++) {
an.remove(y);
}
to something like 像
for (int y = 2; y >= 0; y--) {
an.remove(y);
}
or something like 或类似的东西
for (int y = 0; y < 3; y++) {
an.remove(0);
}
because when your remove the first element the second element is now what was the third. 因为当您删除第一个元素时,第二个元素现在是第三个元素。 That is 9, 0, 0, 6, 2, 3, 0, 0, 0
becomes 0, 0, 6, 2, 3, 0, 0, 0
then 0, 6, 2, 3, 0, 0, 0
and then your reported 0, 6, 3, 0, 0, 0
(which is exactly what you told it to do). 即9, 0, 0, 6, 2, 3, 0, 0, 0
变为0, 0, 6, 2, 3, 0, 0, 0
然后0, 6, 2, 3, 0, 0, 0
和然后您报告的0, 6, 3, 0, 0, 0
(这正是您要求它执行的操作)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.