Collection的迭代器Iterator


 Collection -- 迭代的方法
   toArray()
   iterator()
 迭代器的作用:抓取集合中的元素

 迭代器的方法有
   hasNext()

   next()

  remove()

public static void main(String[] args) {
        Collection c = new ArrayList();// ArrarList是实现Collection接口的一个类
        c.add("海子");
        c.add("王小波");
        c.add("龙应台");

        // 遍历元素
        // 方式一 toArray()
        Object[] arr = c.toArray();
        System.out.print("toArray: ");
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();

        // 方式二 iterator()
        Iterator it = c.iterator();
        System.out.print("iterator: ");
        while (it.hasNext()) {
            System.out.print(it.next() + "  ");
        }
        System.out.println();
        
        //remove()
        c.remove("海子");
        System.out.println("是否删除元素成功? " + c.remove("JK"));
        System.out.println("元素 :" + c);

    }



原文地址:https://www.cnblogs.com/shadowdoor/p/6803769.html