JAVA中foreach循环的实现原理

代码及其注释如下:

/**
 * 
 */
package com.M.controller.test;

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

/**
 * @author online zuozuo于2017年2月21日上午10:43:02编辑 本类用于解释Foreach循环的实现原理(javap)
 * @about 新形式的遍历虽然好用,但是他丢掉了索引信息。当你需要访问数组或者集合的下标,你将不能使用foreach
 *        从JDK的第五个版本开始加入了这个foreach功能,但是java语言对于它的实现做了隐藏,他是隐藏在语言内部的
 *        实现,因此我们在任何的JDK源码中找不到这段实现,如果需要知道他的具体实现,需要写测试类对他进行反编译
 * 		1.foreach遍历不能对元素进行赋值操作
 * 		2.同时只能遍历一个
 * 		3.遍历的时候,只有当前被遍历的元素可见,其他不可见
 * 		4.只能正向遍历,不能反向
 * 		5.foreach对ArrayList的遍历是因为其实现了Iterable接口
 * @since JDK 5.0
 *
 */
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);
		}
	}

}

 

转载于:https://my.oschina.net/TJALS/blog/842691

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值