Kotlin Queue Interface

The Queue interface is a first-in, first-out data structure. In other words, the first item that is added to the queue is the first item to be removed. We can picture the queue as a line for a roller coaster. The first person to enter the line is the first person who gets to ride on the roller coaster.

Example Program

We will use a Queue in this example program to simulate a music player. The Queue is filled with songs that we would like to hear and then it plays them one at a time in the order they were added. Here is the code.

package ch6.queue

import java.util.*

fun main(args : Array<String>){
    //Create the Queue. Note that LinkedList is one of the implementing classes
    val playQueue : Queue<String> = LinkedList()

    //Add songs to the Queue 
    with (playQueue){
        add("Swing Life Away")
        add("Give it All")
        add("Dancing for Rain")
        add("Hero of War")
        add("Black Masks and Gasoline")

    //Loop until the Queue is empty
        //The remove() method takes an item from the Queue and returns it
        println("Playing Song => " + playQueue.remove())

The program uses LinkedList as the concrete class to implement the Queue interface. We add five songs to the Queue using the with function and Queue’s add() method. Then we loop until the queue is empty. When we call remove() on the Queue, the first item in the queue is removed and returned. In this way, we print all of the songs added to the Queue one at a time.

Playing Song => Swing Life Away
Playing Song => Give it All
Playing Song => Dancing for Rain
Playing Song => Hero of War
Playing Song => Black Masks and Gasoline

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 )

Twitter picture

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

Facebook photo

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

Connecting to %s

%d bloggers like this: