Skip to main content

How to replace an element in an ArrayList in Kotlin

How to replace an element in an ArrayList in Kotlin.

Here's a step-by-step tutorial on how to replace an element in an ArrayList in Kotlin:

Step 1: Create an ArrayList

To begin with, you need to create an ArrayList and populate it with some elements. You can do this by using the ArrayList constructor or by using the add() method.

val arrayList = ArrayList<String>()
arrayList.add("Apple")
arrayList.add("Banana")
arrayList.add("Cherry")

Step 2: Find the Index of the Element to Replace

Next, you need to find the index of the element that you want to replace. You can use the indexOf() method to accomplish this.

val elementIndex = arrayList.indexOf("Banana")

Step 3: Replace the Element

Now that you have the index of the element, you can replace it with a new value using the set() method of the ArrayList.

arrayList.set(elementIndex, "Mango")

Alternatively, you can also use the index operator ([]) to replace the element.

arrayList[elementIndex] = "Mango"

Step 4: Verify the Replacement

If you want to ensure that the element has been replaced successfully, you can print the updated ArrayList.

println(arrayList)

Here's the complete code example:

fun main() {
val arrayList = ArrayList<String>()
arrayList.add("Apple")
arrayList.add("Banana")
arrayList.add("Cherry")

val elementIndex = arrayList.indexOf("Banana")
arrayList.set(elementIndex, "Mango")
// or
// arrayList[elementIndex] = "Mango"

println(arrayList)
}

Output:

[Apple, Mango, Cherry]

That's it! You have successfully replaced an element in an ArrayList in Kotlin.