Debug跟踪后发现,原来,集合删除元素时,集合的size会变小,连带索引都会改变!
这可怎么办?我不会被这样一个小问题搞得没辙了吧!
方法一:用传统for循环,从集合最后元素向前循环删除元素,集合的size会变小,连带索引都会改变,但不会影响到前面的未循环元素。
ArrayList a=new ArrayList(15);
a.add(222);
a.add(3);
a.add(333);
a.add(000);
a.add(333);
a.add(4);
for(int s=a.size()-1;s>=0;s--){
if(a.get(s).intValue()==333){
a.remove(s);
}
}
方法二:使用Iterator的remove()方法删除集合中的元素
查看JDK手册的Iterator接口,看到它还有一个remove方法。
remove
void remove()
从迭代器指向的 collection 中移除迭代器返回的最后一个元素(可选操作)。每次调用 next 只能调用一次此方法。如果进行迭代时用调用此方法之外的其他方式修改了该迭代器所指向的 collection,则迭代器的行为是不确定的。
抛出:
UnsupportedOperationException - 如果迭代器不支持 remove 操作。
IllegalStateException - 如果尚未调用 next 方法,或者在上一次调用 next 方法之后已经调用了 remove 方法。
/**
*@paramsource
*@paramblackNameList
*/
privatevoid screenBlackNameList(List source, List blackNameList){
Iterator sourceIt=source.iterator();
while(sourceIt.hasNext()){
SharedBoardSmsWrapper tmpSharedBoardSmsWrapper=sourceIt.next();
Iterator blackNameListIt=blackNameList.iterator();
while(blackNameListIt.hasNext()){
BlackNameListModel tmpBlackNameListModel=blackNameListIt.next();
if(tmpSharedBoardSmsWrapper.getSource().equals(tmpBlackNameListModel.getSource())){
sourceIt.remove();
break;
}
}
}
}
/** *@paramsource *@paramblackNameList */ privatevoid screenBlackNameList(List source, List blackNameList){ Iterator sourceIt=source.iterator(); while(sourceIt.hasNext()){ SharedBoardSmsWrapper tmpSharedBoardSmsWrapper=sourceIt.next(); Iterator blackNameListIt=blackNameList.iterator(); while(blackNameListIt.hasNext()){ BlackNameListModel tmpBlackNameListModel=blackNameListIt.next(); if(tmpSharedBoardSmsWrapper.getSource().equals(tmpBlackNameListModel.getSource())){ sourceIt.remove(); break; } } } }
注意,一次Iterator的next()方法,不能多次调用remove()方法。否则会抛出异常。
42/4<1234>