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

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

The removeAt() method

The ArrayList class contains the removeAt() method, which removes an element at the specified index in the array list.

Syntax

fun removeAt(index: Int): E

Parameters

This method takes an integer index as input.

Return value

The removeAt() method returns the element that is removed at the specified index.

Things to note

  • ArrayList follows the sequence of insertion of elements.

  • ArrayList is allowed to contain duplicate elements.

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

Removing an element at a specified index using the removeAt() method
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)
var removedElement = fruitList.removeAt(2)
println("Removed element is ${removedElement}")
println("Printing ArrayList elements after calling removeAt() --")
println(fruitList)
}

Explanation

  • Line 2: We create an empty array list named fruitList to store the strings.

  • Lines 4 to 7: We use the add() method to add a few fruit names to the ArrayList object, such as "Orange", "Apple", "Grapes", and "Banana".

  • Line 11: We call the removeAt() method and pass the input index as 2. removeAt() removes the element at index 2, "Grapes", and returns the element.

We use the println() function of the kotlin.io package to display the ArrayList elements and result of the removeAt() method.

Free Resources