zoukankan      html  css  js  c++  java
  • List remove注意点

    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();  
        }  
    }  
  • 相关阅读:
    【Uva 10618】Tango Tango Insurrection
    Scripting web services
    防止SQL注入式攻击的笔记
    Net中的Request和Response对象的理解
    Net中的Request和Response对象的理解
    Net中的Request和Response对象的理解
    UEditor编辑器第一次赋值失败的解决方法
    我不问+你不说
    我不问+你不说
    我不问+你不说
  • 原文地址:https://www.cnblogs.com/huhuuu/p/5716257.html
Copyright © 2011-2022 走看看