[英]Why does the class fields update their data after the method works
Help me please.请帮帮我。 Let's say I have a Link class for linked lists.假设我有一个用于链接列表的 Link 类。 And there is the SortedList class where there are methods for working with data created by the first class.还有 SortedList 类,其中有处理由第一个类创建的数据的方法。
public class Link {
public long db;
public Link next;
public Link(long data){
db=data;
}
public void displayLink(){
System.out.println(db+" ");
}
}
public class SortedList {
private Link first;
public SortedList(){
first=null;
}
public void insert(long key){
Link newLink=new Link(key);
Link previous=null;
Link current=first;
while (current!=null&&key>=current.db){
previous=current;
current=current.next;
}
if (previous==null){
first=newLink;
}else {
previous.next=newLink;
newLink.next=current;
}
}
public void displayList(){
System.out.println("List (first-->last): ");
Link current=first;
while (current!=null){
current.displayLink();
current=current.next;
}
System.out.println();
}
}
The insert method uses the first field.插入方法使用第一个字段。 The first field passes its data to the current field.第一个字段将其数据传递到当前字段。 After the method exits with the current field, no changes are made to the first field, but the changes still appear in the first field.方法与当前字段一起退出后,不会对第一个字段进行任何更改,但更改仍会出现在第一个字段中。
How it happens, I pray you help怎么回事,求你帮忙
At the beginning of insert
, we set current
to be a reference to the value of first
.在insert
开始时,我们将current
设置为对first
值的引用。 This means that, at this point, both current
and first
are references to the same field.这意味着,在这一点上, current
和first
都是对同一字段的引用。
The while
loop then iterates over the nodes starting from first
until we either hit the end of the list or a node whose key is less than key
.然后while
循环从first
开始迭代节点,直到我们到达列表的末尾或键小于key
的节点。 The iteration happens by updating current
to follow the next
reference of the current node.迭代通过更新current
以跟随当前节点的next
引用而发生。
Now happens the part that confused you: if first
was null
(ie the first time we call insert
, the next operation updates first
by assigning it a new value. first
will now refer to the value of newLink
, which is precisely the node that we created at the top of insert
.现在发生了让您感到困惑的部分:如果first
为null
(即我们第一次调用insert
,则下一个操作first
通过为其分配一个新值来更新。 first
现在将引用newLink
的值,这正是我们要使用的节点在insert
的顶部创建。
It helps to take pen and paper, draw a table with columns for all variables, and go through the algorithm step by step , like a computer would.它有助于拿起笔和纸,为所有变量绘制一个带有列的表格,并像计算机一样一步一步地执行算法。 You can do something similar by using the debugger, set a break point at the beginning of the method, and “step through” your code.您可以使用调试器做类似的事情,在方法的开头设置一个断点,然后“单步执行”您的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.