Tuesday, 22 January 2019

Groovy: Lists can take negative indexes


Groovy support negative indexes.

list[-1] represents last element in the list, list[-2] represents last but one etc.,

HelloWorld.groovy
primes = [2, 3, 5, 7]

println "primes[-1] : ${primes[-1]}"
println "primes[-2] : ${primes[-2]}"
println "primes[-3] : ${primes[-3]}"
println "primes[-4] : ${primes[-4]}"

Output
primes[-1] : 7
primes[-2] : 5
primes[-3] : 3
primes[-4] : 2


'getAt()' method support -ve indexes, but get() do not support -ve indexes.



Previous                                                 Next                                                 Home

No comments:

Post a Comment