Web / Apache Commons Collections Interview questions
Describe the LoopingIterator class in Apache Commons Collections?
LoopingIterator<E> wraps an existing Collection and iterates over it endlessly, restarting from the first element again once it reaches the end.
List<String> players = Arrays.asList("A", "B", "C"); LoopingIterator<String> turnOrder = new LoopingIterator<>(players); for (int i = 0; i < 7; i++) { System.out.println(turnOrder.next()); // A B C A B C A }
Its hasNext() always returns true as long as the underlying collection isn't empty, since there's always a "next" element to loop back to - meaning code that consumes it must supply its own stopping condition rather than relying on hasNext() to end the loop.
It's a convenient fit for round-robin scheduling, cycling through a fixed set of colors or labels, or repeatedly rotating through a small pool of workers.
More Related questions...