Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




KOTLIN - REPLACE ARRAY ELEMENTS


How to change/replace an Item in an Array?


Let us say, we have a Array that contains three names, 'Mohan', 'John', 'Paul', 'Kriti' and 'Salim'.


And we want to replace the name 'John' with a new name 'Neal'.


Example :



fun main() {

    var arr = arrayOf("Mohan", "John", "Paul", "Kriti", "Salim")
        
    println("\nBefore replacing the second element\n")
        
    for(str in arr) {
        println(str)
    }
        
    arr[1] = "Neal"
        
    println("\nAfter replacing the second element\n")
        
    for(str in arr) {
        println(str)
    }
}


Output :


Before replacing the second element



 Mohan
 John
 Paul
 Kriti
 Salim

After replacing the second element



 Mohan
 Neal
 Paul
 Kriti
 Salim

So, in the above code we have created a 'Array' and initialised to the variable 'x'.


var arr = arrayOf("Mohan", "John", "Paul", "Kriti", "Salim")

Now, let us see, how the values are positioned in the Array


java_Collections

Now, if we see the above diagram, 'John' resides at position/index '1'. So, what we do is,just replace the position/index '1' (i.e. arr[1]) with the new name 'Neal'.


arr[1] = "Neal"

java_Collections

And the name 'John' gets replaced with 'Neal'.


And we get the below output,


[Mohan Neal Paul Kriti Salim]

Change/replace an Item in an Array using set() method


Let us rewrite the above example using set() method.


And we want to replace the name 'John' with a new name 'Neal'.


Example :



fun main() {

    var arr = arrayOf("Mohan", "John", "Paul", "Kriti", "Salim")
        
    println("\nBefore replacing the second element\n")
        
    for(str in arr) {
        println(str)
    }
        
    arr.set(1, "Neal")
        
    println("\nAfter replacing the second element\n")
        
    for(str in arr) {
        println(str)
    }
}


Output :


Before replacing the second element



 Mohan
 John
 Paul
 Kriti
 Salim

After replacing the second element



 Mohan
 Neal
 Paul
 Kriti
 Salim

So if you see the output, the second value 'John' is replaced with 'Neal'.


And this time we have used the 'set()' method to achieve it.


arr.set(1, "Neal")