In Kotlin, the get
method is used to get an element at a given index.
fun get(index: Int): E
This method takes an argument, index
, of the element to be retrieved 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 at a given index.
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("\nThe deque is " + deque);// get elements at indexprintln("\ndeque.get(0) :" + deque.get(0));println("\ndeque.get(2) :" + deque.get(2));try {// index 4 is greater than the size of the dequeprintln("\ndeque.get(4) :" + deque.get(4));} catch (e:Exception) {println(e)}}
Line 1: We create the main()
function.
Line 3: We create an ArrayDeque
with the name deque.
Lines 6–8: We use the add
method to add three elements to the deque
. Now, the deque
is {one,two,three}
.
Line 13: We use the get
method with 0
as an argument. This returns the element at index 0
of deque.
We get one
as a result.
Line 14: We use the get
method with 1
as an argument. This returns the element at index 1
of deque.
and the result is ‘two’.
Line 18: We use the get
method with 4
as an argument. The deque
contains only 3
elements. Therefore, when we try to access the index greater than 2
, we get IndexOutOfBoundsException.