当前位置: 首页 > 知识库问答 >
问题:

在Java中递归调用后无法保留局部变量值[关闭]

锺离嘉容
2023-03-14

想改进这个问题吗 通过编辑这篇文章,更新问题,以便用事实和引文来回答。

我有以下递归方法:

public Set<UUID> recursiveMethod(Set<UUID> productUuids) {

    // approach I
    final Set<UUID> parentUuids = productRepository
            .findAllParentUuidByProductUuidIn(productUuids);

    // approach II
    final Set<UUID> parentUuids = new HashSet<>(
            productRepository.findAllParentUuidByProductUuidIn(productUuids)
    );


    if (!parentUuids.isEmpty()) {
        final Set<UUID> relatedProducts = recursiveMethod(parentUuids);
        parentUuids.addAll(relatedProducts);
    }

    return parentUuids;
}

在本例中,当我调用其中的方法时,以及使用方法I时,会再次创建parentUuids,并且会丢失其值。

另一方面,当使用如下所示的方法II时,我保留了值:

// approach II
final Set<UUID> parentUuids = new HashSet<>(
    productRepository.findAllParentUuidByProductUuidIn(productUuids)
);

我的问题是:

1.方法II是保留局部变量值的正确方法吗?

2.这是一种特殊的用法吗?它叫什么名字?我以前从未使用过这种方法,但我认为它可能对这种情况有用。请澄清一下?

共有1个答案

贝杜吟
2023-03-14

如果要为此使用递归,则需要确保满足以下两个条件:

  • 终止(在您的情况下,当您没有任何uuid可以查找父母时)
  • 返回父uuid并将它们与当前uuid合并
public Set<UUID> recursiveMethod(Set<UUID> productUuids) {
   // If we the set is empty or null, we just return back the empty Set which
   // will be used as the initial set.
   if (CollectionUtils.isEmpty(productUuids)
      return new HashSet<>();   

   // Lookup the parentUuids, this may be empty, but we've accounted for that
   // in the previous section.
   Set<UUID> parentUuids = dao.getParentUuids(productUuids);

   // Call the method with the parent uuids, this will return a Set
   // To the returned set, we add the requested uuids (they have to exist).
   // recursiveMethod(parentUuids) will contain the grand parent uuids (if any)
   // to which we add in the lookup uuids
   return recursiveMethod(parentUuids).addAll(productUuids);
}

如果使用链接集,则可以按父级顺序对其进行迭代

如果您有:

A 
- B
  - C

然后你应该得到:

  • 递归方法([C])=

最终请求如下所示:

rm(A)
rm(B) + A
rm(C) + B + A
[] + C + B + A
 类似资料:
  • 我正在编写一个函数来展平嵌套数组(Python)。例如将[1,2,[3]]变成[1,2,3],[[1,2,[3]],4]变成[1,2,3,4]等。 我有以下内容: 所以这个想法是让函数是递归的,以处理嵌套到未知深度的情况。我的问题是每次遇到嵌套列表都会被重新初始化(当被递归调用时)。 在进行递归调用时,如何保持展平数组的状态?

  • 我使用递归方法在二叉树中使用键查找节点。找到节点后,我将其设置为引用变量foundNode并返回。问题是,当我读取对象时,它的值仍然是null。有人能帮忙吗?

  • 我有一个像下面这样的递归方法 我发现本地变量无法释放,如果我将最大堆大小设置为50M(-xmx50M),它将在第44次调用时满足OOM 但将其更改为for循环则不存在此问题 那么为什么在递归中叫它不释放局部变量的内存呢?

  • 函数甚至可以不使用局部变量来调用自己. 例子 23-14. 汉诺塔 1 #! /bin/bash 2 # 3 # 汉诺塔(The Towers Of Hanoi) 4 # Bash script 5 # Copyright (C) 2000 Amit Singh. All Rights Reserved. 6 # http://hanoi.kernelthrea

  • 问题内容: 是否可以通过java的辅助函数保留信息,而无需使用静态变量。 例如, 也就是说,我想更新变量v而不丢失每个递归情况的信息,而不必访问函数外部的变量。 问题答案: 忘记所有告诉您声明属性或在每次递归调用中更新可变对象的答案。在真正的功能性递归样式中,您可以通过将信息作为参数和/或返回类型传递来“保留”信息。 让我用一个简单的示例进行说明,假设您要递归地计算中的元素之和。在这里, 状态 (

  • 即使不适用局部变量,函数也可以递归的调用自身。 例子24-16. 斐波那契序列 #!/bin/bash # fibo.sh : 斐波那契序列 (递归) # 作者: M. Cooper # License: GPL3 # ----------算法-------------- # Fibo(0) = 0 # Fibo(1) = 1 # else # Fibo(j) = Fibo(j-1) + Fi