How to use the removeAt() method of ArrayDeque in Kotlin

Overview

The removeAt() method removes an element at the given index.


An ArrayDequeArray Double Ended Queue is a resizable array that allows us to add or remove an element from both the front and back.


Syntax


fun removeAt(index: Int): E

Argument

This method takes the index of the element to be removed from the ArrayDeque.


The IndexOutOfBoundException is thrown if the index value is greater than or equal to the size of the deque.


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 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 elements at index 0
println("\ndeque.removeAt(0) :" + deque.removeAt(0));
println("The deque is $deque \n");
try {
// index 4 is greater than the size of the deque
println("\ndeque.removeAt(4) :" + deque.removeAt(4));
} catch (e:Exception) {
println(e)
}
}

Explanation

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

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

  • Line 13: We use the removeAt() method with 0 as an argument. This will remove the element at index 0 and return the removed element. We will get one as the return value. Now deque is {two, three}.

  • Line 18: We use the removeAt() method with 4 as an argument. The deque contains only two elements. When we try to access the index which is greater than or equal to the size of deque, we get IndexOutOfBoundsException.

Free Resources