public class random {
public static class A{
int id= 1;
public int hashCode(){
return id;
}
}
public static void main(String[] args) {
Map<Integer, Integer> map= new HashMap<Integer, Integer>();
A a = new A();
A b = new A();
map.put(a.id, 1);
map.put(b.id, 2);
System.out.println(map.get(a.id));
System.out.println(map.get(b.id));
System.out.println(map.size());
}
}输出是
2
2
1A和b有相同的哈希码(桶),在这个桶内是(1和2)。它说只有一个节点存在,即b的值为2。当两个哈希码相同时,它们是否覆盖当前值?我读到的情况并非如此。
从教程
*"Since hashcode is same, bucket location would be same and collision will occur in HashMap, Since HashMap use LinkedList to store object, this entry (object of Map.Entry comprise key and value ) will be stored in LinkedList.
Read more: http://javarevisited.blogspot.com/2011/02/how-hashmap-works-in-java.html#ixzz2sCM7fNED*这是否意味着我的地图现在有一个值为2个的桶?如何获取(1)的值
发布于 2014-02-02 20:34:25
它们都有相同的id " 1 ",所以当你将它们添加到地图的id键下时,它们都会被添加到键1中,所以第二个会覆盖第一个。
发布于 2014-02-02 20:36:36
来自java (http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html)的hashmap文档
HashMap.put()将指定的值与此映射中的指定键关联。如果映射以前包含键的映射,则替换旧值。
因此,新的值将取代旧的值。
发布于 2014-02-02 20:40:13
您正在使用Integer id作为Map中的键,而不是a或b。因此,根本不使用hashcode() of A。
若要从映射中获取值,请使用get方法。
如果要使用a1或a2作为键,则需要将映射声明为如下:
Map<A, Integer> map = new HashMap<>();https://stackoverflow.com/questions/21515796
复制相似问题