1、HashMap中是否存在key的判断方法如下,归根结底是判断key的hashcode方法:
public boolean containsKey(Object key) { return getEntry(key) != null; }
final Entry<K,V> getEntry(Object key) { if (size == 0) { return null; } 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; }
final int hash(Object k) { int h = hashSeed; if (0 != h && k instanceof String) { return sun.misc.Hashing.stringHash32((String) k); } h ^= k.hashCode(); // This function ensures that hashCodes that differ only by // constant multiples at each bit position have a bounded // number of collisions (approximately 8 at default load factor). h ^= (h >>> 20) ^ (h >>> 12); return h ^ (h >>> 7) ^ (h >>> 4); }
2、而Long和Integer的hashcode方法分别如下:
Long:
public int hashCode() { return (int)(value ^ (value >>> 32)); }
Integer:
public int hashCode() { return value; }
3、问题来了,
当hashmap的key为Long时,用数值a相等的Integer去判断a这个数值可以是否在hashmap中(containsKey),
结果是false;
4、解决方法:
4-1:将Integer强制转换成Long。
4-2:思考中。。。