FreeCode

Donate HTML/CSS JavaFX Java Home
Array Data Structures Array List Data Structures Linked List Data Structures Stack Data Structures Queue Data Structures While Loops Do-While Loops For Loops For-each Loops If, Else, and Multi-Way If Statements Switch Statements Try-Catch Blocks Comment Types and Javadoc Java Classes Java Methods

Queue Data Structures

Code Description:

The Queue data structure should be used when elements that were first added need to be accessed first. A Queue can be thought of as a group of people waiting in line, the sooner a person shows up to the line, the sooner they will be served. Interestingly, a Queue is not 0 based like an array. The bottom element has an index of 1. This has the opposite functionality of a Stack which implements a last in, first out (LIFO) implementation.

Queue Syntax:

Queue<String> queue = new LinkedList<String>();

Runnable Queue Example Code:

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

public class Demo {

    public static void main(String[] args) {
		
	Queue<String> queue = new LinkedList<String>();
		
	queue.offer("Queue Element 1");
	queue.offer("Queue Element 2");
	queue.offer("Queue Element 3");
	queue.offer("Queue Element 4");
	queue.offer("Queue Element 5");
		
	System.out.println("The Element at the front of the queue is: " + queue.peek());
	System.out.println("We are removing the front element");
	queue.poll();
	System.out.println("The Element now in front of the queue is: " + queue.peek());

    }
	
}

How to Run This Code:

Make sure that your Class name is the same as ours. In this case, we are using the Class name of "Demo". Alternatively, you can change the Class name in the provided code to match yours.

Output:

Queue Output Image

Important Methods:

  • element() - retrieves the head of the queue and throws an exception if empty.
  • peek() - retrieves the head of the queue and returns null if empty.
  • remove() - removes and gets the head of the queue and throws an exception if empty.
  • poll() - removes and gets the head of the queue and returns null if empty.
  • offer() - inserts and element in the queue.
  • clear() - removes all elements in the queue.

Related Links:

For-each Loops Stack Data Structures Array Data Structures Linked List Data Structures Array List Data Structures