Está en la página 1de 12

COLECCIONES EN JAVA

PROGRAMACIÓN AVANZADA
ANGELA CARRILLO RAMOS
COLECCIONES

• Conjunto de elementos del mismo tipo


• Arreglos
• Listas
ARREGLOS
• Espacio estático de Memoria
Tipo[] nomArreglo;
int[] notas; // int notas [];
Estudiante[] curso; // Estudiante curso [];
• Para pedir memoria se hace con new
notas=new int [10];
curso=new Estudiante [20];
ARREGLOS
• Para recorrerlos se indexan y se pide el tamaño:
int notas[ ] = {1,2,3,4,5};
int acum=0;
for (int i=0; i<notas.length; i++){
acum+=notas[i];
}
• Otra forma de recorrerlo (for mejorado):
for (int num:notas){
acum+=num;
}
LISTAS
• Es una clase del paquete java.util
• Manejo dinámico de la memoria
List<Clase> nomList;
• Ofrece diversos servicios
• Constructor
• Adicionar elemento (add)
• Eliminar elemento (remove)
• Buscar elemento
• Obtener un elemento (get)
• Dar número de elementos (size)
• …
LISTAS: CREAR UNA LISTA

List<Estudiante> listEst=new ArrayList<Estudiante>();


LISTAS: ADICIONAR UN ELEMENTO

public void adicionarEstudiante(String nom){


Estudiante e=buscarEstudiante(nom);

if (e==null){
e=new Estudiante(nom);
listEst.add(e);
}
}
LISTAS: ADICIONAR UN ELEMENTO
public void adicionarEstudiante(String nom) throws EstExc{
Estudiante e=buscarEstudiante(nom);
if (e==null){
e=new Estudiante(nom);
listEst.add(e);
}
else{
throw new EstExc (“El estudiante ya existe y no se agregó”);
}
}
LISTAS: BUSCAR UN ELEMENTO
public Estudiante buscarEstudiante(String nom){
Estudiante e;
for (int i=0; i<listEst.size(); i++){
e=listEst.get(i);
if (e.getNom().equalsIgnoreCase(nom))
return e;
}
return null;

}
LISTAS: BUSCAR UN ELEMENTO
public Estudiante buscarEstudiante(String nom){

for (Estudiante e:listEst){


if (e.getNom().equalsIgnoreCase(nom))
return e;
}
return null;
}
LISTAS: ELIMINAR UN ELEMENTO
public void eliminarEstudiante(String nom){
for (Estudiante e:listEst){
if (e!=null && e.getNom().equalsIgnoreCase(nom))
listEst.remove(e);
}
}
LISTAS: ELIMINAR UN ELEMENTO
public void eliminarEstudiante(String nom) throws EstExc{
Estudiante e=buscarEstudiante(nom);
if (e!=null){
listEst.remove(e);
}
else{
throw new EstExc(“No se pudo eliminar el estudiante pues no existe”);
}
}

También podría gustarte