2013-08-02 2 views
-3

내가 접근 하나와 초기화하려고 왜 내가 해시 코드를 인쇄 할 때 인쇄 제로의은 HashMap의의 해시 코드는 제로

HashMap<String, String> myMap = new HashMap<String, String>(10); 
myMap.put("key", "value"); 
System.out.println(myMap.hashCode()); 

첫 번째 방법에서,하지만에서 두 번째 방법은 해시 코드를 출력하는 것입니다. 초기화 후 해시 코드가 반환됩니다.

왜 첫 번째 경우의 HashCode가 인쇄되었지만 두 번째 경우는 아닌지?

+7

뭐죠? – Khashayar

+1

무엇을 원하십니까? 나는 이해할 수 없다. 지도를 초기화하려면 새로운 HashMap()을 사용하십시오. –

+1

접근법 3 : Map myMap = new HashMap (10); –

답변

4

Keyvalue이 같은 경우에만 HashCode은 0이됩니다.

다음과 같이 때문이다 HashMap의 내부 항목의 해시 코드 구현의 일이 일어나고 :

public final int hashCode() 
{ 
    return (key==null ? 0 : key.hashCode())^(value==null ? 0 : value.hashCode()); 
} 

그것은 해시 코드의 항상 않으면 0을 반환, 모두 키와 값의에 ^ 수행 둘 다 동일합니다. 당신의 예에서

는 다음 두지도의이 해시 코드를 0

접근이 반환됩니다 myMap.put("key", "key")을 변경하는 경우 :

HashMap<String, String> myMap = new HashMap<String, String>(10); 
myMap.put("key", "key"); 
System.out.println(myMap.hashCode()); 

출력 :

0 
0 
0

I을 appr을 추천하다 oach 세 :

Map<String, String> map = new HashMap<>(10); 
map.put("key", "value"); 

당신은 단지 당신이 모든 후 HashMap를 사용하지 않기로 결정한 경우 한 가지를 수정해야 그런 식으로.

0

아래 코드의 첫 번째 줄은 두 번째 줄에서 재정의하므로 중복되어 있습니다.

Map<String, String> mapInter = Collections.EMPTY_MAP; 
mapInter = new HashMap<String, String>(); 

위의 코드는이 또한

Map<String, String> mapInter = new HashMap<String, String>(); 
2

당신이 접근 한 그것을 사용했습니다으로 초기화에 Collections.EMPTY_MAP의 사용은,이다 같다

Map<String, String> mapInter = null; 
mapInter = new HashMap<String, String>(); 

같다 없음.

변수에 EMPTY_MAP 필드를 지정하고 즉시 덮어 씁니다. 이 첫 번째 할당을 전혀 수행하지 않으면 코드가 동일하게됩니다 (예 ::

Map<String, String> mapInter; 
mapInter = new HashMap<String, String>(); 
mapInter.put("one", "one"); 

또는

Map<String, String> mapInter = new HashMap<String, String>(); 
mapInter.put("one", "one"); 

을 위해 사용되는 변수 는 현재 오브젝트의 해시 아무런 관계가 없음 값.

0

컬렉션 클래스는 컬렉션에서 작동하거나 콜렉션을 반환하는 정적 메서드로만 구성됩니다. 귀하의 Collections.EMPTY_MAP에 대한 Noe입니다. 그것은 다음과 같은 방법을

/** 
* Returns the empty map (immutable). This map is serializable. 
* 
* <p>This example illustrates the type-safe way to obtain an empty set: 
* <pre> 
*  Map&lt;String, Date&gt; s = Collections.emptyMap(); 
* </pre> 
* Implementation note: Implementations of this method need not 
* create a separate <tt>Map</tt> object for each call. Using this 
* method is likely to have comparable cost to using the like-named 
* field. (Unlike this method, the field does not provide type safety.) 
* 
* @see #EMPTY_MAP 
* @since 1.5 
*/ 
@SuppressWarnings("unchecked") 
public static final <K,V> Map<K,V> emptyMap() { 
    return (Map<K,V>) EMPTY_MAP; 
} 

public static final Map EMPTY_MAP = new EmptyMap<>(); 

그래서 기본적으로는 데이터가없는 맵을 돌려줍니다

를 호출하는 것과 같습니다.