Stackoverflow上有碼友被人問到,如下程序結構,不改變if-else語句,如何輸出Not OK。
class Condition {
// you can change in the main
public static void main(String[] args) {
int x = 0;
if (x == x) {
System.out.println("Ok");
} else {
System.out.println("Not ok");
}
}
}
各位碼友紛紛支招,比較有意思的有三種。
方式一:利用Float.NaN 或Double.NaN的數值不可比較性。
public class IfStateNaN {
public static void main(String[] args) {
float x = Float.NaN;
if (x == x) {
System.out.println("Ok");
} else {
System.out.println("Not ok");
}
}
}
方式二:利用多線程讀取一個值和判斷這個值的非原子性(從堆空間上取到線程棧空間後,才能執行棧指令進行比較,兩次取數之前可被其他線程修改掉)。
該方式在Windows開發機器上,只在程序運行開始階段偶爾會出現,後面運行就不出現了,估計被JVM優化了,直接從方法區空間取值,省略了取到棧空間的步驟。
public class IfStateThread {
static int x = 0;
public static void main(String[] args) {
Thread thread = new Thread(){
public void run(){
while(true) x++;
}};
thread.start();
while(true){
if (x == x) {
//System.out.println("Ok");
} else {
System.out.println("Not ok");
}
}
}
}
也有重載System.out.println方法,直接修改輸出的。
public class IfStateStream extends PrintStream{
public IfStateStream(PrintStream x) {super(x);}
public void println(String x) {super.println("Not ok");}
public static void main(String[] args) {
System.setOut(new IfStateStream(System.out));
int x = 0;
if (x == x) {
System.out.println("Ok");
} else {
System.out.println("Not ok");
}
}
}
如果是C++,還可以將 x封裝成對象,將 == 運算符重載,將原來相等的運算結果返回不相等的運算結果。