最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

java中為何重寫(xiě)equals時(shí)必須重寫(xiě)hashCode方法詳解

 更新時(shí)間:2018年11月13日 08:33:58   作者:blueskyli  
這篇文章主要給大家介紹了關(guān)于java中為什么重寫(xiě)equals時(shí)必須重寫(xiě)hashCode方法的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

前言

大家都知道,equals和hashcode是java.lang.Object類(lèi)的兩個(gè)重要的方法,在實(shí)際應(yīng)用中常常需要重寫(xiě)這兩個(gè)方法,但至于為什么重寫(xiě)這兩個(gè)方法很多人都搞不明白。

在上一篇博文Java中equals和==的區(qū)別中介紹了Object類(lèi)的equals方法,并且也介紹了我們可在重寫(xiě)equals方法,本章我們來(lái)說(shuō)一下為什么重寫(xiě)equals方法的時(shí)候也要重寫(xiě)hashCode方法。

 先讓我們來(lái)看看Object類(lèi)源碼

/**
 * 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&trade; 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();
/**
 * 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:是一個(gè)native方法,返回的是對(duì)象的內(nèi)存地址,

equals:對(duì)于基本數(shù)據(jù)類(lèi)型,==比較的是兩個(gè)變量的值。對(duì)于引用對(duì)象,==比較的是兩個(gè)對(duì)象的地址。

接下來(lái)我們看下hashCode的注釋

1.在 Java 應(yīng)用程序執(zhí)行期間,在對(duì)同一對(duì)象多次調(diào)用 hashCode 方法時(shí),必須一致地返回相同的整數(shù),前提是將對(duì)象進(jìn)行 equals 比較時(shí)所用的信息沒(méi)有被修改。
 從某一應(yīng)用程序的一次執(zhí)行到同一應(yīng)用程序的另一次執(zhí)行,該整數(shù)無(wú)需保持一致。
2.如果根據(jù) equals(Object) 方法,兩個(gè)對(duì)象是相等的,那么對(duì)這兩個(gè)對(duì)象中的每個(gè)對(duì)象調(diào)用 hashCode 方法都必須生成相同的整數(shù)結(jié)果。
3.如果根據(jù) equals(java.lang.Object) 方法,兩個(gè)對(duì)象不相等,那么兩個(gè)對(duì)象不一定必須產(chǎn)生不同的整數(shù)結(jié)果。
 但是,程序員應(yīng)該意識(shí)到,為不相等的對(duì)象生成不同整數(shù)結(jié)果可以提高哈希表的性能。

從hashCode的注釋中我們看到,hashCode方法在定義時(shí)做出了一些常規(guī)協(xié)定,即

1,當(dāng)obj1.equals(obj2) 為 true 時(shí),obj1.hashCode() == obj2.hashCode()

2,當(dāng)obj1.equals(obj2) 為 false 時(shí),obj1.hashCode() != obj2.hashCode()

hashcode是用于散列數(shù)據(jù)的快速存取,如利用HashSet/HashMap/Hashtable類(lèi)來(lái)存儲(chǔ)數(shù)據(jù)時(shí),都是根據(jù)存儲(chǔ)對(duì)象的hashcode值來(lái)進(jìn)行判斷是否相同的。如果我們將對(duì)象的equals方法重寫(xiě)而不重寫(xiě)hashcode,當(dāng)我們?cè)俅蝞ew一個(gè)新的對(duì)象的時(shí)候,equals方法返回的是true,但是hashCode方法返回的就不一樣了,如果需要將這些對(duì)象存儲(chǔ)到結(jié)合中(比如:Set,Map ...)的時(shí)候就違背了原有集合的原則,下面讓我們通過(guò)一段代碼看下。

/**
 * @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方法的都不重寫(xiě)

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;
 }
}
p的hashCode:356573597
p1的hashCode:1735600054
false
false
com.blueskyli.練習(xí).Person@677327b6
com.blueskyli.練習(xí).Person@1540e19d

只重寫(xiě)equals方法

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);
 }
}
p的hashCode:356573597
p1的hashCode:1735600054
true
false
com.blueskyli.練習(xí).Person@677327b6
com.blueskyli.練習(xí).Person@1540e19d

equals和hashCode方法都重寫(xiě)

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();
 }
}
p的hashCode:3254239
p1的hashCode:3254239
true
false
com.blueskyli.練習(xí).Person@31a7df

我們知道m(xù)ap是不允許存在相同的key的,由上面的代碼可以知道,如果不重寫(xiě)equals和hashCode方法的話會(huì)使得你在使用map的時(shí)候出現(xiàn)與預(yù)期不一樣的結(jié)果,具體equals和hashCode如何重寫(xiě),里面的邏輯如何實(shí)現(xiàn)需要根據(jù)現(xiàn)實(shí)當(dāng)中的業(yè)務(wù)來(lái)規(guī)定。

總結(jié):

1,兩個(gè)對(duì)象,用==比較比較的是地址,需采用equals方法(可根據(jù)需求重寫(xiě))比較。

2,重寫(xiě)equals()方法就重寫(xiě)hashCode()方法。

3,一般相等的對(duì)象都規(guī)定有相同的hashCode。

4,String類(lèi)重寫(xiě)了equals和hashCode方法,比較的是值。

5,重寫(xiě)hashcode方法為了將數(shù)據(jù)存入HashSet/HashMap/Hashtable(可以參考源碼有助于理解)類(lèi)時(shí)進(jìn)行比較

好了,以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問(wèn)大家可以留言交流,謝謝大家對(duì)腳本之家的支持。

相關(guān)文章

  • 一文掌握Spring?中?@Component?和?@Bean?區(qū)別(最新推薦)

    一文掌握Spring?中?@Component?和?@Bean?區(qū)別(最新推薦)

    ?@Component?用于標(biāo)識(shí)一個(gè)普通的類(lèi),@Bean用于配置類(lèi)里面,在方法上面聲明和配置?Bean?對(duì)象,這篇文章主要介紹了Spring?中?@Component?和?@Bean?區(qū)別(最新推薦),需要的朋友可以參考下
    2024-04-04
  • Spark?實(shí)現(xiàn)自定義加密的示例代碼

    Spark?實(shí)現(xiàn)自定義加密的示例代碼

    這篇文章主要介紹了Spark?實(shí)現(xiàn)自定義加密的示例代碼,代碼簡(jiǎn)單易懂,對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧
    2024-07-07
  • SpringCloud之@FeignClient()注解的使用詳解

    SpringCloud之@FeignClient()注解的使用詳解

    @FeignClient是SpringCloud中用于聲明一個(gè)Feign客戶端的注解,用于解決模塊方法互相調(diào)用的問(wèn)題,Feign是一個(gè)聲明式的WebService客戶端,通過(guò)Feign,只需要?jiǎng)?chuàng)建一個(gè)接口,并使用注解來(lái)描述請(qǐng)求,就可以直接執(zhí)行HTTP請(qǐng)求了
    2024-11-11
  • Spring擴(kuò)展點(diǎn)之BeanFactoryPostProcessor詳解

    Spring擴(kuò)展點(diǎn)之BeanFactoryPostProcessor詳解

    這篇文章主要介紹了Spring擴(kuò)展點(diǎn)之BeanFactoryPostProcessor詳解,Spring的設(shè)計(jì)非常優(yōu)雅,有很多的擴(kuò)展點(diǎn)供我們對(duì)項(xiàng)目進(jìn)行擴(kuò)展,今天學(xué)習(xí)一下Spring其中擴(kuò)展點(diǎn)之一的BeanFactoryPostProcessor,需要的朋友可以參考下
    2023-11-11
  • Servlet實(shí)現(xiàn)統(tǒng)計(jì)頁(yè)面訪問(wèn)次數(shù)功能

    Servlet實(shí)現(xiàn)統(tǒng)計(jì)頁(yè)面訪問(wèn)次數(shù)功能

    這篇文章主要介紹了Servlet實(shí)現(xiàn)統(tǒng)計(jì)頁(yè)面訪問(wèn)次數(shù)功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-04-04
  • 使用Java判定一個(gè)數(shù)值是否在指定的開(kāi)閉區(qū)間范圍內(nèi)

    使用Java判定一個(gè)數(shù)值是否在指定的開(kāi)閉區(qū)間范圍內(nèi)

    這篇文章主要給大家介紹了關(guān)于使用Java判定一個(gè)數(shù)值是否在指定的開(kāi)閉區(qū)間范圍內(nèi)的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用Java具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2022-09-09
  • Java基礎(chǔ)之String類(lèi)使用與字符串比較

    Java基礎(chǔ)之String類(lèi)使用與字符串比較

    String類(lèi)代表字符串,java程序中的所有字符串文字(例如"abc")都被實(shí)現(xiàn)為此類(lèi)的實(shí)例。本文將詳解String類(lèi)的使用,以及如何進(jìn)行字符串比較
    2022-08-08
  • 詳解Jmeter中的BeanShell腳本

    詳解Jmeter中的BeanShell腳本

    BeanShell是一種完全符合Java語(yǔ)法規(guī)范的腳本語(yǔ)言,并且又擁有自己的一些語(yǔ)法和方法,所以它和java是可以無(wú)縫銜接的,學(xué)了Java的一些基本語(yǔ)法后,就可以來(lái)在Jmeter中寫(xiě)寫(xiě)B(tài)eanShell腳本了
    2021-12-12
  • RabbitMQ 最常用的三大模式實(shí)例解析

    RabbitMQ 最常用的三大模式實(shí)例解析

    這篇文章主要介紹了RabbitMQ 最常用的三大模式實(shí)例解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-12-12
  • SpringBoot中的yaml語(yǔ)法及靜態(tài)資源訪問(wèn)問(wèn)題

    SpringBoot中的yaml語(yǔ)法及靜態(tài)資源訪問(wèn)問(wèn)題

    這篇文章主要介紹了SpringBoot中的yaml語(yǔ)法及靜態(tài)資源訪問(wèn)問(wèn)題,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-07-07

最新評(píng)論

肇庆市| 武义县| 宁南县| 南京市| 铜鼓县| 莱州市| 阜宁县| 蓝山县| 巨鹿县| 岱山县| 涿鹿县| 永济市| 且末县| 阿克苏市| 额敏县| 三台县| 射洪县| 宁津县| 罗定市| 资源县| 公安县| 诸城市| 阿克陶县| 阿拉尔市| 南安市| 岗巴县| 台前县| 辽源市| 若尔盖县| 沙河市| 延安市| 中山市| 肥西县| 永福县| 湟中县| 古蔺县| 屏东市| 海安县| 丰宁| 霍州市| 阜阳市|