hashCode equals ==

equals  vs  ==

当 equals 没重写时 equals 就是 == 比较两个对象 是否指向同一内存地址

public boolean equals(Object obj) {
  return (this == obj);

}

equals  vs  hashCode

hashCode

/**
* Returns a hash code value for the object. This method is
* supported for the benefit of hash tables such as those provided by
* {@link java.util.HashMap}.
// hash tables : Hashtable  HashSet  HashMap

* As much as is reasonably practical, the hashCode method defined
* by class {@code Object} does return distinct integers for
* distinct objects. (The hashCode may or may not be implemented
* as some function of an object's memory address at some point
* in time.)
// 没重写  返回的是 对象某一时刻内存地址hash后的一个code (某一时刻 比如GC 时 使用标记-复制算法时 某些对象的内存地址会变化 对应着 hashCode也会变)

<li>Whenever it is invoked on the same object more than once during
* an execution of a Java application, the {@code hashCode} method
* must consistently return the same integer, provided no information
* used in {@code equals} comparisons on the object is modified.

* If two objects are equal according to the {@code equals(Object)}
* method, then calling the {@code hashCode} method on each of
* the two objects must produce the same integer result.

* <li>It is <em>not</em> required that if two objects are unequal
* according to the {@link java.lang.Object#equals(java.lang.Object)}
* method, then calling the {@code hashCode} method on each of the
* two objects must produce distinct integer results. However, the
* programmer should be aware that producing distinct integer results
* for unequal objects may improve the performance of hash tables.

hashCode  &  HashMap

参考:https://blog.csdn.net/qq_38182963/article/details/78940047

源码:

public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}

static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
// ^:异或 >>>:无符号右移 为啥要这样搞 后面研究下

 

猜你喜欢

转载自www.cnblogs.com/light-train-union/p/12918537.html