Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

arraydeque
kotlin
indexof
communitycreator

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

Programming Bytes

Overview

The indexOf() method will return the index of the first occurrence of the specified element in the ArrayDeque object.

Syntax

fun indexOf(element: E): Int

Parameter

  • element: The element to be searched in the deque is passed as an argument.

Return value

This method returns the first index at which the specified element is present in the deque. If the element is not present in the deque, then -1 is returned.

Example

The method below demonstrates how to use the indexOf() method:

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("one");
  deque.add("two");
  deque.add("three");

  println("\nThe deque is " + deque);

  // get indexOf "one"
  println("\ndeque.indexOf('one') : " + deque.indexOf("one"));
  
  // get indexOf "five"
  println("\ndeque.indexOf('five') : " + deque.indexOf("five"));
  
}
Using the indexOf method

Explanation

In the above code,

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

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

  • Line 14: We use the indexOf method of the deque object to get the index of the first occurrence of the element "one". The element "one" is present at two indices: 0 and 1. We get 0 as a result since that is the first occurrence.

  • Line 17: We use the indexOf method of the deque object to get the index of the first occurrence of the element "five". The element "five" is not present so -1 is returned.

RELATED TAGS

arraydeque
kotlin
indexof
communitycreator
RELATED COURSES

View all Courses

Keep Exploring