ArrayList<String> objects point to null. Why? : <p>I have a piece of code that takes in an <code>ArrayList&lt;String&gt;</code> object and eventually takes that object and adds it to a <code>HashMap</code> object as the key. When I print the hashmap, the key's are all null while the values are correct.</p>

<p>I already know I can fix the code by passing in a copy of the <code>ArrayList&lt;String&gt;</code> object and that fixes my issue (i.e. <code>buildHash(new ArrayList&lt;String&gt;(key))</code>. But why does it point to null otherwise?</p>

<pre class="lang-java prettyprint-override"><code>HashMap&lt;ArrayList&lt;String&gt;, ArrayList&lt;String&gt;&gt; hash = new HashMap&lt;&gt;();
ArrayList&lt;String&gt; key = new ArrayList&lt;String&gt;();

for (int i = 0; i &lt;= 9999999; i++) {
     key.add(//different strings depending on the iteration);
     if ( !hash.contains(key) ) {
          buildHash(key);
     }
     key.clear();
}

private void buildHash(ArrayList&lt;String&gt; key) {
    ArrayList&lt;String&gt; follows = new ArrayList&lt;String&gt;();
    for (int index = 0; index &lt;= 9999999; index++) {
         // add stuff to follows...
    }
    hash.put(key, follows);
}
</code></pre>

<p>I thought that the value of the key would be added to the hash, and the hash's keys would point to the value it was before it was cleared by <code>key.clear()</code>. That way I could reuse key over and over without creating another object in memory. </p>

<p>I'm new to Java (and coding) so I'm probably naive, but I thought I could save memory by utilizing the mutability of <code>ArrayLists</code> as opposed to <code>Lists</code> as the number of operations and key's generated for this project are well into the millions, if not more. Is there no avoiding that? And if not, is there any other optimization I could do?</p>
