title: Pass by value trouble with java's list add method
body: <pre><code>ArrayList&lt;ArrayList&lt;String&gt;&gt; list1 = new ArrayList&lt;ArrayList&lt;String&gt;&gt;();
  ArrayList&lt;String&gt; list2 = new ArrayList&lt;String&gt;();
  
  list2.add("foo");
  System.out.println(list2); //[foo]
  list1.add(list2);
  System.out.println(list1); //[[foo]]
  list2.set(0, "bar");
  System.out.println(list2); //[bar]
  System.out.println(list1); //[[bar]]
  </code></pre>
  
  <p>The code above shows 2 lists. When I add <code>list2</code> (containing <code>foo</code>) to <code>list1</code> they both now contain <code>foo</code>. But when I modify <code>list2</code> to <code>bar</code>, <code>list1</code> will change as well. I've always thought the add method only gives a copy of <code>list2</code> to <code>list1</code> and what I do to <code>list2</code> will not change for <code>list1</code>.</p>
  
  <p>How can I make it that I add <code>list2</code> to <code>list1</code> but allow <code>list2</code> to be freely modified in the future so <code>list1</code> will not be affected again?</p>