是否可以在 Java 中使用三元运算符来应用增量?
例如,我想在没有“if”语句的情况下进行此操作,而不是因为它更具可读性或更短,只是我想知道。
if(recordExists(recordId)){
numberofRecords++;
}
是否可以在 Java 中使用三元运算符来应用增量?
例如,我想在没有“if”语句的情况下进行此操作,而不是因为它更具可读性或更短,只是我想知道。
if(recordExists(recordId)){
numberofRecords++;
}
是否可以在 Java 中使用三元运算符来应用增量?
您可以改用加法。
numberOfRecords += recordExists(recordId) ? 1 : 0;
恕我直言,这没有副作用。
是否可以在 Java 中使用三元运算符来应用增量?
那么你可以写:
// Ick, ick, ick.
int ignored = recordExists() ? numberOfRecords++ : 0;
或者进行无操作方法调用:
// Ick, ick, ick.
Math.abs(recordExists() ? numberOfRecords++ : 0);
不过,我强烈建议您不要这样做。这是对条件运算符的滥用。只需使用一个if
语句。
条件运算符的目的是创建一个其值取决于条件的表达式。
语句的目的if
是根据条件执行某些语句。
表达式的目的是计算一个值,而不是产生副作用。声明的目的是产生副作用。
编辑:鉴于对这个答案的有效性产生了怀疑:
public class Test {
public static void main(String[] args) {
boolean condition = true;
int count = 0;
int ignored = condition ? count++ : 0;
System.out.println("After first check: " + count);
Math.abs(condition ? count++ : 0);
System.out.println("After second check: " + count);
}
}
输出:
After first check: 1
After second check: 2
请记住,如果您尝试在其中使用增量,三元运算符可能会做一些奇怪的事情。我相信这个术语是“短路”,结果非常违反直觉。
最好避免!
例如,请注意以下事项:
public class Strange {
public static void main(String[] args) {
int x = 1;
x = x > 0 ? x++ : x--;
System.out.println("x= " + x); // x is 1, both the increment and decrement never happen.
int y = 5;
y = y < 0 ? y++ : y--;
System.out.println("y= " + y); // y is 5, both the increment and the decrement never happens.
// Yet, in this case:
int a = 1;
int b = 2;
a = a > 0 ? b++ : a--;
System.out.println("a= " + a + " b= " +b); // a = 2, b = 3;
// in this case a takes on the value of b, and then b IS incremented, but a is never decremented.
int c = 5;
int d = 1;
int e = 0;
c = c < 10 ? d++ : e--;
System.out.println("c= " + c + " d= " + d + " e= " + e); // c = 1, but d = 2, and e = 0.
// c is assigned to d, then d in INCREMENTED, then the expression stops before evaluating the decrement of e!
c = c > 10 ? d++ : e--;
System.out.println("c= " + c + " d= " + d + " e= " + e);
// c = 0, d = 1, e = -1
}
}