Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

get
arraydeque
kotlin
communitycreator

Get an element at the specific index of ArrayDeque in Kotlin

Programming Bytes

Overview

In Kotlin, the get method is used to get an element at a given index.

Syntax

fun get(index: Int): E

Parameters

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 the deque.

Return value

This method returns the element at a given index.

Example

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("\nThe deque is " + deque);

  // get elements at index
  println("\ndeque.get(0) :" + deque.get(0));
  println("\ndeque.get(2) :" + deque.get(2));
  
  try {
    // index 4 is greater than the size of the deque
    println("\ndeque.get(4) :" + deque.get(4));
  } catch (e:Exception) {
    println(e)
  } 
}
Using the get method

Explanation

  • 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.

RELATED TAGS

get
arraydeque
kotlin
communitycreator
RELATED COURSES

View all Courses

Keep Exploring