java equals函數(shù)用法詳解
更新時間:2012年11月30日 10:42:14 投稿:whsnow
java 中equals函數(shù)的使用方法是廣大java愛好者所關(guān)心的一個話題,本文將詳細介紹其使用方法,需要了解的朋友可以參考下
equals函數(shù)在基類object中已經(jīng)定義,源碼如下
復(fù)制代碼 代碼如下:
public boolean equals(Object obj) {
return (this == obj);
}
從源碼中可以看出默認的equals()方法與“==”是一致的,都是比較的對象的引用,而非對象值(這里與我們常識中equals()用于對象的比較是相餑的,原因是java中的大多數(shù)類都重寫了equals()方法,下面已String類舉例,String類equals()方法源碼如下:)
[java]
復(fù)制代碼 代碼如下:
/** The value is used for character storage. */
private final char value[];
/** The offset is the first index of the storage that is used. */
private final int offset;
/** The count is the number of characters in the String. */
private final int count;
[java] view plaincopyprint?
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;
}
} //www.software8.co
return false;
}
String類的equals()非常簡單,只是將String類轉(zhuǎn)換為字符數(shù)組,逐位比較。
相關(guān)文章
SpringBoot開發(fā)技巧之如何處理跨域請求CORS
CORS(Cross-Origin Resource Sharing)"跨域資源共享",是一個W3C標準,它允許瀏覽器向跨域服務(wù)器發(fā)送Ajax請求,打破了Ajax只能訪問本站內(nèi)的資源限制2021-10-10