How to remove all elements of the ArrayDeque in Kotlin
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 elementsvar deque = ArrayDeque<Int>()// add four elements to dequedeque.add(1)deque.add(2)deque.add(3)deque.add(4)println("\nThe Arraydeque is $deque")// get the last element of dequedeque.clear();println("After calling clear the dequeu is $deque");}
Explanation
In the code above, we see the following:
-
Line 3: We create a new
ArrayDequewith the namedeque. Thedequecontains no element[]. -
Lines 6–9: We add four elements to
dequeusing theaddmethod. Nowdequeis [1,2,3,4]. -
Line 13: We use the
clearmethod to remove all elements present indeque. After calling theclearmethod,dequebecomes empty.