package com.sumea.davinci.util.collections; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; /** * This class extends the arraylist with methods to move elements * to various positions in the same list. * * @author Andreas Prudzilko */ public class DynamicList extends ArrayList { public DynamicList(int initialCapacity) { super(initialCapacity); } public DynamicList() { } public DynamicList(Collection c) { super(c); } /** * Moves an existing object in the list to a new index * * @param o * @param index */ public void move(E o, int index) { move(indexOf(o), index); } /** * moves an object from old index to before the new index * * @param oldindex * @param newindex */ public void move(int oldindex, int newindex) { if (oldindex == newindex) return; E o = get(oldindex); remove(o); if (newindex > oldindex) { newindex--; } add(newindex, o); } public void moveUp(int index) { if (index >= size() - 1) return; synchronized (this) { E o = get(index); E next = get(index + 1); set(index, next); set(index + 1, o); } } public void moveDown(int index) { if (index <= 0) return; synchronized (this) { E o = get(index); E prev = get(index - 1); set(index - 1, o); set(index, prev); } } public Iterator reverseIterator() { return new Iterator() { private int index = size() - 1; public boolean hasNext() { return index >= 0; } public void remove() { } public E next() { return get(index--); } }; } }