可能重复: 什么是Java?:运算符被调用,它做了什么?
我试图阅读二叉树的实现,我遇到了这一行代码:
if (...) { ... } else { node = ( node.left != null ) ? node.left : node.right; //this line } return node;谁能告诉我这条线的含义是什么? 我最好的猜测是它是某种条件陈述。
Possible Duplicate: What is the Java ?: operator called and what does it do?
I am trying to read an implementation of a binary tree, and I ran across this one line of code:
if (...) { ... } else { node = ( node.left != null ) ? node.left : node.right; //this line } return node;Can anyone tell me what this line means? My best guess is that it's a conditional statement of some kind.
最满意答案
它被称为Conditional Operator 。
在expression1 ? expression2: expression3 expression1 ? expression2: expression3 , expression1返回一个boolean值。 如果为true则计算expression2 ,否则计算expression3 。
所以在你的代码片段中: -
node = ( node.left != null ) ? node.left : node.right;相当于: -
if (node.left != null) { node = node.left; } else { node = node.right; }It is called Conditional Operator.
In expression1 ? expression2: expression3, the expression1 returns a boolean value. If it is true then expression2 is evaluated, else expression3 is evaluated.
So in your code snippet: -
node = ( node.left != null ) ? node.left : node.right;is equivalent to: -
if (node.left != null) { node = node.left; } else { node = node.right; }更多推荐
发布评论