简体   繁体   中英

Setting Value Linked List Nodes Java

I was looking over how to remove duplicates from an unsorted Linked List and am getting confused about references in Java:

public static void deleteDups (LinkedListNode n){
  Hashtable table = new Hashtable();
  LinkedListNode previous = null;
  while(n!=null){
      if(table.containsKey(n.data)){
          previous.next = n.next;
      } else {
          table.put(n.data, true);
          previous = n;
      }
      n = n.next;
  }
}

When we do n = n.next , why doesn't the value of previous also get modified, since previous points to n ?

The variable n doesn't actually hold an instance of LinkedListNode .

The variable n holds a number. For example, it might hold the number 0x04AF34ED .

This number is an address . If the processor looks for that address in the computer's RAM, it will find the data associated with a LinkedListNode .

The variable previous also holds a number. At line 10 of your source code, it happens to hold the same number as the variable n , which means that they point to the same object. On line 11 of your source, the variable n is given a new number - the address of the object n.next . The number assigned to previous doesn't change. It still holds the address of the old LinkedListNode .

In Java, every time you create a new object, like List list = new ArrayList() you're actually creating a reference to that object:

  • You ask the operating system for space to store the object.
  • The operating system finds a place for the object and gives you a number - the address of the memory.
  • That number is assigned to the variable.
  • You can access the data stored at the address given to the variable by reading fields of the object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM