how to get index of item in arraylist in kotlin
To get the index of an item in an ArrayList in Kotlin, you can follow these steps:
- Create an ArrayList and add elements to it.
- Use the
indexOf()
function to find the index of the desired item.
Here's an example:
val arrayList = ArrayList<String>()
arrayList.add("Apple")
arrayList.add("Banana")
arrayList.add("Orange")
val index = arrayList.indexOf("Banana")
println("Index of 'Banana': $index")
In this example, we create an ArrayList called arrayList
and add three elements to it: "Apple", "Banana", and "Orange". We then use the indexOf()
function to find the index of the item "Banana" in the ArrayList. The index is stored in the variable index
, and we print it out using println()
.
The output will be:
Index of 'Banana': 1
The indexOf()
function returns the index of the first occurrence of the specified item in the ArrayList. If the item is not found, it returns -1.
Please note that the index is zero-based, so the first item has an index of 0, the second item has an index of 1, and so on.