Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

kotlin
communitycreator

How to remove all elements of the ArrayDeque in Kotlin

Programming Bytes

Overview

We can use the clear method to remove all the elements present in the ArrayDeque object.

Syntax

fun clear()

Parameters

This method doesn’t take any arguments.

Return value

This method doesn’t return any value.

Code

The code below demonstrates how to use the clear method to remove all elements present in the ArrayDeque:

fun main() {
    // create a new empty ArrayDeque which can have int elements
    var deque = ArrayDeque<Int>()

    // add four elements to deque
    deque.add(1)
    deque.add(2)
    deque.add(3)
    deque.add(4)
    println("\nThe Arraydeque is $deque")

    // get the last element of deque
    deque.clear();
    println("After calling clear the dequeu is $deque");

}
Using the clear method

Explanation

In the code above, we see the following:

  • Line 3: We create a new ArrayDeque with the name deque. The deque contains no element [].

  • Lines 6–9: We add four elements to deque using the add method. Now deque is [1,2,3,4].

  • Line 13: We use the clear method to remove all elements present in deque. After calling the clear method, deque becomes empty.

RELATED TAGS

kotlin
communitycreator
RELATED COURSES

View all Courses

Keep Exploring