简体   繁体   English

通过引用与通过值传递

[英]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. 该解决方案使我感到非常困惑,因为在仅具有根参数(驱动程序函数)的createLeveLinkedList函数中,将创建一个新的链表列表。 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. 从Java的角度来看,如果按值传递它,则在调用createLevelLinkedLists(root,list,0)后,据我所知,列表应该没有改变。

If it was C++, I could understand it if they passed the pointer of the lists object into the function. 如果是C ++,如果他们将lists对象的指针传递给函数,则我可以理解。

Could someone please clarify this? 有人可以澄清一下吗?

Apologies for the formatting, I'm still not sure how it works on stackoverflow. 抱歉的格式,我仍然不确定它如何在stackoverflow上工作。

Thanks 谢谢

Java is always pass by value. Java总是按值传递。 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. 然而通过对复杂数据类型的值是基准,所以lists参考送入createLevelLinkedList(...)是指相同的对象的原始lists参考。

As long as you don't change the value of the reference in the createLevelLinkedList(...) method you will change the original object. 只要您不更改createLevelLinkedList(...)方法中引用的值,就可以更改原始对象。

As Paul mentioned, it's all written down here: 正如Paul所提到的,所有内容都记录在这里:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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