Object 클래스 메서드 중
public int hashCode ( ) 메서드는 객체 자신의 해시코드를 반환한다.
예제 )
public static void main(String[] args) {
String str1 = new String("abc");
String str2 = new String("abc");
String str3 = "def";
String str4 = "def";
System.out.println(str1.equals(str2)); // true 출력
System.out.println(str1.hashCode()); // 96354 출력
System.out.println(str2.hashCode()); // 96354 출력
System.out.println(System.identityHashCode(str1)); // 1365202186 출력
System.out.println(System.identityHashCode(str2)); // 1651191114 출력
📢 hashCode() 메서드는 문자열의 내용에 기반하여 해시 코드를 생성
따라서 str1.hashCode()와 str2.hashCode()는 동일한 문자열 "abc"을 나타내므로 같은 해시 코드 값을 반환
System.identityHashCode 메서드는 객체의 메모리 주소를 기반으로 해시 코드를 생성
str1과 str2는 두 개의 서로 다른 String 객체이므로 메모리 주소가 서로 다르기 때문에 다른 해시코드 값 반환
'Java' 카테고리의 다른 글
Java 문법 ) Object클래스 - clone (0) | 2023.11.02 |
---|---|
Java 문법) Object클래스 - toString (0) | 2023.11.02 |
Java문법) 예외처리 -4 (throw와 throws) (0) | 2023.11.01 |
Java문법) 예외처리 -3 (ClassCastException, InputMismatchException) (0) | 2023.11.01 |
Java문법) 예외처리 -2 (NullPointerException, ArrayIndexOutOfBoundsException, NumberFormatException) (0) | 2023.11.01 |