Java的&放大器;&安培; ||在return语句? [英] Java && || in RETURN statements?

查看:139
本文介绍了Java的&放大器;&安培; ||在return语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在看一些Java算法例子,我碰到过这个片段code中的递归方法:

I'm looking at some Java algorithm examples and I come across this snippet code within a recursive method:

boolean subTree(TreeNode t1, TreeNode t2) {
    if (t1 == null) {
        return false;
    }
    if (t1.value == t2.value) {
        if (treeMatch(t1, t2))
            return true;;
    }
    return (subTree(t1.left, t2) || subTree(t1.right, t2));
}

不知道(和从来没有看到)||前一个return语句中使用,更何况是一个递归的,真的让我感到困惑。我复制了code到Eclipse中,看它是否是有效的,它是。然后我更换了||与&功放;&安培;和Eclipse似乎没有被它困扰。从逻辑上讲,我明白,这递归code应该继续沿着树节点T1的左,右子树,但我在寻找背后更多的理论解释,这是如何的Java语法的作品。

Not knowing (and never seeing) || being used within a return statement before, let alone a recursive one, really made me confused. I copied the code into Eclipse to see if it was valid and it was. I then replaced the || with && and Eclipse didn't seem bothered by it. Logically, I understand that this recursive code is supposed to continue down the left and right subtrees of TreeNode t1, but I'm looking for a more theoretical explanation behind how this Java syntax works.

有人可以解释背后的含义||并与功放;&安培;在Java的return语句?这是什么递归而言意味着什么?它是在结合使用递归的时候才有意义?

Can someone explain the meaning behind || and && within Java's return statement? What does it mean in terms of recursion? Is it only meaningful when used in conjunction with recursion?

推荐答案

作为方法签名中定义,你将不得不返回布尔。因此,返回关键字之后,你必须提供一个布尔 或一个前pression 这是评估以布尔

As defined in the method signature, you will have to return a boolean. Therefore, after the return keyword, you will have to provide a boolean or an expression which is evaluated to boolean.

在你的情况,你有expession (子树(t1.left,T2)||子树(t1.right,T2)); ,其中两个操作数将进行评估,以<​​code>布尔键,您将应用的逻辑他们只有在第一个计算结果为。如果第一个操作数的计算结果为第二个将不进行评估,将retured。

In your case you have the expession (subTree(t1.left, t2) || subTree(t1.right, t2)); in which the two operands will be evaluated to boolean and you will apply an logical OR on them only if the first evaluates to false. If the first operand evaluates to true the second will not be evaluated and true will be retured.

这篇关于Java的&放大器;&安培; ||在return语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