---
title: "HashMap 取值应注意key的类型"
author: "john201314"
date: "2015-05-02T17:14:02Z"
tags: ["Java"]
categories: ["编程语言"]
slug: "hashmap-key"
draft: false
lastmod: "2015-05-02T17:20:39Z"
id: 2207911
url: "https://john201314.iteye.com/blog/2207911"
---

```java
 Map<Long,String> hashMap = new HashMap<Long,String>();
        hashMap.put(new Long(1), "A");
        System.out.println(hashMap.get(new Integer(1)));
```

发现取的值为null.

这是因为取值的时候没有与key的类型匹配。

这是取值的逻辑代码

```java

   final Entry<K,V> getEntry(Object key) {
        int hash = (key == null) ? 0 : hash(key);
        for (Entry<K,V> e = table[indexfor(hash, table.length)];
             e != null;
             e = e.next) {
            Object k;
            if (e.hash == hash &&
                ((k = e.key) == key || (key != null && key.equals(k))))
                return e;
        }
        return null;
    }

```


但是Integer的equals方法

```java

  public boolean equals(Object obj) {
        if (obj instanceof Integer) {
            return value == ((Integer)obj).intValue();
        }
        return false;
    }


```

Long的equals方法

```java

  public boolean equals(Object obj) {
        if (obj instanceof Long) {
            return value == ((Long)obj).longValue();
        }
        return false;
    }

```


即使值相等，但因为类型不匹配，并且HashMap接受的参数类型是Object,它这样设计的用途是为了所有的类型都通用。但是HashMap本身就没声明说，一定要类型对才能取值。
哈哈以后要注意了。