List remove注意点

时间:2023-03-08 17:02:26
public class ListTest {

    public static void main(String[] args) {
// TODO Auto-generated method stub
List<String> ll = new ArrayList<String>();
ll.add("1");
ll.add("2");
ll.add("3"); for(String str : ll ){
if(str.endsWith("2")){
ll.remove(str);
}
} } } public class ListTest { public static void main(String[] args) {
// TODO Auto-generated method stub
List<String> ll = new ArrayList<String>();
ll.add("1");
ll.add("2");
ll.add("3"); for(String str : ll ){
if(str.endsWith("3")){
ll.remove(str);
}
} } }
public class ListTest {

    public static void main(String[] args) {
// TODO Auto-generated method stub
List<String> ll = new ArrayList<String>();
ll.add("1");
ll.add("2");
ll.add("3"); for (Iterator it = ll.iterator(); it.hasNext();) {
String str = (String)it.next();
if(str.equals("3")){
it.remove();
System.out.println(it);
}else{
System.out.println(it);
}
} System.out.println("end");
} }

用迭代器就不会有问题:

原因:for是通过指针去判断,如果最后的元素删掉了,那么久没办法判断是否是list结束点了

迭代器的的hasNext()是通过数值判断

public boolean hasNext() {
return cursor != size();
} public E next() {
checkForComodification();
try {
E next = get(cursor);
lastRet = cursor++;
return next;
} catch (IndexOutOfBoundsException e) {
checkForComodification();
throw new NoSuchElementException();
}
}