2013-08-02 19 views
-3

我试图用一种用法初始化:为什么HashMap中的散列码是零

Map<String, String> mapInter = Collections.EMPTY_MAP; 
mapInter = new HashMap<String, String>(); 
mapInter.put("one", "one"); 
System.out.println(mapInter.hashCode());   

方法有两个:

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

在第一种方法,当我打印的哈希码是打印为零,但在第二种方法是打印哈希码。初始化后的hashcode将被返回。

为什么第一个Case中的HashCode打印为零,但不是第二种情况?

+7

最新问题? – Khashayar

+1

你有什么要求?我无法理解。 初始化一个地图只是做一个新的HashMap() –

+1

方法三: 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的哈希码的两者都是一样的。

在您的例子,如果你改变了myMap.put("key", "key")那么这两个地图的将返回哈希码0

方法有两个:

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

输出:

0 
0 
0

我推荐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 = null; 
mapInter = new HashMap<String, String>(); 

这也等于

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

使用的初始化Collections.EMPTY_MAP,正如您在方法一用它,是nothing

您将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

集合类完全由对集合进行操作或返回集合的静态方法组成。 Noe为您的Collections.EMPTY_MAP。这等同于调用下面的方法

/** 
* 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<>(); 

所以基本上它返回,没有数据的地图。

相关问题