Java集合类迭代器

迭代器

  • 概念

迭代器是一种设计模式,提供了一种方法,来对容器、集合进行遍历的方式,
不需要关注底层数据结构和数据类型,来达到底层和上层遍历解耦的目的

  • 方法
    boolean hashNext() 判断集合是否还有元素 true / false
    E next() 返回当前数据
    void remove() 删除元素

  • 注意
    在使用迭代器时,hasNext,next需要交替出现
    要自定义迭代器类需要实现iterable接口
    自定义迭代器类需要实现Iterator接口
    具体实现步骤:自定义实现迭代器

  • 并发异常问题:ConcurrentModificationException
    集合本身修改会引起modCount版本号修改。而迭代器的版本号副本并未改变,因此会引起ConcurrentModificationException异常

    public static void main(String[] args) {
        ArrayList<Integer> arrayList = new ArrayList<>();
        arrayList.add(2);
        arrayList.add(3);
        arrayList.add(8);
        arrayList.add(5);
        Iterator<Integer> iterator = arrayList.iterator();
        while (iterator.hasNext()) {
            arrayList.add(10);
            Integer value = iterator.next();
            System.out.println(value);
        }
    }

如上,在使用迭代器遍历ArrayList集合时,在循环中给原集合添加元素,则原集合版本号发生改变,而迭代器的版本号副本还是原来的集合,引起ConcurrentModificationException异常

ArrayList集合迭代器的使用

    public static void main(String[] args) {
        ArrayList<Integer> arrayList = new ArrayList<>();
        arrayList.add(2);
        arrayList.add(3);
        arrayList.add(8);
        arrayList.add(5);
        Iterator<Integer> iterator = arrayList.iterator();
        while (iterator.hasNext()) {
            Integer value = iterator.next();
            System.out.print(value + " ");
        }
    }

输出结果:在这里插入图片描述

HashMap迭代器

集合HashMap迭代器有三种使用方法,首先我们创建一个HashMap集合如下

        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("allen", "1");
        hashMap.put("sds", "2");
        hashMap.put("fefef", "3");
        hashMap.put("ffffynty", "4");
        hashMap.put("okui", "5");
  1. 通过键值对遍历
    先将HashMap实例转化成set实例(类型:map.entry<>)
        Iterator<Map.Entry<String, String>> iterator = hashMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> next = iterator.next();
            String key = next.getKey();
            String val = next.getValue();
            System.out.print(key + ":" + val + " ");
        }

输出结果:在这里插入图片描述
2. 通过键来遍历,仅仅对键进行访问

        Iterator<String> iterator1 = hashMap.keySet().iterator();
        while (iterator1.hasNext()) {
            String next = iterator1.next();
            System.out.print(next + " ");
        }

输出结果:在这里插入图片描述
3. 通过值进行遍历

        Iterator<String> iterator2 = hashMap.values().iterator();
        while (iterator2.hasNext()) {
            String val = iterator2.next();
            System.out.print(val + " ");
        }

输出结果:在这里插入图片描述

其他集合类的迭代器

其他各集合迭代器使用方法和ArrayList及HashMap相似,可以根据上面的代码模仿使用
下面进行分类

和ArrayList相似的
  1. LInkedList:迭代器方法为listIterator()
  2. HashSet
  3. LinkedHashSet:
  4. TreeSet
  5. PriorityQueue
和HashMap相似的
  1. Hashtable
  2. LinkedHashMap
  3. WeakHashMap
  4. TreeMap

综上,我们可以发现

  • 集合元素以单个值存储的,迭代器使用方法与ArrayList类似
  • 集合元素以键值对存储的,迭代器使用方法与HashMap类似

猜你喜欢

转载自blog.csdn.net/weixin_43289802/article/details/88229221