hashCode()

hashCode()λŠ” 객체의 동일성을 νŒλ‹¨ν•œλ‹€.

equalsλ₯Ό μž¬μ •μ˜ν•œ ν΄λž˜μŠ€μ—λŠ” hashCode도 λ°˜λ“œμ‹œ μž¬μ •μ˜ν•œλ‹€.

Override either both of them or neither of them.

Java의 hashCode

κ°μ²΄λ§ˆλ‹€ κ°€μ§€κ³  μžˆλŠ” hashCodeλŠ” 객체λ₯Ό νŒλ³„ν•˜λŠ” 고유 μ •μˆ˜κ°’μ΄λ‹€. Object 클래슀의 hashCode() λ©”μ†Œλ“œκ°€ 객체의 hashCode값을 return ν•΄μ€€λ‹€.

ν•΄μ‹œ μ•Œκ³ λ¦¬μ¦˜μ„ μ‚¬μš©ν•˜κΈ° μœ„ν•΄μ„œλŠ” 2κ°€μ§€ κΈ°λŠ₯이 ν•„μš”ν•˜λ‹€.

  • ν•΄μ‹œμ½”λ“œλ₯Ό λ§Œλ“€μ–΄μ•Ό ν•œλ‹€.

  • 값이 같은지λ₯Ό 비ꡐ해야 ν•œλ‹€.

이 두가지가 μžˆμ–΄μ•Ό ν•΄μ‹œλ₯Ό 잘 κ΅¬ν˜„ν•  수 μžˆλ‹€.

μžλ°”μ˜ μ»¬λ ‰μ…˜ 자료ꡬ쑰λ₯Ό 보면 hashκ°€ 뢙은 애듀이 μ‘΄μž¬ν•œλ‹€.

  • hashSet, hashMap, hashTable

예제

@Test
@DisplayName("같은 객체λ₯Ό hashCode 비ꡐ")
void hash() {
    Ball ball = new Ball("1");
    Ball ball2 = new Ball("1");

    System.out.println(ball.hashCode());
    System.out.println(ball2.hashCode());
    Assertions.assertThat(ball.hashCode()).isEqualTo(ball2.hashCode());
}

// fail
Expected :1484531981
Actual   :17037394

ν˜„μž¬ equals()λŠ” μ˜€λ²„λΌμ΄λ”© λ˜μ—ˆμ§€λ§Œ hashCode()λŠ” κ·Έλ ‡μ§€ μ•Šλ‹€. λ‹Ήμ—°νžˆ 두 객체의 ν•΄μ‹œκ°’μ΄ κ°™μ§€ μ•Šμ•„μ„œ ν…ŒμŠ€νŠΈλŠ” μ‹€νŒ¨ν•˜κ²Œ λœλ‹€. 객체의 ν•„λ“œκ°’μ΄ 같아도 이 λ‘˜μ€ 같은 객체둜 λ³΄μ§€μ•ŠλŠ”κ²ƒμ΄λ‹€. κ·Έλ ‡κΈ° λ•Œλ¬Έμ— hashCode()λ₯Ό μž¬μ •μ˜ν•œλ‹€.

hashCode()λ₯Ό μ˜€λ²„λΌμ΄λ”© ν•˜κ³ λ‚˜μ„œ 객체λ₯Ό λΉ„κ΅ν•˜λ©΄,

객체 ν•„λ“œ 값이 κ°™μœΌλ©΄ hashCode 값도 κ°™μ•„μ§€κΈ° λ•Œλ¬Έμ— 두 κ°μ²΄λŠ” κ°™λ‹€κ³  λ³Έλ‹€.

Last updated