package util.nice; import java.util.NoSuchElementException; public class NiceVector implements QuickSortable, NiceEnumerable { private Niceable elem[] = null; private int theSize = 0; public NiceVector() { } public NiceVector(int cap) { changeCapacity(cap); } public NiceVector(NiceEnumerable n) { int cap = 0; for (NiceEnumeration enum = n.elements(); enum.hasMoreElements(); enum.nextElement()) ++cap; changeCapacity(cap); for (NiceEnumeration enum = n.elements(); enum.hasMoreElements(); ) insert(enum.nextElement()); } public int getSize() { return theSize; } public int getCapacity() { return elem == null ? 0 : elem.length; } public void removeAll() { elem = null; theSize = 0; } private void changeCapacity(int newCap) { if (newCap == 0) { removeAll(); return; } Niceable newElem[] = new Niceable[newCap]; if (theSize > newCap) theSize = newCap; for (int i = 0; i < getSize(); ++i) newElem[i] = elem[i]; elem = newElem; } public void insert(Niceable obj) { int cap = getCapacity(); if (getSize() >= cap) changeCapacity(cap == 0 ? 1 : cap << 1); elem[theSize++] = obj; } public void append(NiceVector v) { if (v == this) v = new NiceVector(v); int cap = getSize() + v.getSize(); if (cap > getCapacity()) changeCapacity(cap); for (NiceEnumeration enum = v.elements(); enum.hasMoreElements(); ) insert(enum.nextElement()); } public boolean isEmpty() { return theSize == 0; } public Niceable remove() throws NoSuchElementException { if (isEmpty()) throw new NoSuchElementException(); return elem[--theSize]; } public void trim() { changeCapacity(getSize()); } public Niceable getElementAt(int index) throws ArrayIndexOutOfBoundsException { if (index < 0 || index >= getSize()) throw new ArrayIndexOutOfBoundsException(index); return elem[index]; } public void setElementAt(int index, Niceable obj) throws ArrayIndexOutOfBoundsException { if (index < 0 || index >= getSize()) throw new ArrayIndexOutOfBoundsException(index); elem[index] = obj; } public NiceEnumeration elements() { return new NiceVectorEnumeration(this); } }