Junior — Middle
Is it possible to use a custom object in a for-each loop as an iteration element?
sobes.tech AI
Answer from AI
Yes, a custom object can be used in a for-each loop if it implements the Iterable interface or is an array.
For this, the class must implement the iterator() method, which returns an object of type Iterator. For example:
import java.util.Iterator;
class MyCollection implements Iterable<String> {
private String[] data = {"one", "two", "three"};
@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++];
}
};
}
}
public class Main {
public static void main(String[] args) {
MyCollection collection = new MyCollection();
for (String item : collection) {
System.out.println(item);
}
}
}
In this example, MyCollection can be used in a for-each loop because it implements Iterable.