亚洲香蕉成人av网站在线观看_欧美精品成人91久久久久久久_久久久久久久久久久亚洲_热久久视久久精品18亚洲精品_国产精自产拍久久久久久_亚洲色图国产精品_91精品国产网站_中文字幕欧美日韩精品_国产精品久久久久久亚洲调教_国产精品久久一区_性夜试看影院91社区_97在线观看视频国产_68精品久久久久久欧美_欧美精品在线观看_国产精品一区二区久久精品_欧美老女人bb

首頁 > 編程 > Java > 正文

關于Java覆蓋equals方法時必須覆蓋hashCode方法

2019-11-06 06:40:23
字體:
來源:轉載
供稿:網友

java中的對象自動繼承Object類,而Object類實現了equals方法和hashCode方法:

    /**     * Returns a hash code value for the object. This method is      * supported for the benefit of hashtables such as those PRovided by      * <code>java.util.Hashtable</code>.      * <p>     * The general contract of <code>hashCode</code> is:      * <ul>     * <li>Whenever it is invoked on the same object more than once during      *     an execution of a Java application, the <tt>hashCode</tt> method      *     must consistently return the same integer, provided no information      *     used in <tt>equals</tt> 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 <tt>equals(Object)</tt>     *     method, then calling the <code>hashCode</code> 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 <tt>hashCode</tt> 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 hashtables.     * </ul>     * <p>     * As much as is reasonably practical, the hashCode method defined by      * class <tt>Object</tt> 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<font size="-2"><sup>TM</sup></font> programming language.)     *     * @return  a hash code value for this object.     * @see     java.lang.Object#equals(java.lang.Object)     * @see     java.util.Hashtable     */    public native int hashCode();    /**     * Indicates whether some other object is "equal to" this one.     * <p>     * The <code>equals</code> 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>, <code>x.equals(x)</code> should return     *     <code>true</code>.     * <li>It is <i>symmetric</i>: for any non-null reference values     *     <code>x</code> and <code>y</code>, <code>x.equals(y)</code>     *     should return <code>true</code> if and only if     *     <code>y.equals(x)</code> returns <code>true</code>.     * <li>It is <i>transitive</i>: for any non-null reference values     *     <code>x</code>, <code>y</code>, and <code>z</code>, if     *     <code>x.equals(y)</code> returns <code>true</code> and     *     <code>y.equals(z)</code> returns <code>true</code>, then     *     <code>x.equals(z)</code> should return <code>true</code>.     * <li>It is <i>consistent</i>: for any non-null reference values     *     <code>x</code> and <code>y</code>, multiple invocations of     *     <tt>x.equals(y)</tt> consistently return <code>true</code>     *     or consistently return <code>false</code>, provided no     *     information used in <code>equals</code> comparisons on the     *     objects is modified.     * <li>For any non-null reference value <code>x</code>,     *     <code>x.equals(null)</code> should return <code>false</code>.     * </ul>     * <p>     * The <tt>equals</tt> method for class <code>Object</code> implements      * the most discriminating possible equivalence relation on objects;      * that is, for any non-null reference values <code>x</code> and     * <code>y</code>, this method returns <code>true</code> if and only     * if <code>x</code> and <code>y</code> refer to the same object     * (<code>x == y</code> has the value <code>true</code>).     * <p>     * Note that it is generally necessary to override the <tt>hashCode</tt>     * method whenever this method is overridden, so as to maintain the     * general contract for the <tt>hashCode</tt> method, which states     * that equal objects must have equal hash codes.      *     * @param   obj   the reference object with which to compare.     * @return  <code>true</code> if this object is the same as the obj     *          argument; <code>false</code> otherwise.     * @see     #hashCode()     * @see     java.util.Hashtable     */    public boolean equals(Object obj) {	return (this == obj);    }Object類中的hashCode()已自動實現為不同的對象生成不同的hashCode,所以,當我們創建一個新的類時,即使以這個類為基準創建了兩個完全相同的對象(對象中的元素完全相同),這兩個相同對象的hashCode也是不同的:

