해시 코드란 무엇입니까?
- 개체를 식별하는 정수 값
- Object는 최상위 클래스 유형이며 Object의 hashCode() 메소드는 객체의 메모리 주소해시 코드 사용 객체가 생성되고 반환될 때 각 객체는 다른 값을 가집니다.
System.identityHashCode()란 무엇입니까?
- System.identityHashCode()개체의 고유한 해시 코드를 반환하는 메서드입니다.
public static native int identityHashCode(Object x);
System.identityHashCode()도 이미 Object에 선언되어 있습니다. 코드는 위와 같습니다.
객체의 주소를 int로 반환합니다.
class Ex9_3 {
public static void main(String() args) {
//String str1 = new String("abc") 는 new 연산자를 이용한 생성법이고,
//String str2 = "abc"; 는 문자열 리터럴 생성법이다.
//new 연산자는 메모리의 heap 영역에 할당되고 리터럴 방식은 String Constant Pool 영역에 할당된다.
//String Constant Pool 영역은 Java Heap Memory 내에 문자열 리터럴을 저장한 공간이며 HashMap으로 구현되어 있다
String str1 = new String("abc");
String str2 = new String("abc");
System.out.println(str1.equals(str2));
System.out.println(str1.hashCode());
System.out.println(str2.hashCode());
System.out.println(System.identityHashCode(str1));
System.out.println(System.identityHashCode(str2));
}
}
======실행 결과======
진실
96354
96354
460141958
1163157884
실행 결과를 보면 str1과 str2의 해시코드가 같다.
일반 객체라면 hashCode()의 결과 값이 다르고, String 객체이므로 hashCode() 값은 동일합니다.
정리하다
HashCode()를 재정의하여 각 개체의 고유한 값을 변경할 수 있습니다.
System.identityHashCode() 메서드는 재정의할 수 없으므로 객체의 고유한 hashCode를 int 유형으로 반환합니다.