==
用來判斷兩個值,或者兩個對象的內存地址是否一樣。
equals
equals 方法用來判斷兩個對象是否相等。equals 是Object 類的方法,默認情況下,比較兩個對象是否是同一個對象,內部通過 == 實現。如果想比較兩個對象的其他內容,則可以通過重寫equals 方法。比如String 就重寫了equals 方法。
equals是Object類的方法,默認情況下比較兩個對象是否是同一個對象,內部實現是通過“==”來實現的。
如果想比較兩個對象的其他內容,則可以通過重寫equals方法,
例如:String類就重寫了equals方法,改成了對象的內容是否相等。
hasCode方法:
/**
* Returns a hash code value for the object. This method is
* supported for the benefit of hash tables such as those provided by
* {@link java.util.HashMap}.
* <p>
* The general contract of {@code hashCode} is:
* <ul>
* <li>Whenever it is invoked on the same object more than once during
* an execution of a Java application, the {@code hashCode} method
* must consistently return the same integer, provided no information
* used in {@code equals} comparisons on the object is modified.
* This integer need not remain consistent from one execution of an
* application to another execution of the same application.
* <li>If two objects are equal according to the {@code equals(Object)}
* method, then calling the {@code hashCode} method on each of
* the two objects must produce the same integer result.
* <li>It is <em>not</em> required that if two objects are unequal
* according to the {@link java.lang.Object#equals(java.lang.Object)}
* method, then calling the {@code hashCode} method on each of the
* two objects must produce distinct integer results. However, the
* programmer should be aware that producing distinct integer results
* for unequal objects may improve the performance of hash tables.
* </ul>
* <p>
* As much as is reasonably practical, the hashCode method defined by
* class {@code Object} does return distinct integers for distinct
* objects. (This is typically implemented by converting the internal
* address of the object into an integer, but this implementation
* technique is not required by the
* Java™ programming language.)
*
* @return a hash code value for this object.
* @see java.lang.Object#equals(java.lang.Object)
* @see java.lang.System#identityHashCode
*/
public int hashCode() {
return identityHashCode(this);
}
hasCode 這個方法會在HasMap 裏面使用到。
通常來說,在一次程序運行期間,一個對象的hasCode 是不變的。在不同的程序運行期間可以不同。
如果兩個對象的equals的方法返回的值是相等的,那麼hasCode 就應該返回一樣的值。
不同的對象的hasCode可能是一樣的。但是不同對象返回不同hasCode 能夠提高has 表的性能。
同一個類,new 出來兩個實例,他們倆的hasCode 是不一樣的。