import java.util.ArrayList; public class ResizableVector implements Vector { private Object[] array; private int size = 0; public ResizableVector() { this(16); } public ResizableVector(int capacity) { array = new Object[capacity]; } @Override public int size() { return size; } @Override public boolean isEmpty() { return size == 0; } @SuppressWarnings("unchecked") @Override public T elemAtRank(int r) throws VectorOutOfBoundsException { checkRank(r); return (T) array[r]; } @Override public void replaceAtRank(int r, Object elem) throws VectorOutOfBoundsException { checkRank(r); array[r] = elem; } public void addLast(T elem) throws VectorOutOfBoundsException { insertAtRank(size, elem); } @Override public void insertAtRank(int r, Object elem) throws VectorOutOfBoundsException { if (r > size || r < 0) { throw new VectorOutOfBoundsException(); } if (isFull()) { resize(size * 2); } // arrasta para "direita" for (int i = size; i > r; i--) { array[i] = array[i - 1]; } array[r] = elem; size++; } @Override public T removeAtRank(int r) throws VectorOutOfBoundsException { checkRank(r); T obj = (T) array[r]; for (int i = r + 1; i < size; i++) { array[i - 1] = array[i]; } array[size - 1] = null; size--; if (size <= array.length / 4) { resize(array.length / 2); } return obj; } private boolean isFull() { return size == array.length; } private void resize(int newSize) { Object[] array = new Object[newSize]; for (int i = 0; i < size; i++) { array[i] = this.array[i]; } this.array = array; } @Override public String toString() { StringBuffer str = new StringBuffer(); str.append("Tamanho do array: " + array.length + "\n"); str.append("Size: " + size + "\n"); str.append("["); for (int i = 0; i < size; i++) { if (i == size - 1) str.append(array[i] + "]"); else str.append(array[i] + ", "); } return str.toString(); } private void checkRank(int r) throws VectorOutOfBoundsException { if (r >= size || r < 0) { throw new VectorOutOfBoundsException(); } } static void insere(int r, int elem, Vector v) throws VectorOutOfBoundsException { System.out.println("Insert " + elem + " at rank " + r); v.insertAtRank(r, elem); System.out.println(v); } static void remove(int r, Vector v) throws VectorOutOfBoundsException { System.out.println("Remove at rank " + r); v.removeAtRank(r); System.out.println(v); } public static void main(String[] args) throws VectorOutOfBoundsException { ResizableVector h = new ResizableVector(2); insere(0, 1, h); insere(1, 2, h); insere(2, 3, h); insere(3, 4, h); insere(4, 5, h); insere(5, 6, h); insere(6, 7, h); insere(7, 8, h); insere(0, 0, h); remove(4, h); remove(4, h); remove(4, h); remove(4, h); remove(4, h); remove(0, h); remove(0, h); remove(0, h); remove(0, h); insere(0, 1, h); insere(1, 2, h); insere(2, 3, h); } }