In one of the projects I needed a simple Round Robin list, which would just return the next object in round robin fashion.
Even though it's trivial to come up with one, surprised to find out that I didn't find any hits when I searched for one.
This is what I came up with after half-hour. Use it as you wish. Download here.
package org.brsanthu.misc;
import java.util.ArrayList; import java.util.Collection;
/** * Simple extension to <code>ArrayList</code> with round robin functionality. * <p> * Just adds one method {@link #getNext()} which would return the next object * in the list and the method starts over at first element after reaching the * end of list. * <p> * This class it NOT designed for multi-threaded access. So necessary synchronization * is required before accessing {@link #getNext()} method. * * @since Sep 24th 2007 * @author Santhosh Kumar */ public class RoundRobinList extends ArrayList { private static final long serialVersionUID = 1L; /** * Last used index. Initially it would be -1, so that * first element returned is 0th element of the list. */ private int lastIndex = -1; /** * Constructs a new round robin list with default capacity. */ public RoundRobinList() { super(); }
/** * Constructs a new round robin list and pre-populates with the * objects found in given list. * <p> * For more information about usage of the c, see the <code>ArrayList</code> constructor * page. * * @param c - collection of objects to be added by default to the new list. */ public RoundRobinList(Collection c) { super(c); }
/** * Creates the new round robin list with specified capacity. * * @param initialCapacity - initial capacity. */ public RoundRobinList(int initialCapacity) { super(initialCapacity); }
/** * Returns the next object in the list. * <p> * First invocation of this method after creating the list, always returns * the 0th element. Starts over the 0th element after reaching the end of * list. * <p> * If there are no objects in the list, returns <code>null</code>. * * @return - returns the next object in the list. <code>null</code> if list is * empty. * */ public Object getNext() { if (isEmpty()) { return null; } lastIndex++; if (lastIndex >= size()) { lastIndex = 0; } return get(lastIndex); } } |
Java2html |
# posted by Santhosh @ 3:48 PM