java中Long和Integer在hashmap判断key是否存在的问题
2017-03-23 18:58
405 查看
1、HashMap中是否存在key的判断方法如下,归根结底是判断key的hashcode方法:
2、而Long和Integer的hashcode方法分别如下:
Long:
Integer:
3、问题来了,
当hashmap的key为Long时,用数值a相等的Integer去判断a这个数值可以是否在hashmap中(containsKey),
结果是false;
4、解决方法:
4-1:将Integer强制转换成Long。
4-2:思考中。。。
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:思考中。。。
相关文章推荐
- Java学习-020-Properties 判断是否存在对应的 key 项
- java 判断json 某key是否存在
- java判断tomcat下面是否存在某个文件夹并&java上传文件时对文件夹的判断问题
- hashmap判断是否存在key时,使用get(key)==null判断还是containsKey?
- JavaSE8基础 HashMap<Integer,String> containsKey/Value 判断集合是否包含指定的键或值
- java 多种判断key是否在map中存在的方法
- java memcache判断key是否存在
- Java判断id,用户,是否存在问题
- java访问远程文件判断是否存在的问题
- java 多种判断key是否在map中存在的方法
- Java HashMap使用String,Long,Integer作为key的性能测试
- java 多种判断key是否在map中存在的方法
- 判断单链表是否存在环,判断两个链表是否相交问题详解(zz)
- Integer间判断值是否相等问题
- java判断url地址是否存在
- 判断单链表是否存在环,判断两个链表是否相交问题详解
- 判断单链表是否存在环,判断两个链表是否相交问题详解
- 判断单链表是否存在环,判断两个链表是否相交问题详解
- 判断单链表是否存在环,判断两个链表是否相交问题详解(转载)
- 判断单链表是否存在环,判断两个链表是否相交问题详解