Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

removefirst
arraydeque
kotlin
communitycreator

How to use the removeFirst method of ArrayDeque in Kotlin

Programming Bytes

Overview

The removeFirst method removes and returns the first element of the ArrayDeque.

If the deque is empty, NoSuchElementException will be thrown.

Syntax

// remove first element
fun removeFirst(): E

Argument

This method doesn’t take any argument.

Return value

The removeFirst method returns the first element, which is removed.

Code

The code below demonstrates the use of ArrayDeque's removeFirst method:

fun main() {
    // create a new deque which can have string elements
    var deque = ArrayDeque<String>();

    // add three elements to dequeu
    deque.add("one");
    deque.add("two");
    deque.add("three");
    println("The deque is " + deque);

    // remove the first element of the deque
    var removedElement = deque.removeFirst();
    println("\nThe first element removed from the queue is :" + removedElement); 
    println("The deque is " + deque);
}
Using the removeFirst method

Explanation

Line 3: We create an ArrayDeque named deque.

Lines 6-8: We use the add method to add three elements to the deque. Now, the deque is {one,two,three}.

Line 12: We use the removeFirst method to remove and return the first element of the deque. In our case, one is removed from the deque and returned. Now the queue is {two, three}.

RELATED TAGS

removefirst
arraydeque
kotlin
communitycreator
RELATED COURSES

View all Courses

Keep Exploring