HashMap
public boolean equals(Object o) {
if (o == this)
return true; //如果句柄地址一致,肯定相等
if (!(o instanceof Map))
return false; //如果不是Map对象肯定falsh
Map<K,V> m = (Map<K,V>) o;
if (m.size() != size())
return false; //如果长度不一致,肯定falsh
//如果键值对不一致,falsh
try {
Iterator<Entry<K,V>> i = entrySet().iterator();
while (i.hasNext()) {
Entry<K,V> e = i.next();
K key = e.getKey();
V value = e.getValue();
if (value == null) {
if (!(m.get(key)==null && m.containsKey(key)))
return false;
} else {
if (!value.equals(m.get(key)))
return false;
}
}
} catch (ClassCastException unused) {
return false;
} catch (NullPointerException unused) {
return false;
}
return true;
}
HashTable
public synchronized boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Map))
return false;
Map<K,V> t = (Map<K,V>) o;
if (t.size() != size())
return false;
try {
Iterator<Map.Entry<K,V>> i = entrySet().iterator();
while (i.hasNext()) {
Map.Entry<K,V> e = i.next();
K key = e.getKey();
V value = e.getValue();
if (value == null) {
if (!(t.get(key)==null && t.containsKey(key)))
return false;
} else {
if (!value.equals(t.get(key)))
return false;
}
}
} catch (ClassCastException unused) {
return false;
} catch (NullPointerException unused) {
return false;
}
return true;
}
可以看出两者的实现原理都是一样的!
都是先比较对象的句柄地址,如果一样就直接true,再比较是不是Map对象,是不是长度一致,是不是键值对一致。