Before I show my problem what I understand is: Java uses pass by value.
Said that, In below example, I pass "my_root" reference , to NodeModify(),
and in line "NodeModify(my_root);" expect compiler to pass copy of memory address of "my_root " and inside function make "root = new_node;" i.e => expect root's memory location/address be updated to / point to location where "new_node" is.
Surprisingly, it doesn't reflect back in main() function from where it was called, why is this so?
package com.trees;
public class NodeExample {
public static void NodeModify(Node root){
System.out.println("[NodeModify] fresh root is : " + root);
Node new_node = new Node(0);
System.out.println("[NodeModify] new node is : " + new_node);
root = new_node;
System.out.println("[NodeModify] root is : " + root);
}
public static void main(String[]arg){
Node my_root = new Node(55);
System.out.println("my root before NodeModify is: " + my_root);
NodeModify(my_root);
System.out.println("my root after NodeModify is: " + my_root);
}
}
However, if I do the same with other reference, like ArrayList, it gets updated in main() as I expect! Example:
package com.trees;
import java.util.ArrayList;
public class ArrayListUpdateClass {
public static void updateMyArrayList(ArrayList<String> sample){
sample.add("was updated!");
}
public static void main(String[]args){
ArrayList<String> my_list = new ArrayList<String>();
my_list.add("My list ");
System.out.println("**Before call list is:**");
printArrayList(my_list);
updateMyArrayList(my_list);
System.out.println("\n**After call list is:**");
printArrayList(my_list);
}
private static void printArrayList(ArrayList<String> my_list) {
for(String item:my_list){
System.out.println(item);
}
}
}
What am I missing here, I had hard time updating root node in making Binary tree.