top of page

# Queue

In this section, we'll talk about Queues. Queues are on of the most common and fundamental data structures you will come across. They function by a "first-in-first-out" principle, which we will discuss in further detail.

## Queues

When we say "first-in-first-out" principle, we mean that the first thing we insert into the queue will be the first thing that we can take out of it.

Syntax:

This is how we declare queues in Java. We declared a Queue with the name queue, of type "MyObject", which, in this case, is a place holder for a data type such as Integer or String (or something of the sort).

There are many useful methods that we can do with queues in Java. These methods will help us add and remove elements, as well as examine out queue.

Method 1:

This method will add whatever element is in the parenthesis into the queue. For example, if we have an integer queue with elements {1,2,3,4,5}, and we write q.add(6), the new value of q is

{1,2,3,4,5,6}

Method 2:

q.remove()

This method will remove the first element in the queue. Take the example where we had

q. = {1,2,3,4,5}. Then after we take q.remove(), we will get q={2,3,4,5}

Method 3:

q.element()

This method will return the first element in the queue without adding or removing anything. For example, if we have q={1,2,3,4,5,6}, and we let int x = q.element(), then x=1.

More Methods:

Iteration:  As with any data structure, iteration is always important. How do we iterate through a queue?

Example 1:

{

for(Integer item: q){

System.out.println(item);

}

}

When we want to iterate over a queue, we can use an enhanced for loop, or "for-each" loop to do so. This will allow us to access all of the elements in the queue with ease.

Exercise(s):

1. Make an integer Queue, and copy the contents of the queue to another queue using loops. bottom of page