无意看群里有人讨论HashMap,new出来的HashMap实例hashCode都是一样的。而且循环放入键值也还是一样,都是0.细看HashMap hashCode的实现,也就是它的父类AbstractMap的代码 :
public int hashCode() {
int h = 0;
Iterator<Entry<K,V>> i = entrySet().iterator();
while (i.hasNext())
h += i.next().hashCode();
return h;
}
继续看Entry的hashCode:
public final int hashCode() {
return (key==null ? 0 : key.hashCode()) ^
(value==null ? 0 : value.hashCode());
}
由此就不难看出,当一个HashMap实例中,所存储的所有元素key value 对 的hashcode都相同时,那么这个HashMap的hashCode将恒为0,这不知道算不算得上一个bug.
测试代码
Map<String,String> map;
for(int i=0;i<3;i++){
map=new HashMap<String,String>();
map.put(i+"", i+"");
System.out.println(map.hashCode());
}
System.out.println("===========");
for(int i=0;i<3;i++){
map=new HashMap<String,String>();
map.put(i+"", i+i+"");
System.out.println(map.hashCode());
}
分享到:
相关推荐
hashmap的C++实现,对于学习C++方面的很有用
hashmap的底层及源码解析,很适合大家的学习,不要积分。
Java语言使用hashmap实现向购物车添加删除修改商品,显示商品信息
C语言实现hashMap,包含创建hashMap、插入hashMap、查找hashMap、删除hashMap,已经若干经典的hash函数。文章链接:https://blog.csdn.net/sxf1061700625/article/details/109594495
HashMap底层实现原理HashMap与HashTable区别HashMap与HashSet区别。HashMap、HashTable和HashSet是Java中常用的数据结构,它们的底层实现原理以及区别如下:HashMap底层实现原理: HashMap基于哈希表(HashTable)...
用js代码实现java中hashmap 的所有功能
源码解析jdk8.0集合:HashMap的底层实现原理.pdf
NULL 博文链接:https://mengdejun.iteye.com/blog/932060
1.hashcode是用来查找的,如果你学过数据结构就应该知道,在查找和排序这一章有例如内存中有这样的位置而我有个类,这个类有个字段叫ID,我要把这个类存放在以
HashMap的实现原理
源码解析jdk7.0集合(3):HashMap的底层实现原理.pdf
13.HashMap为什么不直接使用hashCode()处理后的哈希值直接作为table的下标? 14.HashMap 的长度为什么是2的幂次方? 15.HashMap 与 HashTable 有什么区别? 16.如何决定使用 HashMap 还是 TreeMap? 17.HashMap 和 ...
listview实现,hashmaplistview实现,hashmaplistview实现,hashmaplistview实现,hashmaplistview实现,hashmaplistview实现,hashmaplistview实现,hashmaplistview实现,hashmap
Javascript实现和操作HashMap,压缩包里面有hashmap定义和操作的例子
HashMap源码实现红黑树添加元素和删除元素
HashMap重写实现 轻量级实现 使用自定义的轻量对象HashObjectMap替代jdk的HahMap HashMap里的Entry占用较大内存,可以用自己实现的轻量级容器替换,步骤如下: 1、 缓存的对象需要继承BaseHashObject /** * 这个类...
一线大厂BATJ面试题讲解-hashmap原理实现
用数据结构的思想实现java中的类hashmap