获取 Java 布尔值的倒数的最简洁方法是什么?
如果你有一个布尔变量:
boolean myBool = true;
我可以用 if/else 子句得到相反的结果:
if (myBool == true)
myBool = false;
else
myBool = true;
是否有更简洁的方法来做到这一点?
If you have a boolean variable:
boolean myBool = true;
I could get the inverse of this with an if/else clause:
if (myBool == true)
myBool = false;
else
myBool = true;
Is there a more concise way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
只需使用逻辑 NOT 运算符
!
进行赋值,就像您在条件语句中所做的那样(if
、for
、while
...)。您已经在使用布尔值,因此它将把true
翻转为false
(反之亦然):Just assign using the logical NOT operator
!
like you tend to do in your condition statements (if
,for
,while
...). You're working with a boolean value already, so it'll fliptrue
tofalse
(and vice versa):一种更酷的方法(如果您想设置变量,那么对于长度超过 4 个字符的变量名,这比
myBool = !myBool
更简洁):顺便说一句,don不要使用
if (something == true)
,如果你只使用if (something)
会更简单(与与 false 比较相同,使用否定运算符)。An even cooler way (that is more concise than
myBool = !myBool
for variable names longer than 4 characters if you want to set the variable):And by the way, don't use
if (something == true)
, it's simpler if you just doif (something)
(the same with comparing with false, use the negation operator).对于
boolean
来说,这非常简单,对于Boolean
来说,则有点具有挑战性。boolean
只有 2 种可能的状态:真
和假
。Boolean
有 3 个:Boolean.TRUE
,Boolean.FALSE
或null
。假设您只是处理一个
boolean
(这是一个原始类型),那么最简单的事情是:但是,如果您想反转一个
Boolean
(这是一个对象),您必须注意null
值,否则最终可能会出现NullPointerException
。假设该值永远不为空,并且您的公司或组织没有针对自动(取消)装箱的代码规则。实际上,您可以将其写在一行中。
但是,如果您确实也想处理
null
值。那么就有好几种解读了。另一方面,如果您希望
null
在反转后保持null
,那么您可能需要考虑使用apache commons
类BooleanUtils
(参见 javadoc)有些人更喜欢将其全部写出来,以避免对 apache 的依赖。
For a
boolean
it's pretty easy, aBoolean
is a little bit more challenging.boolean
only has 2 possible states:true
andfalse
.Boolean
on the other hand, has 3:Boolean.TRUE
,Boolean.FALSE
ornull
.Assuming that you are just dealing with a
boolean
(which is a primitive type) then the easiest thing to do is:However, if you want to invert a
Boolean
(which is an object), you have to watch out for thenull
value, or you may end up with aNullPointerException
.Assuming that this value is never null, and that your company or organization has no code-rules against auto-(un)boxing. You can actually just write it in one line.
However if you do want to take care of the
null
values as well. Then there are several interpretations.On the other hand, if you want
null
to staynull
after inversion, then you may want to consider using theapache commons
classBooleanUtils
(see javadoc)Some prefer to just write it all out, to avoid having the apache dependency.
最简洁的方法是不反转布尔值,当您想检查相反的条件时,只需在代码中使用 !myBool 即可。
The most concise way is to not invert the boolean, and just use !myBool later on in the code when you want to check the opposite condition.