To create a custom Iterator in Java Collections, you need to implement the Iterator interface in your class. The Iterator interface has three methods: hasNext(), next(), and remove(). Here’s an example of a custom Iterator implementation for a simple MyList class:
public class MyList<T> implements Iterable<T> {
private T[] items;
private int size;
public MyList() {
items = (T[]) new Object[10];
size = 0;
}
public void add(T item) {
if (size >= items.length) {
T[] newItems = (T[]) new Object[items.length * 2];
System.arraycopy(items, 0, newItems, 0, size);
items = newItems;
}
items[size] = item;
size++;
}
public Iterator<T> iterator() {
return new MyListIterator();
}
private class MyListIterator implements Iterator<T> {
private int currentIndex = 0;
public boolean hasNext() {
return currentIndex < size;
}
public T next() {
T item = items[currentIndex];
currentIndex++;
return item;
}
public void remove() {
throw new UnsupportedOperationException();
}
}
}
In this example, the MyList class is a simple implementation of a dynamic array that can hold any type of object. The iterator() method returns a new instance of the MyListIterator class, which implements the Iterator interface. The hasNext() method checks if there are more elements in the list, the next() method returns the next element in the list, and the remove() method throws an UnsupportedOperationException since removing elements from a dynamic array is not supported.
Once you have implemented your custom Iterator, you can use it to iterate through your collection using a foreach loop or the Iterator methods. For example:
MyList<Integer> myList = new MyList<>();
myList.add(1);
myList.add(2);
myList.add(3);
for (Integer i : myList) {
System.out.println(i);
}
Iterator<Integer> iterator = myList.iterator();
while (iterator.hasNext()) {
Integer i = iterator.next();
System.out.println(i);
}
In this example, the MyList class is used to create a list of integers, and the for loop and while loop are used to iterate through the list using the custom Iterator.