1. 程式人生 > 程式設計 >詳談Map的key、value值的資料型別不能為基本型別的原因

詳談Map的key、value值的資料型別不能為基本型別的原因

interface Map<K,V>

Map原始碼

  /**
     * Returns the hash code value for this map entry. The hash code
     * of a map entry <tt>e</tt> is defined to be: <pre>
     *   (e.getKey()==null  ? 0 : e.getKey().hashCode()) ^
     *   (e.getValue()==null ? 0 : e.getValue().hashCode())
     * </pre>
     * This ensures that <tt>e1.equals(e2)</tt> implies that
     * <tt>e1.hashCode()==e2.hashCode()</tt> for any two Entries
     * <tt>e1</tt> and <tt>e2</tt>,as required by the general
     * contract of <tt>Object.hashCode</tt>.
     *
     * @return the hash code value for this map entry
     * @see Object#hashCode()
     * @see Object#equals(Object)
     * @see #equals(Object)
  */
    int hashCode();

hashCode返回 (e.getKey()==null ? 0 : e.getKey().hashCode()) ^(e.getValue()==null ? 0 : e.getValue().hashCode())

class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>,Cloneable,Serializable

HashMap原始碼中:

public final int hashCode() {
 return Objects.hashCode(key) ^ Objects.hashCode(value);
}
static final int hash(Object key) {
 int h;
 return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
public final boolean equals(Object o) {
 if (o == this)
    return true;
  if (o instanceof Map.Entry) {
    Map.Entry<?,?> e = (Map.Entry<?,?>)o;
  if (Objects.equals(key,e.getKey()) &&
    Objects.equals(value,e.getValue()))
    return true;
  }
  return false;
}

補充知識:java hashmap key long 和int 區別

最近同事問起,map裡面存的key 是int 型別的,存了一個 Integera =123,為什麼使用long 123 作為key get,取出來的是空,這個問題粗想了一下,感覺long和int 本身 型別不同,肯定不能是同一個key,後來細研究了一下,跟了一下原始碼,發現邏輯不是那麼簡單。

簡單測試了一下,如下程式碼

Map<Object,String> map = new HashMap<>();
Integer b = 123;
Long c =123L;
map.put(b,b+"int");
System.out.println(b.hashCode() == c.hashCode()); //true
System.out.println(map.get(c));  //null
map.put(c,c+"long"); // size =2

簡單的總結了一下問題:

1、HashMap 是把key做hash 然後作為陣列下標,但是 b 和c 的hashcode 竟然是相同的,為什麼 get(c) 為空

2、HashMap 存入c 發現 size=2 ,hashcode相同 為什麼 size=2,get(c) =123long

帶著上面兩個問題跟了一遍原始碼,問題豁然開朗

1、hashmap在存入的時候,先對key 做一遍 hash,以hash值作為陣列下標,如果發現 下標已有值,判斷 存的key 跟傳入的key是不是相同,使用 (k = p.key) == key || (key != null && key.equals(k)) ,如果相同覆蓋,而Interger的equals 方法如下:

if (obj instanceof Integer) {
      return value == ((Integer)obj).intValue();
    }

return false;

Integer 和 Long 肯定不是一個型別,返回 false,這時候 hashmap 以 hashkey 衝突來處理,存入連結串列,所以 Long 123 和 Integer 123 hashmap會認為是 hash衝突

2、hashmap 在 get的時候,也是先做 hash處理,根據hash值查詢對應的陣列下標,如果找到,使用存入時候的判斷條件

(k = first.key) == key || (key != null && key.equals(k)) 如果相等就返回,不相等,查詢當前值的next有沒有值,有繼續根據邏輯判斷,所以 存入Integer 123 根據 Long 123 來獲取返回的 是 NULL

至此,解析完畢。

以上這篇詳談Map的key、value值的資料型別不能為基本型別的原因就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。