Let us say, we have a List that contains three names, 'Mohan', 'Kriti' and 'Salim'. And we want to replace the name 'Kriti' with a new name 'Paul'.
fun main() { var x = mutableListOf("Mohan", "Kriti", "Salim") x[1] = "Paul" println(x) }
So, in the above code we have created a 'List' using 'mutableListOf()' method, because we need to replace an element in the List.
Now, let us see, how the values are positioned in the List
Now, if we see the above diagram, 'Kriti' resides at position/index '1'. So, what we do is, just replace the position/index '1' (i.e. x[1]) with the new name 'Paul'.
And we get the below output,
Let us take the same example, where we have a List that contains three names, 'Mohan', 'Kriti' and 'Salim'. And we want to replace the name 'Kriti' with a new name 'Paul'.
fun main() { var x = mutableListOf("Mohan", "Kriti", "Salim") x.set(1, "Paul") println(x) }
So, in the above code we have created a 'List' using 'mutableListOf()' method, because we need to replace an element in the List.
Now, let us see, how the values are positioned in the List
Now, if we see the above diagram, 'Kriti' resides at position/index '1'. So, what we do is,use the 'set()' method specifying the position/index '1' and the new name 'Paul'.
And we get the below output,