'return`

时间:2015-08-08 21:11:47

标签: java return binary-search-tree

伙计们,方法中单个return语句的目的是什么。它会阻止循环吗?如果没有,它到底是做什么的?请考虑以下示例:

class BinaryTree{

    Node root;

    public void addNode(int key, String name){
        Node newNode = new Node(key, name); 
        if(root == null){
            root = newNode;
        }
        else{
            Node current = root; 
            Node parent = root;
            while(current.key != key){
                parent = current;
                if(key > current.key){
                    current = current.rightChild;
                    if(current == null){
                        parent.rightChild = newNode;
                        return;
                    }
                }
                else{
                    current = current.leftChild;
                    if(current == null){
                        parent.leftChild = newNode;
                        return;
                    }
                }
            }
        }
    }
}

4 个答案:

答案 0 :(得分:5)

return语句终止该函数。停止执行实际上不返回任何值的void函数很有用。在这种情况下,一旦找到新节点的正确位置并添加它,就没有必要继续执行该功能,因此使用了return

答案 1 :(得分:1)

它不仅停止循环,还从函数返回void(nothing)。所以基本上它会停止功能。

答案 2 :(得分:1)

因为该函数返回void。返回只是结束函数并返回void。

答案 3 :(得分:0)

要正式发言,没有表达式的return将突然完成执行(JLS 14.17)。 return也会将控制权返还给其来电者。

有可能并且允许使用带有空void块的return返回的方法。这意味着如果满足某个条件,则停止该方法中的操作。

这与你在循环中用break代替return的情况没有什么不同,因为在这种情况下,他们完成同样的事情:他们都会终止循环并退出方法(由于没有更多的行来执行)。

在这样的场景中,如果使用break,意图会更清晰,因为return可能会混淆学生或初级开发人员。请注意,与break不同, 允许您在循环后运行代码,return不会。