在Java中,可以使用循环结构来遍历数组、集合或者其他数据结构。

  1. 遍历数组: 使用for循环遍历数组,可以通过数组的长度属性来确定循环的次数,然后使用索引访问数组中的元素。

    int[] array = {1, 2, 3, 4, 5};
    for (int i = 0; i < array.length; i++) {
        System.out.println(array[i]);
    }
    
  2. 遍历集合: 使用增强的for循环(也称为foreach循环)遍历集合,可以直接访问集合中的每个元素。

    List<Integer> list = new ArrayList<>();
    list.add(1);
    list.add(2);
    list.add(3);
    for (int num : list) {
        System.out.println(num);
    }
    
  3. 遍历Map: 使用迭代器或者增强的for循环遍历Map,可以获取Map中的键和值。

    Map<String, Integer> map = new HashMap<>();
    map.put("A", 1);
    map.put("B", 2);
    map.put("C", 3);
    // 使用迭代器遍历Map
    Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
    while (iterator.hasNext()) {
        Map.Entry<String, Integer> entry = iterator.next();
        System.out.println(entry.getKey() + ": " + entry.getValue());
    }
    // 使用增强的for循环遍历Map
    for (Map.Entry<String, Integer> entry : map.entrySet()) {
        System.out.println(entry.getKey() + ": " + entry.getValue());
    }
    

除了以上常见的数据结构,还可以根据具体情况使用不同的遍历方法,例如使用递归遍历树形结构等

Java中遍历

原文地址: https://www.cveoy.top/t/topic/hUjH 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录