Wednesday 20 June 2012

Library (Pustaka) Queue dalam Bahasa Pemrograman Java

Sama halnya dengan library Linked List maupun Stack, bahasa pemrograman Java juga telah menyediakan pustaka khusus untuk implementasi struktur data queue (antrian). Dengan adanya pustaka ini, programmer tidak perlu lagi menuliskan class dan method primitif untuk queue. Sebaliknya, programmer cukup mendeklarasikan obyeknya dan langsung memanggil/ menjalankan fungsi-fungsi (method) yang diinginkan.

Dalam penjelasan resmi di situs oracle.com, ada 5 method utama dalam pustaka queue. Yaitu element(), offer(object), peek(), poll(), dan remove(). Berikut ini contoh program sederhananya:

import java.util.LinkedList;
import java.util.Queue;

/**
*
* @author javadb.com
*/
public class Main {

/**
* Example method for using a Queue
*/
public void queueExample() {

Queue queue = new LinkedList();

//Using the add method to add items.
//Should anything go wrong an exception will be thrown.
queue.add(“item1″);
queue.add(“item2″);

//Using the offer method to add items.
//Should anything go wrong it will just return false
queue.offer(“Item3″);
queue.offer(“Item4″);

//Removing the first item from the queue.
//If the queue is empty a java.util.NoSuchElementException will be thrown.
System.out.println(“remove: ” + queue.remove());

//Checking what item is first in line without removing it
//If the queue is empty a java.util.NoSuchElementException will be thrown.
System.out.println(“element: ” + queue.element());

//Removing the first item from the queue.
//If the queue is empty the method just returns false.
System.out.println(“poll: ” + queue.poll());

//Checking what item is first in line without removing it
//If the queue is empty a null value will be returned.
System.out.println(“peek: ” + queue.peek());

}

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().queueExample();
}
}

Sumber:
- http://www.javadb.com/using-a-queue-or-linkedlist
- http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Queue.html