网上都说:equals()相等的两个对象他们的 hashCode()肯定相等,这句话真的对吗?
先看下面代码:
class MyClass {
private int score = 1;
private int age = 2;
public MyClass(int score1, int age1) {
this.score = score1;
this.age = age1;
}
@Override
public boolean equals(Object obj) {
return true; //
// if (!(obj instanceof MyClass)) {
// return false;
// }
// return this.age + this.score == ((MyClass) obj).score + ((MyClass) obj).age;
}
@Override
public int hashCode() {
return this.age;
}
}
只要是重写,那么equals()和hashCode() ,怎么返回都由开发者你控制,你想怎么返回就返回,想不符合这条规则也可以!
如上面例子,equals()直接返回true,所有对象equals()都是true,但是hashCode不相等的。
其实,都说“equals()相等的两个对象他们的 hashCode()肯定相等”,也对,这只是一种代码规范!hashCode的最主要作用就是在HashMap、HashTable三列存储结构使用:
我们再看看HashMap的set和get方法:
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
/**
* Implements Map.put and related methods
*
* @param hash hash for key
* @param key the key
* @param value the value to put
* @param onlyIfAbsent if true, don't change existing value
* @param evict if false, the table is in creation mode.
* @return previous value, or null if none
*/
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
/**
* Implements Map.get and related methods
*
* @param hash hash for key
* @param key the key
* @return the node, or null if none
*/
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
hashMap中的hash,是通过key的hashCode移位取余得到的,所以会出现hash冲突。
存和取值的时候,先通过hash去确定存储位置,然后再通过equeals判断key是否相等,而后存取value;所以我们才默认、也要求我们重写时必须符合“equals()相等的两个对象他们的 hashCode()肯定相等”规范!
输出不然,像MyClass中不符合规范的equals,会导致数据存储混乱,测试下:
public static void main(String[] args) {
MyClass mC0 = new MyClass(0, 2);
MyClass mC1 = new MyClass(1, 2);
MyClass mC2 = new MyClass(2, 2);
MyClass mC3 = new MyClass(3, 2);
HashMap<MyClass, String> testHashMap = new HashMap<>(2);
testHashMap.put(mC0, "--0");
testHashMap.put(mC1, "--1");
testHashMap.put(mC2, "--2");
testHashMap.put(mC3, "--3");
System.out.println("mC0 value:" + testHashMap.get(mC0) + ";mC1 value:" + testHashMap.get(mC1)
+ ";mC2 value:" + testHashMap.get(mC2));
//输出结果: mC0 value:--3;mC1 value:--3;mC2 value:--3
}
会导致在存值的时候遇到 (key != null && key.equals(k))直接就存了,mC3覆盖了所有的testHashMap.put()。
再补一下官方例子,String的equals()和hashCode():
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = length();
if (n == anotherString.length()) {
int i = 0;
while (n-- != 0) {
if (charAt(i) != anotherString.charAt(i))
return false;
i++;
}
return true;
}
}
return false;
}
public int hashCode() {
int h = hash;
final int len = length();
if (h == 0 && len > 0) {
for (int i = 0; i < len; i++) {
//使用质数31,就是尽可能避免不同内容的对象生成相同的数字
h = 31 * h + charAt(i);
}
hash = h;
}
return h;
}
所以“equals()相等的两个对象他们的 hashCode()肯定相等”,它是一种代码规范!
尽管不是“正确”,但是我们开发的时候要遵守!