集合的3种遍历方式

来源:互联网 发布:c语言中exit 0 编辑:程序博客网 时间:2024/05/23 12:37
List<String> books = new ArrayList<String>();
        books.add("疯狂java讲义");
        books.add("疯狂android讲义");
        books.add("疯狂xml讲义");
        
        //设置list的元素值
        books.set(1, "天龙八部");
        //三种遍历方式
        
        //采用foreach遍历
        System.out.println("采用foreach遍历:");
        for (String str:books)
        {
            System.out.println(str);
        }
        
        //采用for循环遍历
        System.out.println("采用for循环遍历:");
        for (int i = 0; i < books.size(); i++)
        {
            System.out.println(books.get(i));
        }
        
        //采用迭代器遍历
        System.out.println("采用迭代器遍历:");
        Iterator<String> it = books.iterator();
        while (it.hasNext())
        {
            System.out.println(it.next());
        }
原创粉丝点击