import java.util.Map;import java.util.Map.Entry;import com.google.common.base.Objects;import com.google.common.collect.Maps;public class Name {    String id;    Name(String id) {        this.id = id;    }    @Override    public boolean equals(Object obj) {        Name otherName = (Name) obj;        return Objects.equal(this.id, otherName.id);    }    @Override    public String toString() {        return this.getClass().getSimpleName() + "@" + this.id + "&" + this.hashCode();    }    public static void main(String[] args) {        Name n1 = new Name("zhao");        Name n2 = new Name("zhao");        System.err.println("n1.equals(n2) = " + n1.equals(n2));        Map<Name, Integer> map = Maps.newHashMap();        map.put(n1, 1);        map.put(n2, 2);        for (Entry<Name, Integer> entry : map.entrySet()) {            System.out.println(entry.getKey() + ":" + entry.getValue());        }        System.err.println(map.get(new Name("zhao")));    }}而Java中的Hash容器會根據Key的hashCode,將不同hashCode對象(即hashCode()不同的對象而非equals()不同的對象)散列到不同的位置,這時候在Hash容器中應用這些對象時會出現錯誤。所以,在覆蓋equals()方法時必須覆蓋hashCode()方法。

    /**     * Associates the specified value with the specified key in this map.     * If the map previously contained a mapping for the key, the old     * value is replaced.     *     * @param key key with which the specified value is to be associated     * @param value value to be associated with the specified key     * @return the previous value associated with <tt>key</tt>, or     *         <tt>null</tt> if there was no mapping for <tt>key</tt>.     *         (A <tt>null</tt> return can also indicate that the map     *         previously associated <tt>null</tt> with <tt>key</tt>.)     */    public V put(K key, V value) {        if (key == null)            return putForNullKey(value);        int hash = hash(key.hashCode());        int i = indexFor(hash, table.length);        for (Entry<K,V> e = table[i]; e != null; e = e.next) {            Object k;            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {                V oldValue = e.value;                e.value = value;                e.recordaccess(this);                return oldValue;            }        }        modCount++;        addEntry(hash, key, value, i);        return null;    }

參考文章:

1、JDK源碼

2、http://www.cnblogs.com/wangliyue/p/4450747.html

3、http://www.cnblogs.com/happyPawpaw/p/3744971.html

Java中的對象自動繼承Object類,而Object類實現了equals方法和hashCode方法:

    /**     * Returns a hash code value for the object. This method is      * supported for the benefit of hashtables such as those provided by      * <code>java.util.Hashtable</code>.      * <p>     * The general contract of <code>hashCode</code> is:      * <ul>     * <li>Whenever it is invoked on the same object more than once during      *     an execution of a Java application, the <tt>hashCode</tt> method      *     must consistently return the same integer, provided no information      *     used in <tt>equals</tt> 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 <tt>equals(Object)</tt>     *     method, then calling the <code>hashCode</code> 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 <tt>hashCode</tt> 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 hashtables.     * </ul>     * <p>     * As much as is reasonably practical, the hashCode method defined by      * class <tt>Object</tt> 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<font size="-2"><sup>TM</sup></font> programming language.)     *     * @return  a hash code value for this object.     * @see     java.lang.Object#equals(java.lang.Object)     * @see     java.util.Hashtable     */    public native int hashCode();    /**     * Indicates whether some other object is "equal to" this one.     * <p>     * The <code>equals</code> 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>, <code>x.equals(x)</code> should return     *     <code>true</code>.     * <li>It is <i>symmetric</i>: for any non-null reference values     *     <code>x</code> and <code>y</code>, <code>x.equals(y)</code>     *     should return <code>true</code> if and only if     *     <code>y.equals(x)</code> returns <code>true</code>.     * <li>It is <i>transitive</i>: for any non-null reference values     *     <code>x</code>, <code>y</code>, and <code>z</code>, if     *     <code>x.equals(y)</code> returns <code>true</code> and     *     <code>y.equals(z)</code> returns <code>true</code>, then     *     <code>x.equals(z)</code> should return <code>true</code>.     * <li>It is <i>consistent</i>: for any non-null reference values     *     <code>x</code> and <code>y</code>, multiple invocations of     *     <tt>x.equals(y)</tt> consistently return <code>true</code>     *     or consistently return <code>false</code>, provided no     *     information used in <code>equals</code> comparisons on the     *     objects is modified.     * <li>For any non-null reference value <code>x</code>,     *     <code>x.equals(null)</code> should return <code>false</code>.     * </ul>     * <p>     * The <tt>equals</tt> method for class <code>Object</code> implements      * the most discriminating possible equivalence relation on objects;      * that is, for any non-null reference values <code>x</code> and     * <code>y</code>, this method returns <code>true</code> if and only     * if <code>x</code> and <code>y</code> refer to the same object     * (<code>x == y</code> has the value <code>true</code>).     * <p>     * Note that it is generally necessary to override the <tt>hashCode</tt>     * method whenever this method is overridden, so as to maintain the     * general contract for the <tt>hashCode</tt> method, which states     * that equal objects must have equal hash codes.      *     * @param   obj   the reference object with which to compare.     * @return  <code>true</code> if this object is the same as the obj     *          argument; <code>false</code> otherwise.     * @see     #hashCode()     * @see     java.util.Hashtable     */    public boolean equals(Object obj) {	return (this == obj);    }Object類中的hashCode()已自動實現為不同的對象生成不同的hashCode,所以,當我們創建一個新的類時,即使以這個類為基準創建了兩個完全相同的對象(對象中的元素完全相同),這兩個相同對象的hashCode也是不同的:

import java.util.Map;import java.util.Map.Entry;import com.google.common.base.Objects;import com.google.common.collect.Maps;public class Name {    String id;    Name(String id) {        this.id = id;    }    @Override    public boolean equals(Object obj) {        Name otherName = (Name) obj;        return Objects.equal(this.id, otherName.id);    }    @Override    public String toString() {        return this.getClass().getSimpleName() + "@" + this.id + "&" + this.hashCode();    }    public static void main(String[] args) {        Name n1 = new Name("zhao");        Name n2 = new Name("zhao");        System.err.println("n1.equals(n2) = " + n1.equals(n2));        Map<Name, Integer> map = Maps.newHashMap();        map.put(n1, 1);        map.put(n2, 2);        for (Entry<Name, Integer> entry : map.entrySet()) {            System.out.println(entry.getKey() + ":" + entry.getValue());        }        System.err.println(map.get(new Name("zhao")));    }}而Java中的Hash容器會根據Key的hashCode,將不同hashCode對象(即hashCode()不同的對象而非equals()不同的對象)散列到不同的位置,這時候在Hash容器中應用這些對象時會出現錯誤。所以,在覆蓋equals()方法時必須覆蓋hashCode()方法。

    /**     * Associates the specified value with the specified key in this map.     * If the map previously contained a mapping for the key, the old     * value is replaced.     *     * @param key key with which the specified value is to be associated     * @param value value to be associated with the specified key     * @return the previous value associated with <tt>key</tt>, or     *         <tt>null</tt> if there was no mapping for <tt>key</tt>.     *         (A <tt>null</tt> return can also indicate that the map     *         previously associated <tt>null</tt> with <tt>key</tt>.)     */    public V put(K key, V value) {        if (key == null)            return putForNullKey(value);        int hash = hash(key.hashCode());        int i = indexFor(hash, table.length);        for (Entry<K,V> e = table[i]; e != null; e = e.next) {            Object k;            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {                V oldValue = e.value;                e.value = value;                e.recordAccess(this);                return oldValue;            }        }        modCount++;        addEntry(hash, key, value, i);        return null;    }

參考文章:

1、JDK源碼

2、http://www.cnblogs.com/wangliyue/p/4450747.html

