What is the ArrayDeque.addFirst() method in Kotlin?

The kotlin.collections package is part of Kotlin’s standard library. It contains all collection types, such as map, list, set, etc. The package provides the ArrayDeque class, a mutable double-ended queue, and uses a dynamic, resizable array as backup storage.

The addFirst() method

The ArrayDeque class contains the addFirst() method, which adds the specified element to the beginning of the queue.

ArrayDeque implements the deque data structure using a resizable array. Deque (pronounced as “deck”) stands for double-ended queue. This class provides methods to access both ends of a queue.

Syntax

fun addFirst(element: E)

Arguments

  • This method takes an element of type E as input.

Return value

  • This method does not return any value.

The illustration below shows the addFirst() method of the ArrayDeque class.

Adding an element to start of the queue using ArrayDeque.addFirst()
fun main() {
val monthQueue = ArrayDeque<String>()
monthQueue.add("February")
monthQueue.add("March")
monthQueue.add("April")
println("Printing Queue elements --")
println(monthQueue)
monthQueue.addFirst("January")
println("Printing Queue elements after calling addFirst() --")
println(monthQueue)
}

Explanation

  • Line 2: We create an empty queue named monthQueue to store the strings.

  • Lines 4-6: We add a few months’ names to the monthQueue object using the add() method.

  • Lines 8-9: We print all the elements present in the queue.

  • Lines 11: We call the addFirst() method and add "January" to the start of the queue.

  • Line 12-13: We print the elements of monthQueue after calling the addFirst() method. As we can observe, "January" is present at the beginning of the printed queue.

The ArrayDeque elements before and after calling addFirst() method are displayed using the println() function of the kotlin.io package.

Free Resources