Java编译器或运行时(或任何其他语言编译器)是否足够聪明,能够意识到分支3永远不可能发生,并将其优化掉?我看到过许多初学者使用这种“防御性编程”,想知道这种无用的代码是否会保留在字节码中。
import java.util.Random;
class Example
{
public static void main(String[] args) {
int x = new Random().nextInt() % 10;
if ( x < 5 )
{
System.out.println("Case 1");
}
else
if ( x >= 5 )
{
System.out.println("Case 2");
}
else
{
System.out.println("Case 3");
}
}
}
甚至是更直接的情况
boolean bool = new Random().nextBoolean();
if ( bool )
{
System.out.println("Case 1");
}
else
if ( bool )
{
System.out.println("Case 2");
}
nextInt(n)
而不是nextInt() % n
。它可以处理各种棘手的情况。http://docs.oracle.com/javase/7/docs/api/java/util/Random.html#nextInt(int) - Jerry101