jmud-0.11/
jmud-0.11/bin/
jmud-0.11/doc/
jmud-0.11/rec/
jmud-0.11/rec/mun/
jmud-0.11/rec/mun/grecia/
jmud-0.11/rec/mun/gunnar/
jmud-0.11/rec/qua/
jmud-0.11/src/bool/
jmud-0.11/src/clone/
jmud-0.11/src/integer/
jmud-0.11/src/misc/
jmud-0.11/src/string/
jmud-0.11/src/util/bit/
jmud-0.11/src/util/color/
jmud-0.11/src/util/file/
jmud-0.11/src/util/jgp/adaptor/
jmud-0.11/src/util/jgp/algorithm/
jmud-0.11/src/util/jgp/container/
jmud-0.11/src/util/jgp/functor/
jmud-0.11/src/util/jgp/interfaces/
jmud-0.11/src/util/jgp/predicate/
jmud-0.11/src/util/log/
jmud-0.11/src/util/state/
jmud-0.11/trash/
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);
  }
}