Java의 HashMap에서 key값으로 primitive type은 올 수 없다.

그래서 int가 key값으로 필요하다면 Integer를 대신 사용하게 된다.


그런데 여기에서 짚고 넘어가야 할 점이 하나 있다.

HashMap에서는 key의 hashCode()값을 기준으로 entry를 찾기 때문에

처음 HashMap에 entry를 넣을 때의 key의 hashCode()값과

entry를 불러 올 때의 key의 hashCode()값이 같아야 한다.

그래서 HashMap에 entry를 넣을 때의 Integer의 reference를 유지해야,

나중에 HashMap에서 entry를 불러 올 때 사용할 수 있다라고 생각하기 쉽다.



위의 경우 과연 Integer value는 null일까?

단순히 생각해 봤을때 처음 entry를 넣을 때 Integer 객체를 하나 생성했고

entry를 찾을 때 새로운 Integer 객체를 생성했기 때문에 null값이 나올 것이라고 생각할 수도 있다.

하지만 실제로 해보면 null값이 아니라 30을 값으로 지니는 Integer가 반환된다.


그렇다면 왜 그런 것일까?

이는 Java API의 Integer의 hashCode() 부분을 보면 쉽게 알 수 있다.


hashCode

public int hashCode()
Returns a hash code for this Integer.

Overrides:
hashCode in class Object
Returns:
a hash code value for this object, equal to the primitive int value represented by this Integer object.


즉, Integer의 hashCode()를 호출하면 Integer가 표현하고 있는 primitive int 값을 리턴한다.

Integer를 언제 어디서 얼마나 많이 생성하던지간에, Integer가 표현하는 primitive int값이 같다면 모두 같은 instance를 공유하는것이 된다.

따라서 HashMap에서 Integer를 사용할 때 쓸데없이 많은 생각을 하지 않아도 된다.



위와 같은 HashMap의 사용이 가능한 것도 모두 같은 원리로써 설명이 가능하다.