Está en la página 1de 10

COLA – QUEUE EN JAVA 

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:

public interface Queue<E> extends Collection<E>, Iterable<E>

• Interfaz Queue ordenada cosas por el orden en que van a ser procesados. Por defecto ordena
como FIFO pero puede ordenar de otras formas.

• Queue generalmento NO PERMITE NULOS pero alguna de sus implementaciones como


LinkedList si que los permiten.

Algunos métodos de Queue:

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>

• Algún constructor de Queue:

PriorityQueue()
// Crea un PriorityQueue con una capacidad inicial de 11
//posiciones y ordena los elementos de forma natural.

PriorityQueue(int initialCapacity, Comparator<? super E>


comparator)
// Crea un PriorityQueue con la capacidad inicial que le
indiquemos
// y ordena de acuerdo al Comparator que le pasemos.

• Ordena de forma natural (ascendente) o según un Comparator y ese orden representa su


prioridad.

• Permite duplicados.

q.add(“A”);

q.add(“A”); // 2 elementos

• No permite nulos. Da error en tiempo de ejecución.

q.add(null); // error en ejecución

• PriorityQueue permite trabajar con primitivos y con Referencias.

• PriorityQueue permite trabajar con Comparator.

• Si utilizamos Comparator con primitivos internamente hara un AutoBoxing para poder usar el
Comparator.

Algunos métodos de PriorityQueue:

boolean remove(Object)
// Elimina un elemento de la PriorityQueue.
   pq.remove("A");

boolean add(e) y offer(e)


// Añaden un elemento.
   pq.add("A");
   pq.offer("A"); // dos 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();

EJEMPLO DE USO DE PRIORITYQUEUE

// NO OLVIDAR IMPORTAR UTIL!!


import java.util.*;

public class C1{

    public static void main(String[] args){

        PriorityQueue<Integer> pq = new PriorityQueue<Integer>();


        // Ordena de forma natural

        Integer[] nums = {4,3,1,2};

        //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();

        while(it.hasNext())System.out.print(it.next() + " ");


        // 1 2 3 4

        //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

        // CONSTRUCTOR CON COMPARATOR


        PriorityQueue<Integer> pqc =
                 new PriorityQueue<Integer>(8, new PQsort());

        Integer[] vals = {9,6,7,8};

        for(Integer i:vals) pqc.offer(i);

        //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

Modifier and Type Method and Description

boolean add(E e)
Inserts the specified element into this priority queue.

void clear()
Removes all of the elements from this priority queue.

Comparator<? super E> comparator()


Returns the comparator used to order the elements in this 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

 Methods inherited from class java.util.AbstractQueue

addAll, element, remove

 Methods inherited from class java.util.AbstractCollection

containsAll, isEmpty, removeAll, retainAll, toString

 Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, wa
it, wait, wait

 Methods inherited from interface java.util.Collection

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:

initialCapacity - the initial capacity for this priority queue

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:

initialCapacity - the initial capacity for this priority queue


comparator - the comparator that will be used to order this priority queue. If null, the natural
ordering of the elements will be used.

Throws:

IllegalArgumentException - if initialCapacity is less than 1

 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:

ClassCastException - if elements of the specified collection cannot be compared to one


another according to the priority queue's ordering

NullPointerException - if the specified collection or any of its elements are null

 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:

ClassCastException - if elements of c cannot be compared to one another according to c's


ordering

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:

ClassCastException - if elements of the specified sorted set cannot be compared to one


another according to the sorted set's ordering

NullPointerException - if the specified sorted set or any of its elements are null

También podría gustarte