title: Copying lists of lists in groovy
body: <p>I want to perform a copy and get two different objects so that I can work on the copy without impacting the original.</p>
  
  <p>I have this code (groovy 2.0.5):</p>
  
  <pre><code>def a = [[1,5,2,1,1], ["one", "five", "two", "one", "one"]]
  def b = a
  b.add([6,6,6,6,6,6])
  println a
  println b
  </code></pre>
  
  <p>that produces:</p>
  
  <pre><code>[[1, 5, 2, 1, 1], [one, five, two, one, one], [6, 6, 6, 6, 6, 6]]
  [[1, 5, 2, 1, 1], [one, five, two, one, one], [6, 6, 6, 6, 6, 6]]
  </code></pre>
  
  <p>seems like b and a are actually the same object</p>
  
  <p>I can fix it in this way:</p>
  
  <pre><code>def a = [[1,5,2,1,1], ["one", "five", "two", "one", "one"]]
  def b = []
  
  a.each {
      b.add(it)
  }
  
  b.add([6,6,6,6,6])
  println a
  println b
  </code></pre>
  
  <p>that produces my wanted result:</p>
  
  <pre><code>[[1, 5, 2, 1, 1], [one, five, two, one, one]]
  [[1, 5, 2, 1, 1], [one, five, two, one, one], [6, 6, 6, 6, 6]]
  </code></pre>
  
  <p>But now look at this, where I want the original object and a copy with unique and sorted elements:</p>
  
  <pre><code>def a = [[1,5,2,1,1], ["one", "five", "two", "one", "one"]]
  def b = a
  
  b.each {
      it.unique().sort()
  }
  
  println a
  println b
  </code></pre>
  
  <p>that produces:</p>
  
  <pre><code>[[1, 2, 5], [five, one, two]]
  [[1, 2, 5], [five, one, two]]
  </code></pre>
  
  <p>If I try the same fix this time it doesn't work:</p>
  
  <pre><code>def a = [[1,5,2,1,1], ["one", "five", "two", "one", "one"]]
  def b = []
  
  a.each { 
      b.add(it)
  }
  
  b.each {
      it.unique().sort()
  }
  
  println a
  println b
  </code></pre>
  
  <p>that still produces: </p>
  
  <pre><code>[[1, 2, 5], [five, one, two]]
  [[1, 2, 5], [five, one, two]]
  </code></pre>
  
  <p>What's going on ?</p>