Java中equal、hashCode等幾個方法

來源:互聯網
上載者:User
文章目錄
  • equals
  • hashCode

String類:

public boolean equals(Object anObject) 重載了object的equals方法
Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.
public int hashCode() 同樣重載了object的hashCode方法
Returns a hash code for this string. The hash code for a String object is computed as

 s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] 

using int arithmetic, where s[i] is the ith character of the string, n is the length of the string, and ^ indicates exponentiation. (The hash value of the empty string is zero.)

但是StringBuffer並沒有重載equals和hashCode方法,所以當調用這兩個方法的時候,還是用的object類中的方法,故而即使兩個StringBuffer的內容一樣,也可能算出的hashCode並不一樣

File類:

compareTo

public int compareTo(File pathname)
Compares two abstract pathnames lexicographically. The ordering defined by this method depends upon the underlying system. On UNIX systems, alphabetic case is significant in comparing pathnames; on Microsoft Windows systems it is not.
equals
public boolean equals(Object obj) 重載了object的方法
Tests this abstract pathname for equality with the given object. Returns true if and only if the argument is not null and is an abstract pathname that denotes the same file or directory as this abstract pathname. Whether or not two abstract pathnames are equal depends upon the underlying system. On UNIX systems, alphabetic case is significant in comparing pathnames; on Microsoft Windows systems it is not.
hashCode
public int hashCode() 重載了object的方法
Computes a hash code for this abstract pathname. Because equality of abstract pathnames is inherently system-dependent, so is the computation of their hash codes. On UNIX systems, the hash code of an abstract pathname is equal to the exclusive or of the hash code of its pathname string and the decimal value 1234321. On Microsoft Windows systems, the hash code is equal to the exclusive or of the hash code of its pathname string converted to lower case and the decimal value 1234321. Locale is not taken into account on lowercasing the pathname string.

所以給一個檔案和其copy分別建立一個對象,可能這兩個對象的雜湊值並不相同,因為和路徑有關,並不意味著這兩個檔案不一樣(這兒是指檔案內容),如果用hash軟體或者md5軟體來計算這兩個檔案的hash值,就應該是一樣的

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.