What is the ArrayList.set() 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, which is a mutable list that uses a dynamic resizable array as the backing storage.

The set() method

The ArrayList class contains the set() method, which replaces an element at a specified index with the provided input element.

Syntax

fun set(index: Int, element: E): E

Parameters

  • This method takes the integer index and an element to put on that index as input.

Return value

  • This method returns the element that was previously present at the input index before the set() operation.

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 set() method.

Replacing element at an index using the set() method

Code

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

fun main(args : Array<String>) {
val sportsList = ArrayList<String>()
sportsList.add("Cricket")
sportsList.add("Football")
sportsList.add("Tennis")
sportsList.add("Volleyball")
println("Printing ArrayList elements--")
println(sportsList)
val prevElement = sportsList.set(1,"BasketBall");
println("Replacing element at index 1 using set() with 'BasketBall', previous element is : ${prevElement}")
println("Printing ArrayList elements--")
println(sportsList)
}

Explanation

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

  • Next, we use the add() method to add a few sport names to the ArrayList object, such as: "Cricket", "Football", "Tennis", and "Volleyball".

  • Next, we call the set() method by passing 1 as the input index and BasketBall as the input value, and it returns Football after replacing the element at index 1 - Football with BasketBall.

  • We use the print() function of the kotlin.io package to display the Arraylist elements and result of the set() method.

Free Resources