一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|JavaScript|易語言|

服務器之家 - 編程語言 - Java教程 - java中為何重寫equals時必須重寫hashCode方法詳解

java中為何重寫equals時必須重寫hashCode方法詳解

2021-06-11 13:58blueskyli Java教程

這篇文章主要給大家介紹了關于java中為什么重寫equals時必須重寫hashCode方法的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

前言

大家都知道,equals和hashcode是java.lang.object類的兩個重要的方法,在實際應用中常常需要重寫這兩個方法,但至于為什么重寫這兩個方法很多人都搞不明白。

在上一篇博文java中equals和==的區別中介紹了object類的equals方法,并且也介紹了我們可在重寫equals方法,本章我們來說一下為什么重寫equals方法的時候也要重寫hashcode方法。

 先讓我們來看看object類源碼

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
 * 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}.
 * <p>
 * the general contract of {@code hashcode} is:
 * <ul>
 * <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.
 * this integer need not remain consistent from one execution of an
 * application to another execution of the same application.
 * <li>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.
 * </ul>
 * <p>
 * as much as is reasonably practical, the hashcode method defined by
 * class {@code object} does return distinct integers for distinct
 * objects. (this is typically implemented by converting the internal
 * address of the object into an integer, but this implementation
 * technique is not required by the
 * java™ programming language.)
 *
 * @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();
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/**
 * indicates whether some other object is "equal to" this one.
 * <p>
 * the {@code equals} method implements an equivalence relation
 * on non-null object references:
 * <ul>
 * <li>it is <i>reflexive</i>: for any non-null reference value
 * {@code x}, {@code x.equals(x)} should return
 * {@code true}.
 * <li>it is <i>symmetric</i>: for any non-null reference values
 * {@code x} and {@code y}, {@code x.equals(y)}
 * should return {@code true} if and only if
 * {@code y.equals(x)} returns {@code true}.
 * <li>it is <i>transitive</i>: for any non-null reference values
 * {@code x}, {@code y}, and {@code z}, if
 * {@code x.equals(y)} returns {@code true} and
 * {@code y.equals(z)} returns {@code true}, then
 * {@code x.equals(z)} should return {@code true}.
 * <li>it is <i>consistent</i>: for any non-null reference values
 * {@code x} and {@code y}, multiple invocations of
 * {@code x.equals(y)} consistently return {@code true}
 * or consistently return {@code false}, provided no
 * information used in {@code equals} comparisons on the
 * objects is modified.
 * <li>for any non-null reference value {@code x},
 * {@code x.equals(null)} should return {@code false}.
 * </ul>
 * <p>
 * the {@code equals} method for class {@code object} implements
 * the most discriminating possible equivalence relation on objects;
 * that is, for any non-null reference values {@code x} and
 * {@code y}, this method returns {@code true} if and only
 * if {@code x} and {@code y} refer to the same object
 * ({@code x == y} has the value {@code true}).
 * <p>
 * note that it is generally necessary to override the {@code hashcode}
 * method whenever this method is overridden, so as to maintain the
 * general contract for the {@code hashcode} method, which states
 * that equal objects must have equal hash codes.
 *
 * @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:是一個native方法,返回的是對象的內存地址,

equals:對于基本數據類型,==比較的是兩個變量的值。對于引用對象,==比較的是兩個對象的地址。

接下來我們看下hashcode的注釋

1.在 java 應用程序執行期間,在對同一對象多次調用 hashcode 方法時,必須一致地返回相同的整數,前提是將對象進行 equals 比較時所用的信息沒有被修改。
 從某一應用程序的一次執行到同一應用程序的另一次執行,該整數無需保持一致。
2.如果根據 equals(object) 方法,兩個對象是相等的,那么對這兩個對象中的每個對象調用 hashcode 方法都必須生成相同的整數結果。
3.如果根據 equals(java.lang.object) 方法,兩個對象不相等,那么兩個對象不一定必須產生不同的整數結果。
 但是,程序員應該意識到,為不相等的對象生成不同整數結果可以提高哈希表的性能。

從hashcode的注釋中我們看到,hashcode方法在定義時做出了一些常規協定,即

1,當obj1.equals(obj2) 為 true 時,obj1.hashcode() == obj2.hashcode()

2,當obj1.equals(obj2) 為 false 時,obj1.hashcode() != obj2.hashcode()

hashcode是用于散列數據的快速存取,如利用hashset/hashmap/hashtable類來存儲數據時,都是根據存儲對象的hashcode值來進行判斷是否相同的。如果我們將對象的equals方法重寫而不重寫hashcode,當我們再次new一個新的對象的時候,equals方法返回的是true,但是hashcode方法返回的就不一樣了,如果需要將這些對象存儲到結合中(比如:set,map ...)的時候就違背了原有集合的原則,下面讓我們通過一段代碼看下。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
 * @see person
 * @param args
 */
 public static void main(string[] args)
 {
 hashmap<person, integer> map = new hashmap<person, integer>();
 
 person p = new person("jack",22,"男");
 person p1 = new person("jack",22,"男");
 
 system.out.println("p的hashcode:"+p.hashcode());
 system.out.println("p1的hashcode:"+p1.hashcode());
 system.out.println(p.equals(p1));
 system.out.println(p == p1);
 
 map.put(p,888);
 map.put(p1,888);
 map.foreach((key,val)->{
  system.out.println(key);
  system.out.println(val);
 });
 }

equals和hashcode方法的都不重寫

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class person
{
 private string name;
 
 private int age;
 
 private string sex;
 
 person(string name,int age,string sex){
 this.name = name;
 this.age = age;
 this.sex = sex;
 }
}
?
1
2
3
4
5
6
p的hashcode:356573597
p1的hashcode:1735600054
false
false
com.blueskyli.練習.person@677327b6
com.blueskyli.練習.person@1540e19d

只重寫equals方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class person
{
 private string name;
 
 private int age;
 
 private string sex;
 
 person(string name,int age,string sex){
 this.name = name;
 this.age = age;
 this.sex = sex;
 }
 
 @override public boolean equals(object obj)
 {
 if(obj instanceof person){
  person person = (person)obj;
  return name.equals(person.name);
 }
 return super.equals(obj);
 }
}
?
1
2
3
4
5
6
p的hashcode:356573597
p1的hashcode:1735600054
true
false
com.blueskyli.練習.person@677327b6
com.blueskyli.練習.person@1540e19d

equals和hashcode方法都重寫

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class person
{
 private string name;
 
 private int age;
 
 private string sex;
 
 person(string name,int age,string sex){
 this.name = name;
 this.age = age;
 this.sex = sex;
 }
 
 @override public boolean equals(object obj)
 {
 if(obj instanceof person){
  person person = (person)obj;
  return name.equals(person.name);
 }
 return super.equals(obj);
 }
 
 @override public int hashcode()
 {
 return name.hashcode();
 }
}
?
1
2
3
4
5
p的hashcode:3254239
p1的hashcode:3254239
true
false
com.blueskyli.練習.person@31a7df

我們知道map是不允許存在相同的key的,由上面的代碼可以知道,如果不重寫equals和hashcode方法的話會使得你在使用map的時候出現與預期不一樣的結果,具體equals和hashcode如何重寫,里面的邏輯如何實現需要根據現實當中的業務來規定。

總結:

1,兩個對象,用==比較比較的是地址,需采用equals方法(可根據需求重寫)比較。

2,重寫equals()方法就重寫hashcode()方法。

3,一般相等的對象都規定有相同的hashcode。

4,string類重寫了equals和hashcode方法,比較的是值。

5,重寫hashcode方法為了將數據存入hashset/hashmap/hashtable(可以參考源碼有助于理解)類時進行比較

好了,以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對服務器之家的支持。

原文鏈接:https://www.cnblogs.com/blueskyli/p/9936076.html

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 欧美福利二区 | 大香线一本 | 成人国产一区二区 | 美女的让男人桶爽免费看 | youyjzzcom最新欧美| 香蕉eeww99国产精选播放 | jk制服白丝超短裙流白浆 | 男人肌肌捅女人肌肌 | 亚洲成人贴图 | 亚洲网站在线看 | 欧美亚洲国产另类在线观看 | 闺蜜的样子小说安沁在线阅读 | 欧美一区二区三 | 高清麻生希在线 | 亚洲黄色大片 | 504神宫寺奈绪大战黑人 | 18young第一次| 久久久免费热线精品频 | 丝袜兔女郎被啪在线观看91 | 国产欧美日韩亚洲精品区2345 | 韩国帅男同gay网站 韩国三级在线播放 | 女子监狱第二季未删减在线看 | 九九九九在线视频播放 | 久久精品视频在线看 | 99r视频在线观看 | 国产欧美一区二区三区免费 | 精品国偷自产在线 | 亚洲精品久久玖玖玖玖 | 亚洲国产综合另类视频 | 嫩草精品 | 99视频久久精品久久 | 亚洲AV综合99一二三四区 | 99精品国产成人一区二区在线 | 美女脱得一二净无内裤全身的照片 | 美女张开腿让男人桶的 视频 | 免费国产高清精品一区在线 | 男人综合网 | 久草色视频 | 99亚洲自拍 | 青草午夜精品视频在线观看 | 男同gay作爰视频网站 |