JAVA/JAVA기본
JAVA - hashCode의 의미
realizers
2021. 12. 14. 21:34
728x90
반응형
hashCode란?
- 객체 해시코드란 객체를 식별하는 하나의 정수값을 의미합니다.
- Object의 hashCode() 메서드는 객체의 메모리 번지를 이용해서 해시코드를 만들어 리턴하기 때문에 객체 마다 다른 값들을 가지고 있습니다.
- 두 객체가 같은 객체인지 동일성을 비교합니다.
- 어떠한 객체와 다른 객체의 equals 결과가 true라면 그 둘의 hashCode 값는 반드시 같아야 하지만 반대로 hashCode값이 같다고 해서 반드시 equals 결과가 true일 필요는 없습니다.
public class Example {
public static void main(String[] args) {
Person person1 = new Person("KDG");
Person person2 = new Person(new String("KDG"));
Person person3 = person2;
System.out.println(person1.hashCode()); // 1521118594
System.out.println(person2.hashCode()); // 1940030785
System.out.println(person3.hashCode()); // 1940030785
}
}
class Person{
String name;
public Person(String name) {
this.name = name;
}
@Override
public boolean hashCode(Object object) {
Person another = (Person) object;
return (this.name.equals(another.name));
}
}
- person1과 person2의 hashCode는 당연히 다릅니다. 왜냐하면 hashCode는 주소를 기반으로 생성된 정수값이기 때문입니다. 대신 person2와 person3은 동일한 주소값을 가지기 때문에 hashCode도 동일합니다.
728x90
반응형