11. java.util.Iterator

来源:互联网 发布:500px知乎什么意思 编辑:程序博客网 时间:2024/05/24 02:27
官方所有的方法,下面的代码是方法实现:default void    forEachRemaining(Consumer<? super E> action)Performs the given action for each remaining element until all elements have been processed or the action throws an exception.boolean     hasNext()Returns true if the iteration has more elements.E   next()Returns the next element in the iteration.default void    remove()Removes from the underlying collection the last element returned by this iterator (optional operation).
import java.util.ArrayList;import java.util.Collection;import java.util.Iterator;public class LianXi {    public static void main(String[] args) throws Exception {        t_1();    }    public static void t_1() {        Collection c_1 = new ArrayList();        c_1.add(9);        c_1.add(2);        c_1.add(6);        c_1.add(5);        c_1.add(3);        c_1.add(8);        c_1.add(4);        Iterator i_1 = c_1.iterator();//        i_1.forEachRemaining(s -> System.out.print(((int)s)*2 + " "));        /*        forEachRemaining方法是Java 8为Iterator新增的默认方法,该方法可使用Lambda表达式来遍历集合元素。        迭代器是读取下一个元素,上面的循环已经读取完的元素,下面的就不会读取到,所以先把它注释掉了         */        if (i_1.hasNext()) {            System.out.print(i_1.next() + " ");         // 9        }        System.out.println();        for (c_1.iterator(); i_1.hasNext(); ) {            System.out.print(i_1.next() + " ");         // 2            if ((int)i_1.next() == 6) {                break;            }        }        System.out.println();        for (c_1.iterator(); i_1.hasNext(); ) {            System.out.print(i_1.next() + " ");         // 5            if ((int)i_1.next() == 3) {                break;            }        }        System.out.println();        if ((int)i_1.next() == 8) {            i_1.remove();        }        while (i_1.hasNext()) {            System.out.print(i_1.next() + " ");         // 4        }    }}
原创粉丝点击