首页 > 其他 > 详细

遍历集合的3种方式

时间:2016-12-08 21:05:23      阅读:175      评论:0      收藏:0      [点我收藏+]
import java.util.ArrayList;
import java.util.Iterator;

/*
 * ArrayList存储字符串并遍历
 * A:迭代器
 * B:普通for
 * C:增强for
 */
public class ArrayListDemo {
    public static void main(String[] args) {
        // 创建集合对象
        ArrayList<String> array = new ArrayList<String>();

        // 创建并添加元素
        array.add("hello");
        array.add("world");
        array.add("java");

        // 遍历集合
        // 迭代器
        Iterator<String> it = array.iterator();
        while (it.hasNext()) {
            String s = it.next();
            System.out.println(s);
        }
        System.out.println("------------------");

        // 普通for
        for (int x = 0; x < array.size(); x++) {
            String s = array.get(x);
            System.out.println(s);
        }
        System.out.println("------------------");

        // 增强for
        for (String s : array) {
            System.out.println(s);
        }
    }
}

 

遍历集合的3种方式

原文:http://www.cnblogs.com/itboys/p/6146229.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!