比較在審計android源代碼時,我發現了一個字符串比較bug,它使用==而不是equals()。但是,該應用程序運行得非常出人意料!android replaceAll和字符串與==
一些測試後,我發現的replaceAll()方法被隱藏的錯誤。
String description = " ";
description = description.trim();
Result1.setText(description + " == " + "" + ": " + (description == ""));
按我的預期打印「==:false」。但是,
String description = " ";
description = description.trim().replaceAll("\\s+|\\r+|\\n+", " ");
Result1.setText(description + " == " + "" + ": " + (description == ""));
打印「==:true」! (是Android 4.4.2,API 19)
我運行相同的代碼在我的桌面文件(javac 1.6.0_45),並打印 「==:假」 如我所料。
這是Android中的錯誤還是它的預期行爲?
首先,我認爲這是Android開源項目的一個片段:反正,我不知道,但基於[這個答案](http://stackoverflow.com/a/513839/2821954)這可能與字符串實習有關。 (這只是我的猜測) –
'description.trim()'是空的所以'replaceAll(「\\ s + | \\ r + | \\ n +」,「」)'什麼也沒做。底線是,不能保證使用'=='的比較是否會返回true或false。但是'equals'方法的行爲已經很好的規定了。因此'description ==「」'應該被替換爲'description.equals(「」)或'description.isEmpty()'。 –