http://blog.csdn.net/chenhui1219/article/details/5628843#comments
java對兩個String進行比較,提高代碼運行效率方法如下:
在編程過程中,有時候我們需要迴圈比較字串,通常使用的方法是equals如下:
public class TestEquals extends Thread {
public static void main(String args[]) {
String[] checkStr = {"","aaaa","bbbb","sdf","dsdf"};
String str="DingDong";
for(int i=0;i<checkStr.length;i++){
if(str.equals(checkStr[i])){//比較字串
System.out.println("DingDong has in the checkStr list!");
break;
}
}
}
}
而equals的原始碼如下:
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String) anObject;
int n = count;
if (n == anotherString.count) {
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
while (n-- != 0) {
if (v1[i++] != v2[j++])
return false;
}
return true;
}
}
return false;
}
我們可以看到,要得到字串完全相同,必須進行如下操作:1)比較是否是同一個個對象:" if (this == anObject) {"; 2)是否是同類型對象:“if (anObject instanceof String) {”; 3)轉換字串,判斷字串長度是否相同:“if (n == anotherString.count) {”; 4)分解字串一一比較。 最終返回boolean值。
通過以上分析,字串比較經過了4補的操作最終獲得結果值。
而當我們知道兩個需要比較的對象都是字串String 時,可以對其代碼進行最佳化!最佳化後結果如下:
public static void main(String args[]) {
String[] checkStr = { "", "aaaa", "bbbb", "sdf", "dsdf" };
String str = "DingDong";
int strL = str.length();
for (int i = 0; i < checkStr.length; i++) {
if(checkStr[i]!=null&&strL==checkStr[i].length()){//先判斷長度,減少直接調用equals方法
if (str.equals(checkStr[i])) {// 比較字串
System.out.println("DingDong has in the checkStr list!");
break;
}
}
}
}
當我們需要比較的字串數組非常大時,比如有上千個String[1000]對象,而且每個字串對象都比較長時,其效能效果就會比較明顯了。
方法避免了過多的重複使用equals方法。