读书人

HashMap hashCode奇怪的兑现

发布时间: 2012-10-19 16:53:36 作者: rapoo

HashMap hashCode奇怪的实现

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









?

读书人网 >编程

热点推荐