Create a Custom Iterator Class in Java for for-in Loop
To create a custom iterator class in Java that can be used with the for-in loop, you need to implement the 'Iterable' interface and provide an implementation of the 'iterator()' method.
Here's an example implementation:
public class MyIterableClass<T> implements Iterable<T> {
private T[] elements;
public MyIterableClass(T[] elements) {
this.elements = elements;
}
@Override
public Iterator<T> iterator() {
return new MyIterator();
}
private class MyIterator implements Iterator<T> {
private int currentIndex = 0;
@Override
public boolean hasNext() {
return currentIndex < elements.length;
}
@Override
public T next() {
return elements[currentIndex++];
}
}
}
In this example, the 'MyIterableClass' takes an array of elements in its constructor and implements the 'Iterable' interface by providing an implementation of the 'iterator()' method. The 'iterator()' method returns an instance of a private class 'MyIterator' that implements the 'Iterator' interface. The 'MyIterator' class keeps track of the current index and provides implementations of the 'hasNext()' and 'next()' methods.
To use this custom iterator class with a for-in loop, you can simply do:
MyIterableClass<String> iterable = new MyIterableClass<>(new String[]{'hello', 'world'});
for (String element : iterable) {
System.out.println(element);
}
This will print:
hello
world
原文地址: https://www.cveoy.top/t/topic/n8jg 著作权归作者所有。请勿转载和采集!