`
lydawen
  • 浏览: 464647 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

HashMap hashCode奇怪的实现

    博客分类:
  • java
 
阅读更多

无意看群里有人讨论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());
		}
 









 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics