如何在不破坏封装性的前提下,利用迭代器模式对集合元素进行遍历?请举例说明。

在 Java 中,迭代器模式(Iterator Pattern)是一种行为设计模式,它允许我们在不暴露集合内部结构的情况下遍历集合中的元素。迭代器模式通过提供一个统一的接口来访问集合中的元素,从而避免了直接操作集合的复杂性。以下是利用迭代器模式遍历集合的详细说明和示例。

1. 迭代器模式的核心概念

迭代器模式包含以下两个核心接口或类:

  • Iterator 接口:定义了访问和遍历集合元素的方法,如 hasNext()、next() 和 remove()。
  • Iterable 接口:表示一个集合可以被迭代,需要实现 iterator() 方法,返回一个 Iterator 对象。

2. 实现迭代器模式的步骤

以下是一个自定义集合类并使用迭代器模式遍历的示例:

自定义集合类

import java.util.Iterator;

public class MyCollection<T> implements Iterable<T> {
    private T[] elements;
    private int size;

    public MyCollection(int capacity) {
        elements = (T[]) new Object[capacity];
        size = 0;
    }

    public void add(T element) {
        if (size < elements.length) {
            elements[size++] = element;
        }
    }

    @Override
    public Iterator<T> iterator() {
        return new MyIterator();
    }

    // 自定义迭代器
    private class MyIterator implements Iterator<T> {
        private int currentIndex = 0;

        @Override
        public boolean hasNext() {
            return currentIndex < size;
        }

        @Override
        public T next() {
            if (!hasNext()) {
                throw new IllegalStateException("No more elements");
            }
            return elements[currentIndex++];
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException("Remove operation is not supported");
        }
    }
}

使用示例

public class Main {
    public static void main(String[] args) {
        MyCollection<String> collection = new MyCollection<>(5);
        collection.add("A");
        collection.add("B");
        collection.add("C");

        // 使用迭代器遍历
        Iterator<String> iterator = collection.iterator();
        while (iterator.hasNext()) {
            String element = iterator.next();
            System.out.println(element);
        }

        // 使用增强 for 循环(底层也是迭代器)
        for (String element : collection) {
            System.out.println(element);
        }
    }
}

3. 迭代器模式的优点

  1. 封装性:迭代器模式隐藏了集合的内部实现,用户只需通过迭代器接口即可遍历集合,无需关心底层数据结构。
  2. 简化客户端代码:客户端代码不需要知道集合的具体实现,只需要调用迭代器的 hasNext() 和 next() 方法。
  3. 支持多种遍历方式:可以为同一个集合提供多种遍历方式,比如正向遍历、反向遍历等。

4. 总结

通过实现 Iterable 接口并提供自定义的 Iterator 实现,可以在不破坏封装性的情况下遍历集合元素。这种模式在 Java 的标准库中广泛应用,例如 ArrayList、LinkedList 等集合类都实现了 Iterable 接口。

上述示例中,MyCollection 类封装了一个数组,并通过 MyIterator 提供了遍历功能,客户端代码只需要调用 iterator() 方法即可遍历集合,而无需直接操作数组。