/**
*
* @author Daniel
*
* @param <T>
*/
public class DynamicArray<T> { Object[] vector;
//Constructor de la clase
public DynamicArray() { vector = new Object[0];
}
//Devuelve el tamaño del array
public int tamaño() { return vector.length;
}
//Devuelve el valor con ese índice
public T obtener(int índice) { final T t = (T)vector[índice];
return t ;
}
// Redimensiona el array dandole un a nueva posicion con el argumento frase
public void agregar(T frase) { Object aux[] = new Object[vector.length + 1];
for (int x = 0; x < vector.length; x++) { aux[x] = vector[x];
}
aux[vector.length] = frase;
vector = aux;
}
// Borra en una posición indicada y redimensiona el array
public void borrar(int posicion) { if(posicion>=0&&posicion<vector.length) { 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;
}else { //Ejecuta la excepcion apropiada si posicion se sale de los límites
throw new ArrayIndexOutOfBoundsException("Has sobrepasado los límites del array"); }
}
}
////Clase principal
/**
*
* @author Daniel
*
*/
public class Prueba {public static void main(String[] args) { DynamicArray<Integer> a = new DynamicArray<Integer>();
//Añadimos en el array
for(int i=0;i<10;i++) { a.agregar(i);
}
//Mostramos lo agregado
for (int i = 0; i<a.tamaño();i ++) { System.out.println("Dentro: "+a.obtener(i)); }
//Borramos una posición
a.borrar(1);
System.out.println("borrando...");
//Capturamos la excepción ya que sale de los límites
try { Thread.sleep(100);
a.borrar(99);
} catch (ArrayIndexOutOfBoundsException | InterruptedException e ) { System.err.println(e.getMessage());
}
//Mostramos el array redimensionado desues de borrar
for (int i = 0; i<a.tamaño();i ++) { System.out.println("Dentro: "+a.obtener(i)); }
}
}