Queue implementation in Java

Queues operate in FIFO model.

Queues are also used in various other data structures, some of them are

  • searching graphs
  • printer queues in our machines
  • keystroke data that is typed onto the keyboard

Efficiency of queue is that it performs insert and remove operations in O(1) complexity.

package algorithm.queue;

/**
 * @author ntallapa
 *
 */
public class TNQueue {
	private int size;
	private int[] queueArr;
	private int front = -1;
	private int rear = -1;
	private int totalItems;

	public TNQueue(int s) {
		size = s;
		queueArr = new int[s];
	}

	public void insert(int i) {
		rear++;
		System.out.println("Inserting "+i);
		queueArr[rear] = i;
		totalItems++;
	}

	public int remove() {
		front++;
		totalItems--;
		System.out.println("Removing "+queueArr[front]);
		return queueArr[front];
	}

	public boolean isFull() {
		return (totalItems == size);
	}

	public boolean isEmpty() {
		return (totalItems == 0);
	}
}

package algorithm.queue;
/**
 * @author ntallapa
 *
 */
public class TNQueueClient {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		TNQueue tnq = new TNQueue(3);
		if(!tnq.isFull())
			tnq.insert(1);
		if(!tnq.isFull())
			tnq.insert(2);
		if(!tnq.isFull())
			tnq.insert(3);
		if(!tnq.isFull())
			tnq.insert(4);
		else
			System.out.println("Queue is full, cannot insert element");

		if(!tnq.isEmpty())
			tnq.remove();
		if(!tnq.isEmpty())
			tnq.remove();
		if(!tnq.isEmpty())
			tnq.remove();
		if(!tnq.isEmpty())
			tnq.remove();
		else
			System.out.println("Queue is empty, cannot remove element");
	}
}

Output:
Inserting 1
Inserting 2
Inserting 3
Queue is full, cannot insert element
Removing 1
Removing 2
Removing 3
Queue is empty, cannot remove element

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Mawazo

Mostly technology with occasional sprinkling of other random thoughts

amintabar

Amir Amintabar's personal page

101 Books

Reading my way through Time Magazine's 100 Greatest Novels since 1923 (plus Ulysses)

Seek, Plunnge and more...

My words, my world...

ARRM Foundation

Do not wait for leaders; do it alone, person to person - Mother Teresa

Executive Management

An unexamined life is not worth living – Socrates

javaproffesionals

A topnotch WordPress.com site

thehandwritinganalyst

Just another WordPress.com site

coding algorithms

"An approximate answer to the right problem is worth a good deal more than an exact answer to an approximate problem." -- John Tukey

%d bloggers like this: