以下代码没有错误。但是,只要 if (i == a.length - 1 || a[i] != a[i + 1])
就可以了条件维持其秩序。将 if 条件交换为 if(a[i] != a[i + 1] || i == a.length - 1)
会抛出异常。通过短路来防止异常是一种可预期的编码标准还是有一些理论/设计模式警告这种编码实践?如果是这样,请提供链接/ Material 。
public static void eliminateDuplicate(int[] a) {
if (a == null) {
throw new NullPointerException();
}
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < a.length; i++) {
if (i == a.length - 1 || a[i] != a[i + 1]) {
System.out.println("now what : " + a[i]);
list.add(i);
}
}
}
最佳答案
使用短路运算符来避免异常是一种常见的做法。这显然是标准的。
JLS Section 15.24 - Conditional OR operator:
The conditional-or operator || operator is like | (§15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand is false.
- ConditionalOrExpression:
- ConditionalAndExpression
- ConditionalOrExpression || ConditionalAndExpression
根据您的情况,如果您使用 Conditional && operator 会更清楚并将您的条件更改为:
if (i < a.length - 1 && a[i] != a[i + 1])
乍一看,这段代码的意图更加清晰。坦白说,我必须对你的情况进行两次检查才能弄清楚它在做什么。
再次与具体问题无关,我将修改您的 for 循环以使用比您当前使用的最大索引少一的最大索引,以完全避免条件运算符:
for (int i = 0; i < a.length - 1; i++) {
if (a[i] != a[i + 1]) {
System.out.println("now what : " + a[i]);
list.add(i);
}
}
<小时/>
一些常见示例:
一些非常常见的示例,您会看到使用条件运算符来避免异常:
重写equals()
方法:
public boolean equals(Object obj) {
return obj instanceof MyClass && ((MyClass)obj).num == this.num;
}
在某些方法调用中处理null
引用:
// Although there are better way to do this.
if (str != null && str.equals(str2)) {
// some code
}
避免被零除:
if (x != 0 && 4/x > 1) {
// some code
}
与此相反,如果您使用Boolean Logical Operator,以上所有代码都会在运行时抛出异常。 ,第一个表达式的计算结果为 false
。
关于java - 通过短路避免异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18552420/