foreach VS for loop

今天电面的时候面试官问:

java中数组和链表,进行遍历时,foreach 和 for loop选哪个?
平常没有注意foreach 和 for loop 的区别,以为它俩是一样的,不过既然面试官这么问了,那肯定是不一样的啦。

参考这个 链接
foreach,即 The enhanced for statement,使用foreach时,被遍历的对象只有两种情况:

1.继承 Iterable 接口的类。

此时 foreach 以以下方式运行

for (I #i = Expression.iterator(); #i.hasNext(); ) {
    {VariableModifier} TargetType Identifier = (TargetType) #i.next();
    Statement
}

这里有一点要注意的是:

If the declared type of the local variable in the header of the enhanced for statement is a reference type, then TargetType is that declared type; otherwise, TargetType is the upper bound of the capture conversion of the type argument of I, or Object if I is raw.
大意就是:如果foreach中的第一个变量是引用类型,那么TargetType就声明为那个类型,否则,TargetType就声明为 Iterator.next 对象的类型。

比如如下例子:

List<? extends Integer> l = ...
for (float i : l) ...

等效于

for (Iterator<Integer> #i = l.iterator(); #i.hasNext(); ) {
    float #i0 = (Integer)#i.next();
    ...

2. 数组

当被遍历的对象为数组时,foreach以以下方式运行

T[] #a = Expression;
L1: L2: ... Lm:
for (int #i = 0; #i < #a.length; #i++) {
    {VariableModifier} TargetType Identifier = #a[#i];
    Statement
}

回到开始的问题,在遍历数组时,使用for和foreach都一样的,但是使用链表时(比如 LinkedList),使用 foreach 性能会好些,毕竟链表长于插入删除,定位存取则不如数组。

注:以上内容如有错误,望不吝指出!
转载请注明出处:http://blog.csdn.net/big_heart_c/article/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值