title: References to nodes in Java linked list
body: <p>I need some help understanding how a method works.</p>
  
  <p>I have a basic <code>Node</code> class defined like this:</p>
  
  <pre><code>class Node {
      Node next = null;
      int data;
      public Node(int d){
          data = d;
      }
  }
  </code></pre>
  
  <p>Now I'm looking at how this <code>deleteDuplicates</code> method is working. I understand that we are passing through each node iteratively and storing its value in a set. If the value is already in the set, I believe we are setting the previous node's <code>next</code> pointer to skip the current node. Here's the method:</p>
  
  <pre><code>public static Node deleteDuplicates(Node head){
      Node n = head;
      HashSet&lt;Integer&gt; set = new HashSet&lt;Integer&gt;();
      Node previous = null;
      while(n != null) {
          if (set.contains(n.data)){
              // skip this node
              previous.next = n.next;
          }
          else {
              set.add(n.data);
              previous = n;
          }
          n = n.next;
  
      }
      return head;
  }
  </code></pre>
  
  <p>I'm confused about the variables <code>previous</code> and <code>n</code>. When we set <code>previous = n;</code>, isn't that making them reference the same object? If they reference the same object, one change you make to <code>n</code> will be the same in <code>previous</code>. So how does the line <code>previous.next = n.next;</code> work?</p>
  
  <p>Thanks!</p>