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.
set()
methodThe ArrayList
class contains the set()
method, which replaces an element at a specified index with the provided input element.
fun set(index: Int, element: E): E
set()
operation.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.
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)}
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.