Tuesday, 22 January 2019

Groovy: lists: Set the element at given position


There are three ways to set element at given position.
a.   Using index notation
b.   Using putAt method
c.    Using set method

HelloWorld.groovy
evenNumbers = [0, 2, 4, 6]

evenNumbers[0] = 8
evenNumbers.putAt(1, 10)
evenNumbers.set(2, 12)

println evenNumbers

Output
[8, 10, 12, 6]

‘set' method return old value in the list.


HelloWorld.groovy
evenNumbers = [0, 2, 4, 6]

oldValue = evenNumbers.set(2, 12)

println "oldValue : ${oldValue}"
println "evenNumbers : ${evenNumbers}"

Output
oldValue : 4
evenNumbers : [0, 2, 12, 6]


Previous                                                 Next                                                 Home

No comments:

Post a Comment