JAVA中的foreach循环

    技术2024-08-11  64

    JAVA中的foreach循环

    JDK5.0后推出了一个新特性:叫做增强for循环,或者叫foreach 格式: for(元素类型 变量名 : 数组或集合){ }foreach有一个缺点:没有下标增强for循环可以看为一个增强版遍历用foreach循环遍历一个集合时,不能改变集合中的元素, 如增加元素、修改元素。否则会抛出ConcurrentModificationException异常。 public class ForEachTest01 { public static void main(String[] args) { //数组使用foreach //创建一个数组 int[] ints = {1, 2, 3, 4}; //遍历(普通for循环) for (int i = 0; i < ints.length; i++) { System.out.print(ints[i] + " "); } System.out.println(); //使用foreach(增强for循环) for (Integer i : ints) { System.out.print(i + " "); } } } //运行结果: 1 2 3 4 1 2 3 4 public class ForEachTest02 { public static void main(String[] args) { //集合使用foreach //创建集合对象 List<String> list = new ArrayList<>(); //添加元素 list.add("abc"); list.add("def"); list.add("123"); //遍历(使用迭代器) Iterator<String> it = list.iterator(); while(it.hasNext()){ System.out.print(it.next() + " "); } System.out.println(); //使用foreach遍历 for (String str: list) { System.out.print(str + " "); } } } //运行结果: abc def 123 abc def 123
    Processed: 0.099, SQL: 9