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

Cannot keep local variable value after recursive call in Java

我有以下递归方法:

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;
}

在此示例中,当我调用其中的方法并使用 approach I 时,parentUuids 被再次创建并且它失去了它的值。

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

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

我的问题是:

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

2.是不是有什么特殊用法,叫什么名字?我以前从未使用过这种方法,但我认为它可能对这种情况有用。有什么需要说明的吗?

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

  • 终止(在你没有任何要查找的 uuid 的情况下 parents)
  • Return parent 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
   // This is actually how it should look, addAll returns boolean (I just wrote it like the way I did to try and point out that you need to get the result Set first and use that then return that.
   Set<> set = recursiveMethod(parentUuids);
   set.addAll(productUuids);
   return set;
}

如果您使用链接集,那么您将能够按照大 parent > parent > 产品的顺序迭代它们。

如果你有:

A 
- B
  - C

那么你应该得到:

  • recursiveMethod([C]) => [C]
  • recursiveMethod([B]) => [C, B]
  • recursiveMethod([A]) => [C, B, A]

最终请求的样子:

rm(A)
rm(B) + A
rm(C) + B + A
[] + C + B + A