Sobes.tech
Junior — Middle

What methods need to be implemented in a class so that its objects can be used in a for-each loop?

sobes.tech AI

Answer from AI

To use objects of a class in a for-each loop in Java, the class must implement the Iterable<T> interface. The main method to implement is:

Iterator<T> iterator();

This method returns an Iterator object, which implements the methods:

  • boolean hasNext() — checks if there is a next element.
  • T next() — returns the next element.

Example:

import java.util.Iterator;

public class MyCollection implements Iterable<String> {
    private String[] data = {"a", "b", "c"};

    @Override
    public Iterator<String> iterator() {
        return new Iterator<String>() {
            private int index = 0;

            @Override
            public boolean hasNext() {
                return index < data.length;
            }

            @Override
            public String next() {
                return data[index++];
            }
        };
    }
}

// Usage:
// for (String s : new MyCollection()) {
//     System.out.println(s);
// }
What methods need to be implemented in a class so… - sobes.tech