簡體   English   中英

為什么類字段在方法起作用后更新它們的數據

[英]Why does the class fields update their data after the method works

請幫幫我。 假設我有一個用於鏈接列表的 Link 類。 還有 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();
}
  }

插入方法使用第一個字段。 第一個字段將其數據傳遞到當前字段。 方法與當前字段一起退出后,不會對第一個字段進行任何更改,但更改仍會出現在第一個字段中。

怎么回事,求你幫忙

insert開始時,我們將current設置為對first值的引用。 這意味着,在這一點上, currentfirst都是對同一字段的引用。

然后while循環從first開始迭代節點,直到我們到達列表的末尾或鍵小於key的節點。 迭代通過更新current以跟隨當前節點的next引用而發生。

現在發生了讓您感到困惑的部分:如果firstnull (即我們第一次調用insert ,則下一個操作first通過為其分配一個新值來更新。 first現在將引用newLink的值,這正是我們要使用的節點在insert的頂部創建。

它有助於拿起筆和紙,為所有變量繪制一個帶有列的表格,像計算機一樣一步一步地執行算法 您可以使用調試器做類似的事情,在方法的開頭設置一個斷點,然后“單步執行”您的代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM