for-each循环总结

Java for-each循环

 {
	//循环体
 }

for-each总结

  1. for-each循环的缺点:丢掉了索引信息。

  2. 当遍历集合或数组时,如果需要访问集合或数组的下标,那么最好使用旧式的方式来实现循环或遍历,而不要使用增强的for循环,因为它丢失了下标信息。

  3. 使用for-each时对collection或数组中的元素不能做赋值操作。

  4. 同时只能遍历一个collection或数组,不能同时遍历多余一个collection或数组,遍历过程中,collection或数组中同时只有一个元素可见,即只有“当前遍历到的元素”可见,而前一个或后一个元素是不可见的。

代码演示

package com.wangke.practice;

import java.util.Collection;
import java.util.Arrays;
import java.util.Iterator;

public class forEachTest {

    public static void main(String[] args) {
        int[] integers = {1, 2, 3, 4};
        //遍历数组 方法1 普通for循环
        for (int i = 0; i < integers.length; i++) {
            System.out.println(integers[i]);
        }

        //遍历数组 方法2 
        for (int i : integers) {
            System.out.println(i);
        }

        //遍历collection对象 方法1
        String[] strings = {"A", "B", "C", "D"};
        //asList()方法:将数组转成list
        Collection stringList = Arrays.asList(strings);
        for (Object str : stringList) {
            System.out.println(str);
        }

        //遍历collection对象 方法2(iter遍历)
        String[] strings2 = {"E", "F", "G", "H"};
        Collection stringList2 = Arrays.asList(strings2);
        //迭代器是一种设计模式,它是一个对象,它可以遍历并选择序列中的对象,
        //使用方法iterator()要求容器返回一个Iterator
        //next()获得序列中的下一个元素(第一次调用时即为第一个元素)
        //hasNext()检查序列中是否还有元素
        for (Iterator itr = stringList2.iterator(); itr.hasNext(); ) {
            Object str = itr.next();
            System.out.println(str);
        }

    }

}

原文地址:https://www.cnblogs.com/alwayszzj/p/14463967.html