You are on page 1of 5

LISTAS ENLAZADAS Y OBJETOS USANDO GENRICOS

Objetivo: Saber como crear una lista enlazada con cualquier tipo de TDA que se disee, y emplear los mtodos ya definidos en el API de JAVA. Introduccin: El API de java versin 6, introduce el uso de Listas enlazadas dentro del siguiente paquete:

Class LinkedList<E>
java.lang.Object java.util.AbstractCollection<E> java.util.AbstractList<E> java.util.AbstractSequentialList<E> java.util.LinkedList<E>

Cuenta con dos constructores:

Constructor Summary
LinkedList() Constructs an empty list. LinkedList(Collection<? Extends E> c) Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator. Adems tiene todos los mtodos necesarios, ms los includos ya por se por ser un Objeto.

Method Summary
boolean void boolean

add(E e) Appends the specified element to the end of this list. add(int index, E element) Inserts the specified element at the specified position in this list. addAll(Collection<? Extends E> c) Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator. addAll(int index, Collection<? Extends E> c) Inserts all of the elements in the specified collection into this list, starting at the specified position. addFirst(E e) Inserts the specified element at the beginning of this list.

boolean

void

void void Object boolean Iterator<E>

addLast(E e) Appends the specified element to the end of this list. Clear() Removes all of the elements from this list. Clone() Returns a shallow copy of this LinkedList. contains(Object o) Returns true if this list contains the specified element. DescendingIterator() Returns an iterator over the elements in this deque in reverse sequential order. Element() Retrieves, but does not remove, the head (first element) of this list. get(int index) Returns the element at the specified position in this list. GetFirst() Returns the first element in this list. GetLast() Returns the last element in this list. indexOf(Object o) Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. lastIndexOf(Object o) Returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element. listIterator(int index) Returns a list-iterator of the elements in this list (in proper sequence), starting at the specified position in the list. offer(E e) Adds the specified element as the tail (last element) of this list. offerFirst(E e) Inserts the specified element at the front of this list. offerLast(E e) Inserts the specified element at the end of this list. peek() Retrieves, but does not remove, the head (first element) of this list. peekFirst() Retrieves, but does not remove, the first element of this list, or returns null if this list is empty. peekLast() Retrieves, but does not remove, the last element of this list, or returns null

E E E E int

int

ListIterator< E> boolean boolean boolean E E

if this list is empty.


E E

Poll() Retrieves and removes the head (first element) of this list PollFirst() Retrieves and removes the first element of this list, or returns null if this list is empty. pollLast() Retrieves and removes the last element of this list, or returns null if this list is empty. pop() Pops an element from the stack represented by this list. push(E e) Pushes an element onto the stack represented by this list. remove() Retrieves and removes the head (first element) of this list. remove(int index) Removes the element at the specified position in this list. remove(Object o) Removes the first occurrence of the specified element from this list, if it is present. RemoveFirst() Removes and returns the first element from this list. removeFirstOccurrence(Object o) Removes the first occurrence of the specified element in this list (when traversing the list from head to tail). RemoveLast() Removes and returns the last element from this list. removeLastOccurrence(Object o) Removes the last occurrence of the specified element in this list (when traversing the list from head to tail). set(int index, E element) Replaces the element at the specified position in this list with the specified element. Size() Returns the number of elements in this list. ToArray() Returns an array containing all of the elements in this list in proper sequence (from first to last element). toArray(T[] a) Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array.

E void E E boolean

E boolean

E boolean

int Object[]

<T> T[]

--- INICIO --La siguiente clase, cuenta con dos atributos, un constructor y sus mtodos getters y setters respectivos. Adems cuenta con una sobreEscritura al mtodo equals(): CLASE: Libro.java public class Libro { private String autor; private String titulo; public Libro(String a, String t){ autor = a; titulo = t; } public String getAutor() { return autor; } public void setAutor(String autor) { this.autor = autor; } public String getTitulo() { return titulo; } public void setTitulo(String titulo) { this.titulo = titulo; } public boolean equals(Object other) { System.out.println("En el metodo equals" + other + this); Libro book = (Libro)other; if(this.getAutor().equals(book.getAutor()) && this.getTitulo().equals(book.getTitulo())) return true; else{ return false; } } } ***Es preciso sobreescribir el mtodo equals(), ya que el mtodo contains() de la Clase LinkedList emplea este mtodo. As que se sobreescribe para hacer la comparacin adecuada con el tipo de objeto que se espera encontrar en la Lista Enlazada, en este caso un Libro.

Una vez implementado el TDA, se procede a crear una clase de prueba con la cual podamos observar que los mtodos de esta clase funcionan correctamente, en especial el mtodo de bsqueda y el mtodo que acabamos de sobreescribir. En esta parte usaremos un gnerico. El objeto predeterminado para cualquier clase es de tipo Object, por lo que para definirlo debemos indicarle el tipo de clase del que queremos que este objeto sea definido, esto se hace mediante la siguiente notacin: List<Libro> lista = new LinkedList<Libro>(); El uso de parntesis triangulares, indica de que tipo ser el objeto genrico de esta manera ya no ser necesario usar el casting para los elementos que tengamos en la lista. Use el siguiente cdigo de prueba para verificar que el modelo anterior funciona correctamente con su mtodo equals(). Clase: Buscar.java import java.util.*; public class Buscar { public static void main(String args[]){ List<Libro> lista = new LinkedList<Libro>(); Libro libro = new Libro("DENIS", "ECUACIONES"); lista.add(libro); libro = new Libro("MIRELES", "CALCULO"); lista.add(libro); libro = new Libro("DROZDEK","ESTRUCTURAS"); lista.add(libro); libro = new Libro("DENIS", "ECUACIONES"); System.out.println(lista.contains(libro)); } } En este cdigo de prueba, se crean tres objetos de la clase Libro con los atributos mostrados, al final se crea un nuevo objeto el cual se colocal dentro del mtodo para ver si este existe en la lista. Si usted ejecuta est clase que tiene mtodo principal (main) observar lo siguiente: run: En el metodo equalsLibro@19821fLibro@addbf1 true BUILD SUCCESSFUL (total time: 5 seconds) ---- FIN ---

You might also like