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
-1if the input element is not present in the list.
Things to note
-
ArrayListfollows the sequence of insertion of elements. -
It is allowed to contain duplicate elements.
The illustration below shows the function of 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
fruitListto store the strings. -
Next, we add a few fruit names to the
ArrayListobject using theadd()method, such as:"Orange","Apple","Grapes", and"Banana". -
Next, we call the
indexOf()method by passingAppleas input, and it returns1. -
We call the
indexOf()method by passingBananaas input, and it returns3. -
Next, we call the
indexOf()method by passingStrawberryas input, and it returns-1, asStrawberryis not present in the array list. -
The
Arraylistelements and result of theindexOf()method are displayed using theprint()function of thekotlin.iopackage.