Can we write a container class ourselves and use a for-each loop?

In Java, we can write a container class ourselves, and we can use for-each loop (also called enhanced for loop or foreach loop) to iterate over the elements in the container. To achieve this, our container class must meet the following conditions:

  1. Implement the Iterable interface

  Our container class must implement the java.lang.Iterable interface. The interface contains a method called iterator(), which returns an object implementing the java.util.Iterator interface for traversing the elements in the container.

  2. Implement the Iterator interface

  Our container class must also implement the java.util.Iterator interface. The Iterator interface defines several methods, such as hasNext() (judging whether there is a next element), next() (returning the next element) and remove() (removing the current element from the container, optional operation).

  Next, the author uses a specific code example to demonstrate how to create a custom container class and use the for-each loop to traverse it:

import java.util.Iterator;

// 自定义容器类
class MyContainer<T> implements Iterable<T> {
    private T[] elements;
    private int size;
    
    @SuppressWarnings("unchecked")
    public MyContainer(int capacity) {
        elements = (T[]) new Object[capacity];
        size = 0;
    }
    
    public void add(T element) {
        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() {
            return elements[currentIndex++];
        }
    }
}

public class Main {
    public static void main(String[] args) {
        MyContainer<String> container = new MyContainer<>(3);
        container.add("Apple");
        container.add("Banana");
        container.add("Orange");

        // 使用 for-each 循环遍历容器
        for (String fruit : container) {
            System.out.println(fruit);
        }
    }
}

  Output result:

Apple
Banana
Orange

  In the above example, we created a custom container class MyContainer that implements the Iterable interface, and provides an inner class MyIterator that implements the Iterator interface. In this way, we can use a for-each loop to iterate over the elements in the container.

Guess you like

Origin blog.csdn.net/Blue92120/article/details/132035460