Documentos de Académico
Documentos de Profesional
Documentos de Cultura
QUEUE
En Programación, se le llama “Cola” al Tipo de Dato Abstracto que es una Lista en la que sus
elementos se introducen (Encolan) únicamente por un extremo que le llamamos “Final de la
Cola” y se remueven (Desencolan) únicamente por el extremo contrario al que le llamamos
“Frente de la Cola” o “Principio de la Cola”.
En Java podemos encontrar variadas formas de crear Colas en pocas lineas de código, un
ejemplo es una de sus Interfaces que tiene como nombre “Queue” con la cual podemos crear
Colas
Paquete:
java.util
Declaración de clase:
• Interfaz Queue ordenada cosas por el orden en que van a ser procesados. Por defecto ordena
como FIFO pero puede ordenar de otras formas.
boolean add(E e)
// Añade si hay capacidad en el Queue.
// Si ha podido añadir devuelve true y
// si no devuelve una excepción
//RuntimeException.IllegalStateException.
E element()
// Recupera sin borrar la cabeza del Queue.
boolean offer(E e)
// Inserta el elemento especificado en el Queue
// si hay tamaño suficiente. Devuelve un booleano.
// como add
E peek()
// Recupera sin borrar la cabeza del Queue o
// devuelve null si el Queue está vacío.
E poll()
// Recupera y elimina la cabeza del Queue o
// devuelve null si el Queue está vacío.
E remove()
// Recupera y elimina la cabeza del Queue.
EJEMPLO
import java.util.LinkedList;
import java.util.Queue;
public class Main {
public static void main(String[] args) {
/*Creamos la Cola Indicando el tipo de dato*/
Queue<Integer> cola=new LinkedList();
/*Insertamos datos*/
cola.offer(3);
cola.add(14);
cola.offer(12);
cola.add(7);
cola.offer(10);
/*Impresion de la Cola llena con los datos*/
System.out.println("Cola llena: " + cola);
/*Estructura repetitiva para desencolar*/
while(cola.poll()!=null){//Desencolamos y el valor se compara con
null
System.out.println(cola.peek());//Muestra el nuevo Frente
}
/*Muestra null debido a que la cola ya esta vacia*/
System.out.println(cola.peek());
}
}
PRIORITYQUEUE
• Paquete:
java.util
Class PriorityQueue<E>
java.lang.Object
java.util.AbstractCollection<E>
java.util.AbstractQueue<E>
java.util.PriorityQueue<E>
PriorityQueue()
// Crea un PriorityQueue con una capacidad inicial de 11
//posiciones y ordena los elementos de forma natural.
• Permite duplicados.
q.add(“A”);
q.add(“A”); // 2 elementos
• Si utilizamos Comparator con primitivos internamente hara un AutoBoxing para poder usar el
Comparator.
boolean remove(Object)
// Elimina un elemento de la PriorityQueue.
pq.remove("A");
E peek()
// Devuelve 1 elemento en función del orden y no elimina.
String primero = pq.peek();
//tememos los mismos elementos
E poll()
// Devuelve 1 elemento en función del orden y lo elimina.
String primero = pq.poll();
//hemos eliminado el 1º elemento
Iterator<E> iterator()
// NO ORDENADOS.
java.util.Iterator i = pq.iterator();
Object[] toArray()
// Devuelve un Array con los elementos de PriorityQueue.
String[] nums = pq.toArray();
//OFFER(E) añadir
for(Integer i:nums)pq.offer(i);
//SIZE()
System.out.println("size: " + pq.size());
// 4
//ITERATOR(), no orden.
Iterator it = pq.iterator();
//ADD
pq.add(new Integer(1)); // permite duplicados
try{
pq.offer(null);
// Error ejecución, no permite nulos.
}catch(java.lang.NullPointerException e){
//RuntimeException.NullPointerException
System.out.println("\n Error, PriorityQueue no "+
" permite nulos!");
}
//ADD(E)
System.out.println("\n Añade 5 -> add(5) : " +
pq.add(new Integer(5)));
// true
//ELEMENT()
System.out.println("Devuelve el 1º elemento sin "+
" borrar -> element(): " + pq.element());
// 1
//PEEK()
System.out.println("Devuelve el 1º sin " +
" borrarlo -> peek(): " + pq.peek());
// 1
//POLL()
System.out.println("Devuelve el 1º y lo " +
" elimina -> poll(): " + pq.poll());
// 1
//REMOVE()
System.out.println("Devuelve el 1º elemento " +
" y lo elimina -> remove: " + pq.remove());
// 1
//SIZE()
System.out.println("size: " + pq.size());
// 4
//ITERATOR(), no orden
Iterator<Integer> itc = pqc.iterator();
while(itc.hasNext())System.out.print(itc.next() + " ");
// 9 8 7 6
}
Constructor Summary
Constructors
Constructor and Description
PriorityQueue()
Creates a PriorityQueue with the default initial capacity (11) that orders its elements according to
their natural ordering.
PriorityQueue(Collection<? extends E> c)
Creates a PriorityQueue containing the elements in the specified collection.
PriorityQueue(int initialCapacity)
Creates a PriorityQueue with the specified initial capacity that orders its elements according to
their natural ordering.
PriorityQueue(int initialCapacity, Comparator<?
super E> comparator)
Creates a PriorityQueue with the specified initial capacity that orders its elements according to the
specified comparator.
PriorityQueue(PriorityQueue<? extends E> c)
Creates a PriorityQueue containing the elements in the specified priority queue.
PriorityQueue(SortedSet<? extends E> c)
Creates a PriorityQueue containing the elements in the specified sorted set.
ethod Summary
Methods
boolean add(E e)
Inserts the specified element into this priority queue.
void clear()
Removes all of the elements from this priority queue.
boolean contains(Object o)
Returns true if this queue contains the specified element.
Iterator<E> iterator()
Returns an iterator over the elements in this queue.
boolean offer(E e)
Inserts the specified element into this priority queue.
E peek()
Retrieves, but does not remove, the head of this queue, or return
E poll()
Retrieves and removes the head of this queue, or returns null
boolean remove(Object o)
Removes a single instance of the specified element from this queu
int size()
Returns the number of elements in this collection.
Object[] toArray()
Returns an array containing all of the elements in this queue.
<T> T[] toArray(T[] a)
Returns an array containing all of the elements in this queue; the
addAll, element, remove
containsAll, isEmpty, removeAll, retainAll, toString
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wa
it, wait, wait
containsAll, equals, hashCode, isEmpty, removeAll, retainAll
Constructor Detail
PriorityQueue
public PriorityQueue()
Creates a PriorityQueue with the default initial capacity (11) that orders its elements according to
their natural ordering.
PriorityQueue
public PriorityQueue(int initialCapacity)
Creates a PriorityQueue with the specified initial capacity that orders its elements according to
their natural ordering.
Parameters:
Throws:
IllegalArgumentException - if initialCapacity is less than 1
PriorityQueue
public PriorityQueue(int initialCapacity,
Comparator<? super E> comparator)
Creates a PriorityQueue with the specified initial capacity that orders its elements according to the
specified comparator.
Parameters:
Throws:
PriorityQueue
public PriorityQueue(Collection<? extends E> c)
Creates a PriorityQueue containing the elements in the specified collection. If the specified collection is
an instance of a SortedSet or is another PriorityQueue, this priority queue will be ordered
according to the same ordering. Otherwise, this priority queue will be ordered according to the natural
ordering of its elements.
Parameters:
c - the collection whose elements are to be placed into this priority queue
Throws:
PriorityQueue
public PriorityQueue(PriorityQueue<? extends E> c)
Creates a PriorityQueue containing the elements in the specified priority queue. This priority queue will
be ordered according to the same ordering as the given priority queue.
Parameters:
c - the priority queue whose elements are to be placed into this priority queue
Throws:
NullPointerException - if the specified priority queue or any of its elements are null
PriorityQueue
public PriorityQueue(SortedSet<? extends E> c)
Creates a PriorityQueue containing the elements in the specified sorted set. This priority queue will be
ordered according to the same ordering as the given sorted set.
Parameters:
c - the sorted set whose elements are to be placed into this priority queue
Throws:
NullPointerException - if the specified sorted set or any of its elements are null