I have the following Groovy list:
l = [1, 2, 3]
println(l)
Which gives me:
[1, 2, 3]
Now I want to create a copy of this list:
println(l*.collect())
But this gives me the following:
[[1], [2], [3]]
Apparently I got a list of lists.
How can I create a list of the same objects as in the original list?
You are using the spread operator (*
), which is making a list out of each element. Remove that:
list1 = [1, 2, 3]
println list1
list2 = list1.collect()
assert list2 == [1, 2, 3]
Check out the doc for more info on that method.
def list = [1, 2, 4]
//by value
def clonedList = list.clone() //or list.collect()
assert clonedList == list
assert !clonedList.is(list) //Reference inequality
list.pop() //modify list
assert clonedList == [1, 2, 4]
assert list == [1, 2]
//by reference
def anotherList = list
assert anotherList == [1, 2]
assert anotherList.is(list) //Reference equality
list.pop() //modify again
assert list == [1]
assert anotherList == [1]
Run it here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With