当前位置:  首页>> 技术小册>> Java语言基础10-Java中的集合

增强 for 循环(也称为 for each 循环)是 JDK 5 之后出来的一个高级的 for 循环,专门用来遍历数组和集合。

语法:

  1. for(元素的数据类型 变量: 数组 Collection集合){
  2. // 写代码
  3. }

示例:遍历数组(不要在遍历数组的时候对数组的元素进行修改)

  1. package com.github.collection1.demo6;
  2. /**
  3. * @author maxiaoke.com
  4. * @version 1.0
  5. */
  6. public class Test {
  7. public static void main(String[] args) {
  8. // 创建数组
  9. int[] arr = {1, 2, 3, 4, 5};
  10. // 遍历数组
  11. for (int i : arr) {
  12. System.out.println("i = " + i);
  13. }
  14. }
  15. }

示例:遍历集合(不要在遍历集合的时候对集合中的元素进行增加、删除、替换等操作)

  1. package com.github.collection1.demo7;
  2. import java.util.ArrayList;
  3. import java.util.Collection;
  4. /**
  5. * @author maxiaoke.com
  6. * @version 1.0
  7. */
  8. public class Test {
  9. public static void main(String[] args) {
  10. // 创建集合
  11. Collection<Integer> collection = new ArrayList<>();
  12. // 向集合中添加元素
  13. collection.add(1);
  14. collection.add(2);
  15. collection.add(3);
  16. collection.add(4);
  17. // 遍历集合
  18. for (Integer i : collection) {
  19. System.out.println("i = " + i);
  20. }
  21. }
  22. }