for循环与增强for循环的区别与使用

for循环分为两种:一种为普通for循环,一种为增强for循环(也就是foreach循环)
区别:

1)任何循环都能用普通for循环运行,但不一定能用增强for循环,也就是增强for循环的使用范围要小。
2)增强for循环内部其实是使用了Iterator迭代器遍历的,只能遍历数组和实现了Interable接口的集合。
3)普通for循环可以获取元素索引,增强for循环无法获取元素索引
4)增强for循环比普通for循环代码更简洁。
5)增强for循环必要有被遍历的目标。
6)增强for循环无法在循环时动态的删除元素和获取下标。
7)对于非集合类(没有实现 Iterable接口的)的数组遍历,增强型for循环和普通循环遍历原理相同,效率基本相同。
8)对于集合类(实现了Iterable接口的),增强型for循环的遍历其本质就是迭代器 iterator的遍历,和普通循环遍历相比,各自有自己适用的场景,比如说普通for循环比较适合List类(数组类)遍历通过下标查找数据的,而增强型for循环则比较适合链表结构的集合的遍历。

下面来demo对比下区别:

1.对于数组循环,两种循环效率基本相同
  public static void main(String[] args) {
        //定义数组长度为1000万
        Integer[] a = new Integer[10000000];
        for (int i = 0; i < a.length; i++) {
            a[i] = i;
        }
        int b = 0;
        long startTime = System.currentTimeMillis();
        //1.开始普通for循环
        for (int i = 0; i < a.length; i++) {
            b = a[i];
        }
        System.out.println("1000万次循环普通for循环消耗时间:" + (System.currentTimeMillis() - startTime));


        //2.开始增强for循环
        long startTime1 = System.currentTimeMillis();
        for (int i : a) {
            b = i;
        }
        System.out.println("1000万次循环增强for循环消耗时间:" + (System.currentTimeMillis() - startTime1));

    }

运行结果如下:1000万次循环时间仅仅相差两秒,基本可以忽略不计区别。


1000万次循环普通for循环消耗时间:10
1000万次循环增强for循环消耗时间:8

2.增强for循环无法在循环中动态删除或新增元素
package org.sang.test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * create by 86159 on 2021/1/13
 */
public class Foreach {
    public static void main(String[] args) {
        //1.定义一个集合
        List<Map<String, Object>> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Map map = new HashMap();
            map.put("id", i);
            map.put("msg", "消息" + i);
            list.add(map);
        }
        //2.删除偶数位元素
        for (Map lmap : list) {
            if ((int) lmap.get("id") % 2 == 0) {
                list.remove(lmap);
            }
        }
        System.out.println(list.size());
    }
}

运行结果如下:

Exception in thread "main" java.util.ConcurrentModificationException
	at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909)
	at java.util.ArrayList$Itr.next(ArrayList.java:859)
	at org.sang.test.Foreach.main(Foreach.java:42)

Process finished with exit code 1

注意这个java.util.ConcurrentModificationException异常,就是在这个增强for循环中进行了remove元素操作。

同理,调用add添加元素也是报同样的错误,这种情况,需要动态的删除或新增集合中的元素,则建议使用普通for循环操作。

总结:
能用增强for循环的一定能用普通for循环,能用普通for循环的不一定能用增强for循环。

### Java Traditional For Loop vs Enhanced For Loop Differences In Java, both traditional and enhanced `for` loops serve the purpose of iterating over elements but differ significantly in syntax and usage scenarios. #### Syntax Comparison The **traditional for loop** requires initialization, a condition check, and an increment or decrement statement explicitly defined within its structure: ```java // Traditional for loop example for (int i = 0; i < array.length; i++) { System.out.println(array[i]); } ``` Conversely, the **enhanced for loop**, introduced with Java 5, simplifies iteration by abstracting away index management. This results in cleaner code when only sequential access is needed without requiring direct manipulation of indices[^4]: ```java // Enhanced for loop example for (Type element : array) { System.out.println(element); } ``` #### Performance Implications Regarding performance concerns about whether one form might be faster than another, it's important to note that modern JVM optimizations often render these differences negligible. The claim that "results are dead-code eliminated" suggests that under certain conditions, unnecessary computations may indeed be optimized out during compilation[^1]. However, this does not imply inherent speed advantages between the two forms across all contexts. #### Use Cases When dealing with collections where indexed access isn't necessary, such as performing operations on every item sequentially, the enhanced version offers more readable and concise syntax. On the other hand, situations demanding precise control over iteration order or needing to modify collection contents while traversing would favor using the standard variant due to greater flexibility provided through explicit indexing mechanisms[^3].
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

初夏0811

你的鼓励将是我创作最大的动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值