如何确保方法返回值



我在下面编写的方法应该在二进制电极上作用,以使树上"下面"的树扁平。据我的理解,我的if-else if-else以及递归(?)结构总是会返回一个值,但是我在Eclipse中遇到了一个错误,说"此方法必须返回类型<Integer>的结果。

进行研究后,我相信Java不能完全说出该方法始终返回正确的值,因为返回语句在"其他"中。这是问题吗?我如何设计避免此问题的方法?

//doFlatten acts on a BinaryTreeNode and takes a storage list as an argument
//it will call itself on any children on the node
//if the node is a leaf, it will update the storage list and return that updated list
public List<Integer> doFlatten(List<Integer> result){
    if (this.leftChild != null){
        this.leftChild.doFlatten(result);
    }
    else if (this.rightChild != null){
        this.rightChild.doFlatten(result);
    }
    else{
        result.add(this.value); //add leaf to result list
        return result;
    }
}

制作返回类型void并删除return result。无需返回结果对象,因为它是传递的结果对象(呼叫者已经对其进行了引用)。

最好的选择是用该方法的返回类型定义一个变量,并将其初始化为默认值,在方法中分配结果的正确值,最后,最后,作为方法的最后一行,返回此变量。

对于您的方法,可能看起来像这样:

public List<Integer> doFlatten(List<Integer> result) {
    List<Integer> realResult = new ArrayList<>(result);
    if (this.leftChild != null){
        this.leftChild.doFlatten(result);
    }
    else if (this.rightChild != null){
        this.rightChild.doFlatten(result);
    }
    else{
        result.add(this.value); //add leaf to result list
        realResult.add(this.value);
        //avoid return statement here
        //return result;
    }
    //single point for return statement
    return realResult;
}

但是,在这种情况下,正如您在上面的代码中看到的那样,返回结果似乎毫无意义,因为此方法的正确结果存储在List<Integer> result中。因此,只需使您的方法void

public void doFlatten(List<Integer> result) {
    //rest of your code...
}

您的方法实际上并不总是返回一个值(第一个if和否则第一个)没有返回。

这似乎是您想要的:

    public List<Integer> doFlatten(List<Integer> result){
        if (this.leftChild != null){
            this.leftChild.doFlatten(result);
        }
        else if (this.rightChild != null){
            this.rightChild.doFlatten(result);
        }
        else{
            result.add(this.value); //add leaf to result list
        }
        return result;
    }

再次检查您的代码。您在最后一个else分支中只有一个返回语句。这意味着您的方法仅在到达这一点时才返回值。这正是编译器报告的内容。

因此,可以像"编译您的代码"一样回答"如何确保我的方法返回值"的问题。如果您设法编译代码,请确保您的方法确实返回值或投掷异常。

但是,如果您实际上是在询问最佳的编码实践,以帮助您避免这种汇编错误恕我直言,则没有100%正确的答案。

请参阅Luigi Mendoza的建议。在某些情况下,它们很好。但是(对不起,路易吉)我不同意他们总是很好。我会说您应该在可能的情况下避免/其他结构。例如,在if块末尾具有返回的if语句在某些情况下更可读。

我想你只想要:

//doFlatten acts on a BinaryTreeNode and takes a storage list as an argument
//it will call itself on any children on the node
//if the node is a leaf, it will update the storage list and return that updated list
public List<Integer> doFlatten(List<Integer> result){
    if (this.leftChild != null){
        return this.leftChild.doFlatten(result);
    }
    else if (this.rightChild != null){
        return this.rightChild.doFlatten(result);
    }
    else{
        result.add(this.value); //add leaf to result list
        return result;
    }
}

请注意,在我的版本中,所有谓词结果都会导致List<Integer>返回,在您的情况下,只有else子句才能。

最新更新