62,614
社区成员
发帖
与我相关
我的任务
分享
public void sayhello()
{
ArrayList<Integer> list=new ArrayList<Integer>();
list.add(2);
list.add(3);
list.add(2);
for(int a:list)
{
list.remove(2);
}
}
public class Hello {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
Collections.addAll(list, "a,b,c,d,e,f".split(","));
for (String string : list) {
if (string.equals("d")) {
list.remove(string);
break;
}
}
for (int i = 0; i < list.size(); i++) {
String string = list.get(i);
if (string.equals("b")) {
list.remove(string);
}
}
}
}
for (int a : list) {
list.remove(2);
}
这个写法本身就是有问题的。
①、如果想要保持你的操作而不报错请加上这样一个判断
for (int a : list) {
if (a == 2) list.remove(2);
}
②、list.remove(2);会将2当数组下标也就是说会删除list的第三个元素,而你的list本身只有3个元素,所以for执行到二次的时候就会抛出IndexOutOfBoundException。要删除元属请使用list.remove(new Integer(2));
③、如果要达到预期的效果也就是删除list中所有的2可以使用
while (list.contains(new Integer(2))) {
list.remove(new Integer(2));
}