简体   繁体   English

设置值链接列表节点Java

[英]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: 我一直在研究如何从未排序的链接列表中删除重复项,并对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 ? 当我们执行n = n.next ,为什么previous的值也没有被修改,因为previous指向n

The variable n doesn't actually hold an instance of LinkedListNode . 变量n实际上没有保存LinkedListNode的实例。

The variable n holds a number. 变量n包含一个数字。 For example, it might hold the number 0x04AF34ED . 例如,它可能包含数字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 . 如果处理器在计算机的RAM中寻找该地址,它将找到与LinkedListNode关联的数据。

The variable previous also holds a number. 变量previous也包含一个数字。 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. 在源代码的第10行,它恰好拥有与变量n相同的数字,这意味着它们指向同一对象。 On line 11 of your source, the variable n is given a new number - the address of the object n.next . 在源代码的第11行,为变量n提供了一个新数字-对象n.next的地址。 The number assigned to previous doesn't change. 分配给previous的数字不变。 It still holds the address of the old LinkedListNode . 它仍然保留旧LinkedListNode的地址。

In Java, every time you create a new object, like List list = new ArrayList() you're actually creating a reference to that object: 在Java中,每次创建新对象(例如List list = new ArrayList() ,实际上是在创建对该对象的引用:

  • 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. 您可以通过读取对象的字段来访问存储在变量指定地址处的数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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