切换布尔值,但只切换一次? (java)
有时需要在循环中只存储一次布尔值(以记录它从 false 变为 true,反之亦然),同时将循环执行到最后,但不再关心布尔值的变化价值。示例:
public static boolean dbDelete(Collection argObjectCollectionToDelete) {
boolean result = true;
for (Object object : argObjectCollectionToDelete) {
boolean dbDelete = dbDelete(object);
if (!dbDelete) {
result = false;
}
}
return result;
}
是否有某种方法可以执行等效的代码
if (!dbDelete) {
result = false;
}
或
if (!dbDelete && !result) {
result = false;
}
以更优雅的方式(最好是在一行中)?
Every now and then there is a need to store a boolean value only once (to record that it has changed from false to true or vice versa) in a loop, while executing the loop to the end but not caring anymore about changes in the boolean value. Example:
public static boolean dbDelete(Collection argObjectCollectionToDelete) {
boolean result = true;
for (Object object : argObjectCollectionToDelete) {
boolean dbDelete = dbDelete(object);
if (!dbDelete) {
result = false;
}
}
return result;
}
Is there some way to execute the equivalent of the code
if (!dbDelete) {
result = false;
}
or
if (!dbDelete && !result) {
result = false;
}
in a more elegant way, preferrably in one line?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
怎么样:
这相当于:
所以只有当
result
之前为 true 并且dbDelete
返回 true 时,它才为 true。How about:
This is equivalent to:
So it will only be true if
result
was previously true anddbDelete
returned true.结果 = dbDelete(对象) ?结果:假;
result = dbDelete(object) ? result : false;
尝试为变量名称赋予更多含义 - 这会让事情变得更容易。
Try putting more meaning into your variable names - it makes things easier.