返回顶部

收藏

java使用while或for遍历Collection对象

更多

下面例子使用两种方法遍历Collection接口:

import java.util.ArrayList;
import java.util.Iterator;

/**
 *
 * @author outofmemory.cn
 */
public class Main {

    /**
     * Example of iterating through a Collection object
     */
    public void iterateCollection() {

        ArrayList<String> list = new ArrayList<String>();

        list.add("Monday");
        list.add("Tuesdag");
        list.add("Wednesday");
        list.add("Thursday");
        list.add("Friday");
        list.add("Saturday");
        list.add("Sunday");

        Iterator<String> iterator = null;

        //Example 1:
        iterator = list.iterator();
        while (iterator.hasNext()) {
            String element = iterator.next();
            System.out.println(element);
        }

        //blank line
        System.out.println();

        //Example 2:
        for (iterator = list.iterator(); iterator.hasNext(); ) {
            String element = iterator.next();
            System.out.println(element);
        }

        //blank line
        System.out.println();

        //Example 3:
        for (String element : list) {
            System.out.println(element);
        }
    }

    /**
     * @param args 命令行参数
     */
    public static void main(String[] args) {
        new Main().iterateCollection();
    }
}

输入如下:

Monday
Tuesdag
Wednesday
Thursday
Friday
Saturday
Sunday

Monday
Tuesdag
Wednesday
Thursday
Friday
Saturday
Sunday

Monday
Tuesdag
Wednesday
Thursday
Friday
Saturday
Sunday

标签:java,基础,集合

收藏

0人收藏

支持

0

反对

0

发表评论