29.2 Iterator 迭代器

/*

* 集合的遍历方式:
* 1.toArray(),可以把集合转换成数组,然后遍历数组即可
* 2.iterator(),可以返回一个迭代器对象,我们可以通过迭代器对象来迭代集合
*
* Iterator:可以用于遍历集合
* E next() :返回下一个元素
* boolean hasNext() :判断是否有元素可以获取
*
* 注意:Exception in thread "main" java.util.NoSuchElementException
* 使用next方法获取下一个元素,如果没有元素可以获取,则出现NoSuchElementException

*/

public class IteratorDemo_迭代器 {
    public static void main(String[] args) {
//        toArrayMethod();
        iteratorMethod();


    }

    private static void iteratorMethod() {
        //创建集合对象
        Collection c = new ArrayList();
        //添加元素
        c.add("hello");
        c.add("world");
        c.add("java");

        Iterator it = c.iterator();
//        System.out.println(it.next());
//        System.out.println(it.next());
//        System.out.println(it.next());
//        System.out.println(it.next()); //如果没有元素可以获取,则出现NoSuchElementException

        while (it.hasNext()) {
            System.out.println(it.next());
        }
    }

    private static void toArrayMethod() {
        //创建集合对象
        Collection c = new ArrayList();
        //添加元素
        c.add("hello");
        c.add("world");
        c.add("java");

        Object[] obj = c.toArray();
        for(int i=0;i<obj.length;i++) {
            System.out.println(obj[i]);
        }
    }
}
原文地址:https://www.cnblogs.com/longesang/p/11264313.html