0

implementing a singly-linked-list containing one integer and the reference to the next element. I wrote 2 methods which display the entire list.

VERSION A does contain the local variable current.

VERSION B does not contain a "current" variable. Both versions work fine, I however dont understand why VERSION B without a local variable works too.

public class LList{
 // VERSION A
public static void printListA(Node Head){
    Node current = Head;

     while(current != null){
        System.out.println(current._value);
        current = current._next;
    }    
}   

// VERSION B
public static void printListB(Node Head){

     while(Head != null){
        System.out.println(Head._value);
        Head = Head._next;
    }

}

Question to Version B: Since a Node-instance qualifies as a mutable object, it is passed by reference to the "printListB-function". I would therefore expect the Head-node to be changed by "printListB", since "Head" is over-written at each iteration ("Head" should become the Tail-node). This is however not the case, and it seems that "Head" is treated like a variable local to the function.

Could somebody explain, why printListB does not change the Parameter "Head" despite it being passed by reference.

Thanks a lot in advance.

Andrej
  • 1
  • 2
  • While the variable `Head` passed in points to the head of the list, it is not _the_ head of the list. Changing `Head` to point to a different value does not change the actual head of the list – phflack Feb 14 '18 at 14:25
  • Literally the top question in the 'related' section: https://stackoverflow.com/q/40480 – bcsb1001 Feb 14 '18 at 14:26
  • Similar to [Is it a good practice to change arguments in Java](https://stackoverflow.com/q/12019978/5475891) – phflack Feb 14 '18 at 14:27

0 Answers0