Can we write our own iterator in Java?

The best reusable option is to implement the interface Iterable and override the method iterator(). Here’s an example of a an ArrayList like class implementing the interface, in which you override the method Iterator(). import java.util.Iterator; public class SOList<Type> implements Iterable<Type> { private Type[] arrayList; private int currentSize; public SOList(Type[] newArray) { this.arrayList = newArray; … Read more

If range() is a generator in Python 3.3, why can I not call next() on a range?

range is a class of immutable iterable objects. Their iteration behavior can be compared to lists: you can’t call next directly on them; you have to get an iterator by using iter. So no, range is not a generator. You may be thinking, “why didn’t they make it an iterator”? Well, ranges have some useful … Read more

How to get the current loop index when using Iterator?

I had the same question and found using a ListIterator worked. Similar to the test above: List<String> list = Arrays.asList(“zero”, “one”, “two”); ListIterator<String> iter = list.listIterator(); while (iter.hasNext()) { System.out.println(“index: ” + iter.nextIndex() + ” value: ” + iter.next()); } Make sure you call the nextIndex() before you actually get the next().