반응형

[ 서 론 ]

해당 게시물은 인터넷에 여러 떠돌아 다니는 정보를 종합해서

제가 이해한 수준으로 적습니다.

우리는 HashCode 라는 메소드를 자주 사용합니다. 때론 골때리는 경우가 발생할 수 있는데요..

과연 HashCode값은 유일성을 보장해 주는것인가?  .흠... 절대 아닌듯...

[ 결 론 ]

우리가 보통

HashMap map = new HashMap();
map.put("test","1234");

라고 넣는다 key는 test 이다. 그럼 내부로직은 어떻게 될까? test라는 String 문자열값을 hasCode 화 하여 저장한다.

API에 보면 아래와 같이 공식이 적혀있다.


public int hashCode()
Returns a hashcode for this string. The hashcode for a String object is computed as
 s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
using int arithmetic, where s[i] is the ith character of the string, n is the length of the string, and ^ indicates exponentiation. (The hash value of the empty string is zero.)
Overrides:
hashCode in class Object
Returns:
a hash code value for this object.
 

주저리 주저리 영어로 되어있지만 결론적으로 네모 박스 안에가 공식이다.

저런 공식을 통해 return 값은 int 타입이다.

즉, 4,294,967,295 개 반환 가능하다는 말이다.

이말인즉 언젠가는 겹칠 가능성이 존재한다는것이다. 왜냐 String은 JVM이 뻐티는 한 무한대로

생성가능하기 때문이다.

따라서 내부적으로 HashCode값과 뭔가를 같이 써야지만, 중복없는 hashCode값이 생성될것이다.

이상!!!! 끝!

반응형

'Program > JAVA' 카테고리의 다른 글

POJO(Plain Old Java Object) 란?  (5) 2010.11.05
Abstract Class란?  (0) 2010.09.16
Spring 설정 방법 - UPDATE중  (0) 2010.02.09
[ Factory Pattern ]  (0) 2010.02.07
Properties Class를 이용하여 설정파일 가져오기  (0) 2010.02.06

+ Recent posts