关于java:Day13-Iterator接口

第二章 Iterator迭代器

public class Demo01 {
    public static void main(String[] args) {
    //应用多态办法 创建对象
       Collection<String> nb= new ArrayList<String>();
       //元素
        nb.add("吃屁");
        nb.add("吃");
        nb.add("牛逼");
        //应用迭代器
        Iterator<String> it = nb.iterator();
        while (it.hasNext()){
            String s = it.next();//获取元素
            System.out.println(s);

在进行汇合元素取出时,如果汇合中曾经没有元素了,还持续应用迭代器的next办法,将会产生java.util.NoSuchElementException没有汇合元素的谬误。

2.2加强for循环

它的外部原理其实是个Iterator迭代器,所以在遍历的过程中,不能对汇合中的元素进行增删操作

for(元素数据类型 变量 Collection汇合or数组){
              //代码
}

遍历数组

public class Demo2 {
    public static void main(String[] args) {
        int[] arr = {3,5,6,87};
           //应用加强for遍历数组
        for(int a : arr){//a代表数组中的每个元素
            System.out.println(a);
        }
    }
}

遍历汇合=

public class Demo03 {
    public static void main(String[] args) {        
        Collection<String> coll = new ArrayList<String>();
        coll.add("小河神");
        coll.add("老河神");
        coll.add("神婆");
        //应用加强for遍历
        for(String s :coll){//接管变量s代表 代表被遍历到的汇合元素
            System.out.println(s);
        }
    }
}

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理