public static void main(String[] args) {
Country c1=new Country();
c1.setAddr(1);
c1.setIdCard("123");
Country c2=new Country();
c2.setAddr(1);
c2.setIdCard("234");
System.out.println(c1.equals(c2));
Map map=new HashMap();
Object obj=map.put(c1, 56);
System.out.println(obj);
obj=map.put(c2, 56);
System.out.println(obj);
Map map2=new HashMap();
Object obj2=map2.put(c1, 56);
obj2=map2.put(c2, 56);
System.out.println(map.equals(map2));
}
这段代码的本意是想验证下重写hashcode是否会对比较时产生影响
其结果,没有重写equals方法,object的equals如下
public boolean equals(Object obj) {
return (this == obj);
}
当然我重写hashcode是改变不了内存地址的
然后看是否对HashMap的put操作是否有影响(忘记说了,这里我重写country是hashcode方法使其返回固定的值)
其结果也没影响
public V put(K key, V value) {
if (key == null)
return putForNullKey(value);
int hash = hash(key);
int i = indexFor(hash, table.length);
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
addEntry(hash, key, value, i);
return null;
}
原因就在红色标注了。
最后就是abstractMap重写equals方法的比较规则
object.equals->类型是否为map->集合大小一致->集合中对应映射的值是否相等,key是否相等
除object.equals的结果为false继续比较后面条件外,后续操作为false直接返回map的equals比较结果为false。
最后只重写hashcode方法到底影响在哪方面呢,有没有哪位大师能解答下,谢谢。