浅谈 foreach 的原理

package com.shenzhou;

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

public class ForeachTest {
    
    private static int[] array = { 1, 2, 3 };
    private static int[][] arrayTwo = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
    private static List<String> list = new ArrayList<String>();

    static {
        list.add("array - 1");
        list.add("array - 2");
        list.add("array - 3");
    }

    public static void main(String[] args) {
        oldWrite();
        newWrite();
        foreachTwo();
        forList();
        iteratorList();
        foreachList();
    }

    /**
     * 旧形式的遍历
     */
    private static void oldWrite() {
        for (int i = 0; i < array.length; i++) {
            System.out.println(array[i]);
        }
    }

    /**
     * 新形式的遍历
     * @since JDK5.0
     */
    private static void newWrite() {
        for (int i : array) {
            // foreach实现原理一:实际上本方法去遍历数组的时候使用的是for一样的方式去循环遍历数组
            System.out.println(i);
        }
    }

    /**
     * 新形式对于多维数组的遍历
     * @since JDK5.0
     */
    private static void foreachTwo() {
        for (int[] i : arrayTwo) {
            for (int j : i) {
                System.out.println(j);
            }
        }
    }

    /**
     * 旧方式遍历集合
     */
    private static void forList() {
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));

        }
    }

    /**
     * 使用迭代器遍历集合
     */
    private static void iteratorList() {
        for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {
            System.out.println((String) iterator.next());
        }
    }

    /**
     * 使用新形式遍历集合
     * @since JDK5.0
     */
    private static void foreachList() {
        for (String string : list) {
            // foreach实现原理二:实际上本方法遍历容器使用的方式是通过迭代器来进行的
            System.out.println(string);
        }
    }

}

输出结果:

1
2
3
1
2
3
1
2
3
4
5
6
7
8
9
array - 1
array - 2
array - 3
array - 1
array - 2
array - 3
array - 1
array - 2
array - 3

Foreach的原理:

  要使用foreach来遍历的对象必须实现Iterable接口,这是因为foreach内部其实是封装了一个迭代器对象来对所要遍历的对象进行迭代,而这个迭代器的来源是通过所要遍历对象的Iterator  iterator()方法来 获取的,Iterator  iterator()这个方法封装在Iterable接口中,所以要遍历对象必须实现Iterable 接口。

特点:

1.foreach遍历不能对元素进行赋值操作
2.同时只能遍历一个
3.遍历的时候,只有当前被遍历的元素可见,其他不可见
4.只能正向遍历,不能反向

猜你喜欢

转载自www.cnblogs.com/liuqing576598117/p/9844363.html