[英]How does the ternary operator work
I don't understand this code; 我不明白这段代码;
Can someone write it proper so I can also understand. 有人可以写得正确,所以我也可以理解。
public void deleteStudentsPersistence(Student student) {
em.remove(em.contains(student) ? student : em.merge(student));
}
The operator you used there is called a ternary operator and it works almost the same way an if-else statement works. 您在那里使用的运算符称为三元运算符,它的工作方式与if-else语句的工作方式几乎相同。 Consider the statement below:
请考虑以下声明:
int min = (a < b) ? a : b;
What this means is: Evaluate the value of (a < b)
, if it's true, the value of min is a
, otherwise, the value of min is b
. 这意味着: 评估
(a < b)
的值,如果为真,则min的值为a
,否则min的值为b
。 It can be related to the if-else statement this way: If (a < b) is true: min = a; 它可以通过这种方式与if-else语句相关: 如果(a <b)为真:min = a; else: min is b.
否则:min是b。
Back to your question now.... 现在回到你的问题....
em.remove(em.contains(student) ? student : em.merge(student));
This means if em.contains(student)
is true, then perform em.remove(student)
, however if it's false, then perform em.remove(em.merge(student))
. 这意味着如果
em.contains(student)
为true,则执行em.remove(student)
,但如果它为false,则执行em.remove(em.merge(student))
。
PS: PS:
Obviously, in many practical cases that involve giving a variable a value based on a two-way condition, this can be a subtle replacement for if-statement. 显然,在许多实际情况中,涉及根据双向条件给变量赋值,这可能是if语句的微妙替代。 There is great argument about the "more efficient" method as seen in this post but I personally prefer to use the ternary operator because of it's relatively short syntax length and readability.
有关于“更有效”的方法看到巨大争论这个职位 ,但我个人更喜欢使用三元运算符,因为它是相对较短的语法长度和可读性。
I hope this helps.. Merry coding! 我希望这有帮助..快乐编码!
this is a ternary operator, called conditional operator. 这是一个三元运算符,称为条件运算符。 it could also be written this way:
它也可以这样写:
public void deleteStudentsPersistence(Student student) {
if (em.contains(student)){
em.remove(student);
} else{
em.remove(em.merge(student));
}
}
basically, it check if em contains the student before removing, otherwise it merge it 基本上,它会在删除之前检查em是否包含学生,否则将其合并
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.