我的理解是Java的HashMap实现使用指向值列表来处理碰撞的“桶”,并且如果对象的hashCode()与AND对象的equals()对于添加的对象和它碰撞的对象都是相同的。Java HashMap碰撞示例不起作用
我试着玩弄HashMap来试图看到行为中的碰撞行为,但无论我做什么,它似乎总是覆盖。
我在做什么错在这里(注意我有意留下“计数”出hashCode和等于方法)?
public class HashMapTest {
public static void main(String[] args) {
HashMapTest test = new HashMapTest();
test.execute();
}
public void execute() {
HashMap<String, Node> nodeMap = new HashMap<String, Node>();
Node node1 = new Node("data1", 1);
Node node2 = new Node("data2", 2);
String key = "1";
System.out.println("node1 hash: " + node1.hashCode());
System.out.println("node2 hash: " + node2.hashCode());
System.out.println("node1 hash == node2 hash? " + (node1.hashCode() == node2.hashCode() ? "true" : "false"));
System.out.println("node1.equals(node2)? " + (node1.equals(node2) ? "true" : "false"));
nodeMap.put(key, node1);
System.out.println("added node1 to hash map");
System.out.println("hash map size: " + nodeMap.size());
System.out.println("hash map entry set size: " + nodeMap.entrySet().size());
System.out.println("hash map contains node1? " + (nodeMap.containsValue(node1) ? "true" : "false"));
System.out.println("hash map contains node2? " + (nodeMap.containsValue(node2) ? "true" : "false"));
nodeMap.put(key, node2);
System.out.println("added node2 to hash map");
System.out.println("hash map size: " + nodeMap.size());
System.out.println("hash map entry set size: " + nodeMap.entrySet().size());
System.out.println("hash map contains node1? " + (nodeMap.containsValue(node1) ? "true" : "false"));
System.out.println("hash map contains node2? " + (nodeMap.containsValue(node2) ? "true" : "false"));
}
protected class Node {
private String data;
private Integer count;
public Node(String data, Integer count) {
this.data = data;
this.count = count;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((data == null) ? 0 : data.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Node other = (Node) obj;
if (data == null) {
if (other.data != null)
return false;
}
else
if (!data.equals(other.data))
return false;
return true;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
}
}
它输出:
node1 hash: 95356390
node2 hash: 95356391
node1 hash == node2 hash? false
node1.equals(node2)? false
added node1 to hash map
hash map size: 1
hash map entry set size: 1
hash map contains node1? true
hash map contains node2? false
added node2 to hash map
hash map size: 1
hash map entry set size: 1
hash map contains node1? false
hash map contains node2? true
顺便说一句,你可以简化你的'hashCode'方法来'返回数据!= null? data.hashCode():0;'不需要添加1,然后乘以31. –