Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

removelast
arraydeque
kotlin
communitycreator

How to use the removeLast method of ArrayDeque in Kotlin

Programming Bytes

Overview

The removeLast method removes and returns the last element of the ArrayDeque.

If the deque is empty, then a NoSuchElementException will be thrown.

Syntax

// remove first element
fun removeLast(): E

Parameters

This method doesn’t take any parameters.

Return value

The removeLast method returns the last element which was removed.

Code example

The code below demonstrates how to use the removeLast method of the ArrayDeque:

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

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

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

Code explanation

In the code above, we see the following:

  • Line 3: We create an ArrayDeque with the name deque.

  • Lines 6 to 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 removeLast method to remove and return the last element of the deque. In our case, three is removed from the deque and returned. Now the queue is {one, two}.

RELATED TAGS

removelast
arraydeque
kotlin
communitycreator
RELATED COURSES

View all Courses

Keep Exploring