zoukankan      html  css  js  c++  java
  • 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]);
            }
        }
    }
  • 相关阅读:
    解决Cannot change version of project facet Dynamic web module to 3.0
    mysql 存储过程
    查看建表语句
    mysql query cache 查询缓存
    数据库连接池
    JDBC Statement PrepareStatement
    mysql 改变表结构 alter
    maven 获取pom.xml的依赖---即仓库搜索服务
    windows常用快捷键
    oracle 的数据完整性
  • 原文地址:https://www.cnblogs.com/longesang/p/11264313.html
Copyright © 2011-2022 走看看