forEachRemaining
ArrayList<Integer> arrayList=new ArrayList<>(); for (int i = 0; i <10; i++) { arrayList.add(i); } System.out.println("迭代器第一次遍历"); Iterator iterator=arrayList.iterator(); while(iterator.hasNext()){ System.out.print(iterator.next()); } System.out.println(""); System.out.println("迭代器第二次遍历"); Iterator iterator0=arrayList.iterator(); while(iterator.hasNext()){ System.out.print(iterator0.next()); }
上面迭代器只能遍历一次,第二次遍历时里面已经没有了元素,就不遍历了
二:
ArrayList<Integer> arrayList=new ArrayList<>(); for (int i = 0; i <10; i++) { arrayList.add(i); } System.out.println("迭代器第一次遍历"); Iterator<Integer> iterator=arrayList.iterator(); while(iterator.hasNext()){ int num=iterator.next(); System.out.print(num); if(num==5){ break; } } System.out.println(""); System.out.println("输出其余元素:"); iterator.forEachRemaining(new Consumer<Integer>() { @Override public void accept(Integer s) { System.out.print(s); } });
forEachRemaining继续输出其余的元素
一点点学习,一丝丝进步。不懈怠,才不会被时代淘汰