3、http://www.cnblogs.com/happyPawpaw/p/3744971.html


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
亚洲香蕉成人av网站在线观看_欧美精品成人91久久久久久久_久久久久久久久久久亚洲_热久久视久久精品18亚洲精品_国产精自产拍久久久久久_亚洲色图国产精品_91精品国产网站_中文字幕欧美日韩精品_国产精品久久久久久亚洲调教_国产精品久久一区_性夜试看影院91社区_97在线观看视频国产_68精品久久久久久欧美_欧美精品在线观看_国产精品一区二区久久精品_欧美老女人bb
欧美最猛性xxxxx亚洲精品| 亚洲欧美日韩久久久久久| 日韩大片在线观看视频| 91精品国产91| 日本亚洲精品在线观看| 日本亚洲精品在线观看| 亚洲国产精品成人一区二区| 国产69久久精品成人看| 中文字幕日韩av| 韩国三级电影久久久久久| 欧美精品一区在线播放| 国产精品99久久久久久久久久久久| 在线观看成人黄色| 亚洲国产精品久久久久秋霞蜜臀| 久久精品国产99国产精品澳门| 亚洲精品国产拍免费91在线| 国产成人综合精品| 国产一区二区在线免费视频| 日韩视频在线一区| 亚洲天堂免费观看| 久久99久国产精品黄毛片入口| 欧美亚洲视频在线看网址| 成人欧美一区二区三区黑人| 色樱桃影院亚洲精品影院| 国产第一区电影| 久久色在线播放| 最好看的2019年中文视频| 成人写真福利网| 日韩在线中文字幕| 国产精品88a∨| 精品自在线视频| 国产精品wwwwww| 在线观看亚洲视频| 91情侣偷在线精品国产| 麻豆国产va免费精品高清在线| 最好看的2019年中文视频| 久久视频免费观看| 91精品国产777在线观看| 国产高清视频一区三区| 97超级碰在线看视频免费在线看| 欧美成人精品在线视频| 亚洲成人网在线| 久久成人精品一区二区三区| 日韩欧美高清视频| 日韩av影院在线观看| 一本一本久久a久久精品综合小说| 欧美精品在线观看| 国a精品视频大全| 国产精品视频最多的网站| 亚洲欧美激情精品一区二区| 国产精品入口夜色视频大尺度| 在线亚洲午夜片av大片| 国产成人午夜视频网址| 日韩在线观看电影| 日本国产欧美一区二区三区| 日本成人免费在线| 午夜精品一区二区三区在线视频| 日韩国产在线看| 精品国偷自产在线视频99| 欧美—级a级欧美特级ar全黄| 欧美亚洲另类制服自拍| 6080yy精品一区二区三区| 国产精品对白刺激| 国产精品一区二区3区| 精品国产一区二区三区久久| 97在线视频免费播放| 另类专区欧美制服同性| 欧美最猛黑人xxxx黑人猛叫黄| 91丨九色丨国产在线| 日韩在线高清视频| 亚洲精品网站在线播放gif| 久久久久久久久国产精品| 欧美激情欧美狂野欧美精品| 亚洲精品www久久久久久广东| 欧美成人免费小视频| 最近2019中文免费高清视频观看www99| 日韩在线观看视频免费| 国产精品成人国产乱一区| 欧美xxxx18性欧美| 97超碰色婷婷| 欧美成人性色生活仑片| 激情成人中文字幕| 日韩一区二区久久久| 欧洲亚洲女同hd| 欧美在线亚洲在线| 久久精品精品电影网| 欧美高清理论片| 91久久久久久久久久| 亚洲日本aⅴ片在线观看香蕉| 国产亚洲一区二区精品| 成人精品视频99在线观看免费| 欧美亚州一区二区三区| 国产精品福利无圣光在线一区| 97热精品视频官网| 亚洲小视频在线| 欧美日韩xxxxx| 日韩中文av在线| 国产欧美日韩高清| 日韩激情片免费| 亚洲最大的免费| 最近2019中文免费高清视频观看www99| 91爱爱小视频k| 美日韩在线视频| 中文字幕欧美日韩| 日韩欧美亚洲一二三区| 国产精品久久久久久久电影| 欧美亚洲伦理www| 亚洲a成v人在线观看| 亚洲精品国精品久久99热一| 美女扒开尿口让男人操亚洲视频网站| 茄子视频成人在线| 日韩亚洲国产中文字幕| 欧美尤物巨大精品爽| 国产日韩欧美自拍| 色偷偷av一区二区三区| 国产成人综合精品在线| 欧美精品在线观看| 日韩在线视频二区| 亚洲欧洲在线免费| 国产欧美日韩中文字幕| 亚洲天堂av在线免费观看| 欧美亚洲视频一区二区| 欧洲s码亚洲m码精品一区| 久久国产精品久久精品| 91啪国产在线| 国产亚洲精品成人av久久ww| 性欧美xxxx交| 日本欧美一二三区| 成人免费淫片视频软件| 91av福利视频| 国产精品一区二区三区免费视频| 亚洲精品中文字幕女同| 国产欧美va欧美va香蕉在| 国产97色在线| 91精品国产91久久| 亚洲人免费视频| 欧美猛交ⅹxxx乱大交视频| 亚洲欧美国产精品久久久久久久| 欧美亚洲另类视频| 黄色成人在线免费| 久久久久久久999精品视频| 国产九九精品视频| 91精品国产91久久| 欧美裸体xxxx| 国产日产欧美a一级在线| 国产精品极品美女粉嫩高清在线| 久久av.com| 一区二区三区视频免费在线观看| 久久人人爽人人爽人人片av高请| 久久久久久久一区二区三区| 黄色精品一区二区| 日韩精品亚洲精品| 91av国产在线| 欧美成人亚洲成人日韩成人| 国产成人一区二区| 欧美日韩午夜视频在线观看| 国产欧美精品va在线观看| 清纯唯美亚洲激情| 久久久久久久国产精品视频| 亚洲自拍欧美色图| 久久久久久久久久久久久久久久久久av| 久久成人在线视频| 国产精品日韩欧美| 亚洲аv电影天堂网|