Skip to content
Advertisement

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. And there is the SortedList class where there are methods for working with data created by the first class.

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

Advertisement

Answer

At the beginning of insert, we set current to be a reference to the value of first. This means that, at this point, both current and first are references to the same field.

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. The iteration happens by updating current to follow the next reference of the current node.

Now happens the part that confused you: if first was null (i.e. 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.

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.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement