答案:不對
我們先看到Objec類中hashCode()方法源碼
/* @ return a hash code value for this object.
* @see java.lang.Object#equals(java.lang.Object)
* @see java.lang.System#identityHashCode
*/
public native int hashCode();
該方法是個native方法,因爲native方法是由非Java語言實現的,所以這個方法的定義中也沒有具體的實現。根據jdk文檔,該方法的實現一般是“
通過將該對象的內部地址轉換成一個整數來實現的
”,這個返回值就作爲該對象的哈希碼值返回。
再看equals源碼,尤其要注意return的說明
/* @param obj the reference object with which to compare.
* @return {@code true} if this object is the same as the obj
* argument; {@code false} otherwise.
* @see #hashCode()
* @see java.util.HashMap
*/
public boolean equals(Object obj) {
return (this == obj);
}
hashCode值是從hash表中得來的,hash是一個函數,該函數的實現是一種算法,通過hash算法算出hash值,hash表就是hash值組成的,一共有8個位置。因此,hashCode相同的兩個對象不一定equals()也爲true。
舉個栗子:
public static void main(String[] args) {
String s1 = "通話";
String s2 = "重地";
System.out.println(s1.hashCode()+" "+s2.hashCode());
System.out.println(s1.equals(s2));
}
Console:
1179395 1179395
false
拓展:
兩個對象值相同(x.equals(y) == true),Hashcode是否一定相同?
分兩種情況:
- 該類未重寫了equals() 方法
(x.equals(y) == true),Hashcod() 一定相同
- 重寫了equals方法,沒有重寫hashCode的方法
(x.equals(y) == true),Hashcod() 不一定相同
再舉個栗子說明
先定義個Person類 ,重寫equals方法
static class Person{
private String name;
public Person(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return Objects.equals(name, person.name);
}
}
main函數運行
public static void main(String[] args) {
Person person = new Person("通話");
Person person1 = new Person("通話");;
System.out.println(person.hashCode()+" "+person1.hashCode());
System.out.println(person.equals(person1));
}
Console:
411631404 897913732
true
樓主也是菜鳥萌新,不對的地方歡迎大佬評論指正!
參考:
https://blog.csdn.net/meism5/article/details/89166768
https://blog.csdn.net/zouliping123456/article/details/82692127