How to use the removeAt() method of ArrayDeque in Kotlin
Overview
The removeAt() method removes an element at the given index.
An
is a resizable array that allows us to add or remove an element from both the front and back. ArrayDeque Array Double Ended Queue
Syntax
fun removeAt(index: Int): E
Argument
This method takes the index of the element to be removed from the ArrayDeque.
The
IndexOutOfBoundExceptionis thrown if the index value is greater than or equal to the size of thedeque.
Return value
This method returns the element removed from the deque.
Code
The example below demonstrates how to use the removeAt() method to remove an element at the specific index of the deque.
fun main() {// create a new deque which can have string elementsvar deque = ArrayDeque<String>()// add three elements to dequeudeque.add("one");deque.add("two");deque.add("three");println("The deque is " + deque);// remove elements at index 0println("\ndeque.removeAt(0) :" + deque.removeAt(0));println("The deque is $deque \n");try {// index 4 is greater than the size of the dequeprintln("\ndeque.removeAt(4) :" + deque.removeAt(4));} catch (e:Exception) {println(e)}}
Explanation
-
Line 3: We create an
ArrayDequewith the namedeque. -
Lines 6-8: We use the
addmethod to add three elements todeque. Nowdequeis {one, two, three}. -
Line 13: We use the
removeAt()method with0as an argument. This will remove the element at index0and return the removed element. We will getoneas the return value. Nowdequeis {two, three}. -
Line 18: We use the
removeAt()method with4as an argument. Thedequecontains only two elements. When we try to access the index which is greater than or equal to the size ofdeque, we getIndexOutOfBoundsException.