What is the ArrayList.indexOf() method in Kotlin?

The kotlin.collections package is part of Kotlin’s standard library, and it contains all collection types, such as Map, List, Set, etc. The package provides the ArrayList class, which is a mutable list and uses a dynamic resizable array as the backing storage.

The indexOf() method

The ArrayList class contains the indexOf() method, which returns the index of the first occurrence of a specified element in the array list, or -1, if the element is not contained in the list.

Syntax

fun indexOf(element: E): Int

Arguments

  • This method takes the element to search as the input.

Return value

  • It returns the integer index of the element in the array list, or -1 if the input element is not present in the list.

Things to note

  • ArrayList follows the sequence of insertion of elements.

  • It is allowed to contain duplicate elements.

The illustration below shows the function of the indexOf() method.

Getting index of elements in an array list using the indexOf() method

Code

The ArrayList class is present in the kotlin.collection package and is imported by default in every Kotlin program.

fun main(args : Array<String>) {
val fruitList = ArrayList<String>()
fruitList.add("Orange")
fruitList.add("Apple")
fruitList.add("Grapes")
fruitList.add("Banana")
println("Printing ArrayList elements--")
println(fruitList)
println("Index of 'Apple' in array list using indexOf() : ${fruitList.indexOf("Apple")}")
println("Index of 'Apple' in array list using indexOf() : ${fruitList.indexOf("Banana")}")
println("Index of 'Strawberry' in array list using indexOf() : ${fruitList.indexOf("Strawberry")}")
}

Explanation

  • First, we create an empty array list named fruitList to store the strings.

  • Next, we add a few fruit names to the ArrayList object using the add() method, such as: "Orange", "Apple", "Grapes", and "Banana".

  • Next, we call the indexOf() method by passing Apple as input, and it returns 1.

  • We call the indexOf() method by passing Banana as input, and it returns 3.

  • Next, we call the indexOf() method by passing Strawberry as input, and it returns -1, as Strawberry is not present in the array list.

  • The Arraylist elements and result of the indexOf() method are displayed using the print() function of the kotlin.io package.

Free Resources