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
-
ArrayListfollows the sequence of insertion of elements. -
ArrayListis allowed to contain duplicate elements.
The illustration below shows the function of 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
sportsListto store the strings. -
Next, we use the
add()method to add a few sport names to theArrayListobject, such as:"Cricket","Football","Tennis", and"Volleyball". -
Next, we call the
set()method by passing1as the input index andBasketBallas the input value, and it returnsFootballafter replacing the element at index1-FootballwithBasketBall. -
We use the
print()function of thekotlin.iopackage to display theArraylistelements and result of theset()method.