Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy a list in Groovy

Tags:

groovy

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?

like image 558
Matthias Avatar asked Sep 04 '25 17:09

Matthias


2 Answers

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.

like image 72
grantmcconnaughey Avatar answered Sep 07 '25 17:09

grantmcconnaughey


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.

like image 38
dmahapatro Avatar answered Sep 07 '25 16:09

dmahapatro