java 函数返回 False 或对象

标签 java python recursion types

我正在开发一个将在回溯场景中递归调用的函数。该函数要么工作正常并返回工作列表,要么失败并返回 false。在Python中,我可以这样写:

def myfunc(input):
    # logic and logic
    if fails:
        return False
    return alist

在 java 中,函数不能返回 List 或 False。我想我可以绕过这个问题 (? 只是为了争论,我知道我要返回什么):

public List<?> myfunc(someType input){
    // logic and logic
    return res
    // empty or special result instead of False.
}

但是有没有更优雅的方法来做到这一点?也许 try catch ?我对java很陌生,想知道这种情况下的标准。谢谢。

最佳答案

有几个选项:

使用java.util.Optional

public Optional<List> myfunc(someType input){
    // logic and logic
    if (fail) return Optional.empty();
    else return Optional.of(res);
}

返回null

public List myfunc(someType input){
    // logic and logic
    if (fail) return null;
    else return res;
}

抛出异常

public List myfunc(someType input){
    // logic and logic
    if (fail) throw new RuntimeException("What an interesting case!");
    else return res;
}
PS。我会推荐可选或异常(exception)。

关于java 函数返回 False 或对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56711620/

相关文章:

java - “启动配置”的位置>> tomcat中的环境变量

python - 如何将 URL 中的图像加载到 Tensorflow 中?

swift - 您如何利用 Swift 特性来重构这个递归函数?

bash - 递归 ls 和 grep 会比在大型文件系统上查找更快吗?

java - 数组复杂度中的 K 个最大元素

java - 为什么当我按下 enter 时我的程序不会停止

python - str封装数组到pandas数组

c++ - 递归查找优化

java - 如何递归求解 'classic' 背包算法?

Python 文件写入后仍为空问题