简体   繁体   中英

Passing by reference vs Passing by value

I'm currently studying Cracking the Coding interview, and I believe my basic understanding of pointers are being called into question. I am currently looking at a solution to make a linked list for every level of a binary tree. The solution is as follows:

void createLevelLinkedList(TreeNode root, ArrayList<LinkedList<TreeNode» lists, int level) {
    if (root == null) return; // base case
    LinkedList<TreeNode> list = null;
    if (lists.size() == level) { // Level not contained in list
        list = new LinkedList<TreeNode>();
        /* Levels are always traversed in order. So., if this is the
         * first time we've visited level i, we must have seen levels
         * 0 through i - 1. We can therefore safely add the level at
         * the end. */
        lists.add(list);
    } else {
        list = lists.get(level);
    }
    list.add(root);
    createLevelLinkedList(root.left, lists, level + 1);
    createLevelLinkedList(root.right, lists, level + 1);
}

ArrayList<LinkedList<TreeNode» createLevelLinkedList(TreeNode root) {
    ArrayList<LinkedList<TreeNode» lists = new ArrayList<LinkedList<TreeNode»();
    createLevelLinkedList(root, lists, 0);
    return lists;
}

This solution greatly confuses me, because in the createLeveLinkedList function with only the root parameter (the driver function), a new list of linked lists is created. From a java perspective, if it is passed by value, after createLevelLinkedLists(root, lists, 0) is called, to my understanding, lists should not have changed.

If it was C++, I could understand it if they passed the pointer of the lists object into the function.

Could someone please clarify this?

Apologies for the formatting, I'm still not sure how it works on stackoverflow.

Thanks

Java is always pass by value. However the value passed for complex datatypes is that of the reference, so the lists reference passed into createLevelLinkedList(...) refers to the same object as the original lists reference.

As long as you don't change the value of the reference in the createLevelLinkedList(...) method you will change the original object.

As Paul mentioned, it's all written down here:

https://stackoverflow.com/a/40523/1619628

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM