java for each 原理,java foreach原理

foreach语法糖

foreach是java的语法糖,所谓语法糖就是通过编译器或者其它手段优化了代码,给使用带来了遍历。比如,没有forach之前,我们需要这样遍历一个集合

for(int i=0; i

是不是很麻烦?

如果用foreach只需要这样

List list = new ArrayList();

for(String e : list){

//

}

是不是省事多了,不用索引值,不用判断是否越界。

foreach集合原理

但是,今天探讨的是foreach是什么,我们还是通过反编译代码来看吧。

源代码

List a = new ArrayList();

a.add("1");

a.add("2");

a.add("3");

for(String temp : a){

System.out.print(temp);

}

反编译后的代码

List a = new ArrayList();

a.add("1");

a.add("2");

a.add("3");

String temp;

for(Iterator i$ = a.iterator(); i$.hasNext(); System.out.print(temp)){

temp = (String)i$.next();

}

foreach集合相当于获取迭代器(a.iterator),通过判断是否有下一个元素(i.hasNext()∗∗),,然后移动光标(∗∗i.next());,执行操作(System.out.print(temp))

我们知道集合都实现了iterator接口

public interface Iterator {

boolean hasNext();

E next();

void remove();

}

public interface Collection extends Iterable

foreach数组

好了,foreach集合的真面目,我们看懂了。因为集合实现了Iterator接口,所以遍历时走的Iterator的方法,但是foreach不只可以遍历集合,还可以遍历数组,难道数组也实现了Iterator接口?

同样,看反编译后的代码

String[] arr = {"1","2"};

for(String e : arr){

System.out.println(e);

}

反编译后代码

String arr[] = { "1", "2" };

String arr$[] = arr;

int len$= arr$.length;

for(int i$= 0; i$< len$; i$++)

{

String e = arr$[i$];

System.out.println(e);

}

可以看到foreach数组,走的是for(int i=0; i< len; i++)经典模式。^_^

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值