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
fun removeAt(index: Int): E
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 thedeque
.
This method returns the element removed from the deque
.
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)}}
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
.