Returns a hash code value for the object.
This method is supported for the benefit of hash tables such as those provided by HashMap
- ๊ฐ์ฒด์ ํด์ ์ฝ๋ ๊ฐ์ ๋ฆฌํดํฉ๋๋ค.
- ์ด ๋ฉ์๋๋ HashMap์์ ์ ๊ณตํ๋ ๊ฒ๊ณผ ๊ฐ์ HashTable์ ์ด์ ์ ์ํด ์ง์๋ฉ๋๋ค.
์ฝ๋๋ก ๋ณด๊ฒ ์ต๋๋ค.
package com.study.hashcode.equals
public class LikeLion {
private String name;
private int age;
public LikeLion(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
package com.study.hashcode.equals
public class Example01 {
public static void main(String[] args) {
Object obj = new Object();
System.out.println("(1) ์ฐธ์กฐ๋ณ์ obj ์ถ๋ ฅ๊ฐ: " + obj);
System.out.println("(2) obj ๊ฐ์ฒด์ hashcode ์ถ๋ ฅ๊ฐ: " + obj.hashCode());
LikeLion lion = new LikeLion("์๊ธฐ์ฌ์", 20);
System.out.println("(3) ์ฐธ์กฐ๋ณ์ lion ์ถ๋ ฅ๊ฐ: " + lion);
System.out.println("(4) lion ๊ฐ์ฒด์ hashcode ์ถ๋ ฅ๊ฐ: " + lion.hashCode());
String str1 = "๋ฉ์ฌ";
System.out.println("(5) \"๋ฉ์ฌ\" ๊ฐ์ฒด์ hashcode ์ถ๋ ฅ๊ฐ: " + str1.hashCode());
String str2 = "๋ฉ์ฌ";
System.out.println("(6) \"๋ฉ์ฌ\" ๊ฐ์ฒด์ hashcode ์ถ๋ ฅ๊ฐ: " + str2.hashCode());
}
}
์ถ๋ ฅ ๊ฒฐ๊ณผ๋ ๋ค์๊ณผ ๊ฐ์ต๋๋ค.
(1) ์ฐธ์กฐ๋ณ์ obj ์ถ๋ ฅ๊ฐ: java.lang.Object@1540e19d
(2) obj ๊ฐ์ฒด์ hashcode ์ถ๋ ฅ๊ฐ: 356573597
(3) ์ฐธ์กฐ๋ณ์ lion ์ถ๋ ฅ๊ฐ: com.study.hashcode.equals.LikeLion@677327b6
(4) lion ๊ฐ์ฒด์ hashcode ์ถ๋ ฅ๊ฐ: 1735600054
(5) "๋ฉ์ฌ" ๊ฐ์ฒด์ hashcode ์ถ๋ ฅ๊ฐ: 1527745
- (1)์ 16์ง์, (2)๋ (1)์ 10์ง์๋ก ๋ณํํ ๊ฐ์ ๋๋ค.
- ์๋ก ๋ค๋ฅธ ๊ฐ์ฒด๋ ๊ฐ๊ฐ์ ์ฃผ์๊ฐ์ ๊ฐ๊ธฐ ๋๋ฌธ์ ๋ค๋ฅธ hashcode ๊ฐ์ ๊ฐ์ต๋๋ค.
- (3)๋ 16์ง์, (4)๋ (3)์ 10์ง์๋ก ๋ณํํ ๊ฐ์ ๋๋ค.
- ์ ๋ฆฌํ๋ฉด, Object.hashCode() ๋ฉ์๋๋ ๊ฐ ๊ฐ์ฒด์ ๋์๋๋ ๊ณ ์ ํ ์ ์๊ฐ์ ๋ฆฌํดํฉ๋๋ค.
- ์ ์์ ์ hashCode() ๋ฉ์๋๋ Object ํด๋์ค์ ์ ์๋ ๋ฉ์๋์
๋๋ค.
๊ฐ์ฒด์ ์ฃผ์๊ฐ๊ณผ ์ฐ๊ด์ด ์์ต๋๋ค.
- String ํด๋์ค์ hashCode() ๋ฉ์๋๋ Overriding์ ํตํด ์๋กญ๊ฒ ์ ์๋ฉ๋๋ค.
- ์ด ์๋กญ๊ฒ ์ ์๋ ๋ด์ฉ์ ๋ฐ๋ฅด๋ฉด, ๊ฐ์ ๋ฌธ์์ด์ ๊ฐ์ hashcode ๊ฐ์ ๊ฐ์ต๋๋ค.
- String ํด๋์ค์์ hashCode() ๋ฉ์๋๋ฅผ Overridingํ์ง ์์ผ๋ฉด,
String str1 = "๋ฉ์ฌ" ์ String str2 = "๋ฉ์ฌ" ์ hashcode๋ ์๋ก ๋ค๋ฅธ ๊ฐ์ด์ด์ผ ํฉ๋๋ค. - ๊ทธ๋ฐ๋ฐ String ํด๋์ค ์ ์ฅ์์ str1๊ณผ str2๋ ๊ฐ์ ๋ฌธ์์ด์ด๊ธฐ ๋๋ฌธ์ ๊ฐ์ ๊ฐ์ฒด๋ผ๊ณ ์๊ฐํ ์ ์์ต๋๋ค.
- ๊ฐ์ ๋ฌธ์์ด์ ๊ฐ์ ๋ ๊ฐ์ฒด์ hashcode ๊ฐ์ด ๋ค๋ฅด๋ค๋ฉด hashcode์ ์๋ฏธ๊ฐ ์๋ค๊ณ ์๊ฐํ ์ ์์ต๋๋ค.
- hashcode ๊ฐ์ ํ์ฉํด Map์ด๋ Set์ ์ ์ฅ๋ Key ๊ฐ์ ์ฐพ์์ผ ํ๋๋ฐ,
๊ฐ์ ๊ฐ์ฒด์์๋ ๋ถ๊ตฌํ๊ณ hashcode ๊ฐ์ด ๋ค๋ฅด๋ ์ ๋๋ก ์ฐพ์ ์๊ฐ ์์ ๊ฒ์ ๋๋ค. - ๊ทธ๋ ๊ธฐ ๋๋ฌธ์, ์ธ์์ ์ผ๋ก hashCode() ๋ฉ์๋๋ฅผ Overridingํ ๊ฒ์ ๋๋ค.