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.
addFirst()
methodThe 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.
fun addFirst(element: E)
element
of type E
as input.The illustration below shows the addFirst()
method of the ArrayDeque
class.
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)}
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.