equals(Object o) 메서드는 객체간 비교를 하는 메서드입니다.
만약 false가 나왔다면 서로 다른 객체로 볼 수 있습니다.
hashCode()의 값은 Hash 메서드의 결과 값입니다.
아래와 같이 객체의 상태 값들을 이용해서 hashCode() 값을 얻어 올 수 있습니다.
/* String.java#hashCode() */
/**
* Returns a hash code for this string. The hash code for a
* {@code String} object is computed as
* <blockquote><pre>
* s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
* </pre></blockquote>
* using {@code int} arithmetic, where {@code s[i]} is the
* <i>i</i>th character of the string, {@code n} is the length of
* the string, and {@code ^} indicates exponentiation.
* (The hash value of the empty string is zero.)
*
* @return a hash code value for this object.
*/
public int hashCode() {
int h = hash;
final int len = length();
if (h == 0 && len > 0) {
for (int i = 0; i < len; i++) {
h = 31 * h + charAt(i);
}
hash = h;
}
return h;
}서로 다른 타입의 객체(equals(otherTypeObject) == false)간 hashCode()의 값을 일치할 수 도 있습니다.
서로 다른 타입의 객체(equals(otherTypeObject) == false)간 Hash 메서드가 다를 수 있는데, 우연히도 그 결과가 일치할 수 있습니다.
앞선 설명대로 서로 다른 타입의 객체(equals(otherTypeObject) == false)간 hashCode를 이용한 비교는 같은 값이 나올 수 있기 때문에 할 수 없습니다.
하지만 같은 타입의 객체(equals(sameTypeObject) == true)간 hashCode()를 이용한 비교는 가능 합니다.