Reputation: 59
This is what I am trying to do.
Inside a loop i am generating list items in the format [a,1]. First element is a string, second is a number. Once I have all the lists from the loop, I need to put this in another list. example -> [[a,1],[b,2],[c,3]]
This is my sample code I was trying albeit with just the int element. I am unfortunately not able to get what i am looking for. Should be something simple I am overlooking.
a = [1,2]
b = []
c = []
a.each
{
b.clear()
b.add(it)
println b
c.add(b)
}
println c
Output generated is
[1]
[2]
[[2], [2]]
I am trying to get
[1]
[2]
[[1], [2]]
EDIT
After help from Alexander
a = [1,2]
c = []
a.each
{
b = []
b.add(it)
c.add(b)
}
println c
Upvotes: 0
Views: 512
Reputation: 59
Came across an easier way to achieve this. Using collate()
a = [1,2]
a.collate(1)
Result [[1],[2]]
Upvotes: 1
Reputation: 399
You insert into c a reference to the same list twice. Hence you get what you put.
Try to replace b.clear()
with b = []
Then it will be a new list.
Upvotes: 0