title: Why Does My Apex Map Appear To Get Overwritten?
body: <p>I am trying to build a test data factory to create a number of contacts and attach them to an account. The method should return a map of account Id to List of contacts. However, my test class is failing and I can see from the debug logs that all of the contacts are related to one account. I have put debug statements in place so that I can see the map being built inside a loop and it looks okay. Then when I look at the map immediately outside the loop it contains 4 copies of the same contact. Here is my code followed by the debug statements. I've kept it simple by using 2 accounts each with one contact. I'd really like to understand what's going wrong here if anyone can help please.</p>
  <pre><code>public static Map&lt;Id, List&lt;Contact&gt;&gt; createContacts(List&lt;Account&gt; accounts, Integer numOfContacts) {
  
  Map&lt;Id, List&lt;Contact&gt;&gt; mapOfAccountIdToListOfContacts = New Map&lt;Id, List&lt;Contact&gt;&gt;();
  List&lt;Contact&gt; addedContacts = New List&lt;Contact&gt;();
  List&lt;Contact&gt; accContacts = New List&lt;Contact&gt;();
  
      for(Account ac :accounts) {
          accContacts.clear();
          for(Integer i=0;i&lt;numOfContacts;i++) {
              Contact newContact = New Contact(LastName='TestContact' + i,
                                            Email = 'TestContact' + i + '@testco.com',
                                              AccountId = ac.Id);
              accContacts.add(newContact);
          }
          mapOfAccountIdToListOfContacts.put(ac.Id, accContacts);
          System.debug('Map.put=' + ac.id + ', ' + accContacts);
          addedContacts.addAll(accContacts);
      }
      insert addedContacts;
      for(Id key :mapOfAccountIdToListOfContacts.keyset()) {
          System.debug('Contacts=' + mapOfAccountIdToListOfContacts.get(key));
      }
      return mapOfAccountIdToListOfContacts;
  }
  </code></pre>
  <p>and the log output:</p>
  <p><a href="https://i.stack.imgur.com/197ug.png" rel="nofollow noreferrer">It said the log was spam so here's an image of the log.</a>
  Thank you</p>