title: Why is my ArrayList being populated with duplicate node values?
body: <p>It should simply be 5=[6] for node 5, why 3 different values. Also, I know, this current code is buggy big time, because it would even do 2=[3,3] when I add in edges like 2,1 and 2,3. It just keeps replacing the old values with the last one and duplicates it. Here's an image with the results.</p>
  
  <p><strong>Graph.java</strong></p>
  
  <pre><code>import java.util.ArrayList;
  import java.util.HashMap;
  import java.util.Map.Entry;
  
  
  public class Graph {
  
      HashMap &lt;Integer, ArrayList&lt;Integer&gt;&gt; adj =new HashMap&lt;Integer, ArrayList&lt;Integer&gt;&gt;();
  
      public void addEdge(int source, int destination) {
  
          ArrayList&lt;Integer&gt; list = new ArrayList&lt;Integer&gt;();
          adj.put(source,list);
          list.add(destination);
  
          for(Entry&lt;Integer, ArrayList&lt;Integer&gt;&gt; entry: adj.entrySet()) {
              int existing = entry.getKey();
              System.out.println("Existing: "+existing);
              System.out.println("Source: " +source);
              if (source != existing) {
                  //adj.get(2).add(9);
                  //System.out.println(source +": "+ destination);
                  adj.get(source).add(destination); 
  
              }
  
          }
  
  
      }
  
  
      public void print() {
          System.out.println(adj);
      }
  
  
  }
  </code></pre>
  
  <p><strong>AdjacencyList.java</strong></p>
  
  <pre><code>import java.util.Scanner;
  
  
  
  public class AdjacencyList {
  
      public static void main(String[] args) {
  
          Scanner in = new Scanner (System.in);
          System.out.println("Enter nodes below like (u,v):");
  
          Graph g = new Graph();
  
          for (int i=0; i&lt;3; i++)  {
  
              String nodes = in.nextLine();
              String[] data = nodes.split(",");
  
              String u    = data[0]; 
              String v    = data[1];
              int inNode  = Integer.parseInt(u);
              int outNode =Integer.parseInt(v);
  
              g.addEdge(inNode,outNode);
              System.out.println("Added to list");
  
          }
  
  
            g.print();
  
      }
  
  }
  </code></pre>