递归时的变量值保留

AFH*_*AFH 2 java recursion

我有以下伪代码,如果tree是binaryTree的实例,我需要更新计数器值.如果树有更多的孩子,我会递归调用该方法并递增计数器.

问题是如果我使计数器静态(我不想这样),计数器值很好但是当我将变量作为输入传递给方法时(如下所述)我只得到值1.什么是错的这里?

//Pseudo code
public static int test(tree) {
    Integer count = 0;
    return testTreeRecCounts(tree, count);
}

private static Integer testTreeRecursiveCounts(tree, Integer count) {
    if (tree instanceof  binaryTree) {
        count++;
        for (Node node :tree.getChild())) {
            testTreeRecursiveCounts((tree)node, count);
        }
    }
    return count;
}
Run Code Online (Sandbox Code Playgroud)

Pha*_*ung 5

该问题Integer不可变的,所以你做的那一刻count++时,count会指向不同的对象.

过程是:count - > unboxing - >将值增加1 - >自动装箱(创建一个新对象).

这就是原因,只有值为1的第一个对象才会返回.

另请注意,使用Integer而不是原语int会降低性能,因为它需要连续进行自动装箱/拆箱.

这样的问题可以解决这个问题:

private static int testTreeRecursiveCounts(tree) {
    int count =0;
    if (tree instanceof  binaryTree) {
        count++;
        for (Node node :tree.getChild())) {
           count += testTreeRecursiveCounts((tree)node);
        }
    }
    return count;
}
Run Code Online (Sandbox Code Playgroud)