[JAVA] 17. 제네릭 & Wrapper & 컬렉션 & 오브젝트 Ⅲ. Object 메서드 (1) hashCode()

최재원's avatar
Feb 18, 2025
[JAVA] 17. 제네릭 & Wrapper & 컬렉션 & 오브젝트 Ⅲ. Object 메서드 (1) hashCode()
주소값을 해쉬코드로 바꿈
notion image

1. 아스키코드로 만드는 hashCode

package ex17; public class Ha01 { public static int simpleHash(String key, int tableSize) { int hash = 0; for (char c : key.toCharArray()) { hash += c; // 각 문자의 ASCII 값을 더함 } return hash % tableSize; // 테이블 크기로 나눈 나머지를 해시 값으로 사용 } public static void main(String[] args) { String key1 = "apple"; String key2 = "banana"; int tableSize = 10; // 해시 테이블 크기 System.out.println("apple의 해시 값: " + simpleHash(key1, tableSize)); System.out.println("banana의 해시 값: " + simpleHash(key2, tableSize)); } }
notion image

2. 생성한 객체의 주소를 해시값으로 확인

package ex17; class Animal { } public class Ha02 { public static void main(String[] args) { Animal a = new Animal(); System.out.println(a.hashCode()); Animal b = new Animal(); System.out.println(b.hashCode()); } }
notion image
 
Share article

jjack1