package v22;
/**
*
* @author Daniel
*
* @param <T>
*/
public class DynamicArray<T> { Object[] vector;
public DynamicArray() { vector = new Object[0];
}
public int tamaño() { return vector.length;
}
// Devuelve el valor con indice como parametro
public T obtener(int índice) { final T t = (T) vector[índice];
return t;
}
// Redimensiona el array
public void agregar(T item) { Object aux[] = new Object[vector.length + 1];
for (int x = 0; x < vector.length; x++) { aux[x] = vector[x];
}
aux[vector.length] = item;
vector = aux;
}
// Borra en una posición indicada y redimensiona el array
public void borrar(int posicion) { if (posicion < 0 || posicion >= vector.length)
throw new ArrayIndexOutOfBoundsException("Has sobrepasado los límites del array");
if ((vector.length - 1) != posicion) { for (int i = posicion; i < (vector.length - 1); i++) { vector[i] = vector[i + 1];
}
}
Object aux[] = new Object[vector.length - 1];
for (int i = 0; i < aux.length; i++) { aux[i] = vector[i];
}
vector = aux;
}
}
//Prueba
package v22;
/**
*
* @author Daniel
*
*/
public class Prueba { DynamicArray<Integer> a = new DynamicArray<Integer>();
public static void main(String[] args) {
new Prueba();
}
public Prueba() { pruebaAgregar();
mostrarItems();
System.out.println("borrando..."); pruebaExcepcion();
borrar();
}
// Añadimos en el array
void pruebaAgregar() {
for (int i = 0; i < 10; i++) { a.agregar(i);
}
}
// Mostramos el contenido del array
void mostrarItems() {
for (int i = 0; i < a.tamaño(); i++) { System.out.println("Dentro: " + a.obtener(i)); }
}
// Borramos indicando el indice y el tamaño tras borrar
void borrar() { for (int i = a.tamaño() - 1; i >= 0; i--) { a.borrar(i);
System.out.println("Se ha borrado el indice: " + i + ", el tamaño del array es: " + a.tamaño());
}
}
// Capturamos la excepcion ya que sale de los límites
void pruebaExcepcion() {
try { Thread.sleep(100);
a.borrar(99);
} catch (ArrayIndexOutOfBoundsException | InterruptedException e) { System.err.println(e.getMessage());
}
}
}