java 迭代器iterator

对于如ArrayList<E>类的数据,常用iterator遍历。

    ArrayList<String> list = new ArrayList<String>();
        list.add("1");
        list.add("2");
        list.add("3");
        Iterator<String> iterator = list.iterator();
        for(;iterator.hasNext();){
            String aString = iterator.next();
            System.out.println(aString);
            if(aString=="1"){
                iterator.remove();
            }
        }
        iterator = list.iterator();
        for(;iterator.hasNext();){
            String aString = iterator.next();
            System.out.println(aString);
        }

注意的是:

    /**
     * Returns an iterator over the elements in this list in proper sequence.
     *
     * <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
     *
     * @return an iterator over the elements in this list in proper sequence
     */
    public Iterator<E> iterator() {
        return new Itr();
    }

 

posted @ 2016-11-21 00:24  微风&细雨  阅读(291)  评论(0编辑  收藏  举报