您的位置:首页 > 其它

重写equals方法为什么一定要重写hashcode方法

2017-09-22 01:50 549 查看
重写equals方法时需要重写hashCode方法,主要是针对Map、Set等集合类型的使用

HashSet的add方法源码:

  /**

     * Adds the specified element to this set if it is not already present.

     * More formally, adds the specified element <tt>e</tt> to this set if

     * this set contains no element <tt>e2</tt> such that

     * <tt>(e==null ? e2==null : e.equals(e2))</tt>.

     * If this set already contains the element, the call leaves the set

     * unchanged and returns <tt>false</tt>.

     *

     * @param e element to be added to this set

     * @return <tt>true</tt> if this set did not already contain the specified

     * element

     */

    public boolean add(E e) {
return map.put(e, PRESENT)==null;

    }

HashMap的put方法的源码:

    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;

    }

HashMap的get方法:

    public V get(Object key) {

        if (key == null)

            return getForNullKey();

        int hash = hash(key.hashCode());

        for (Entry<K,V> e = table[indexFor(hash, table.length)];

             e != null;

             e = e.next) {

            Object k;

            if (e.hash == hash && ((k = e.key) == key || key.equals(k)))

                return e.value;

        }

        return null;

    }

可见重写equalls不重写HashCode那么Set中可以加入重复的元素,Map中可以加入重复的Key,而HashMap在get的时候又会取到不同的元素

即:
(1)当obj1.equals(obj2)为true时,obj1.hashCode() == obj2.hashCode()必须为true 
(2)当obj1.hashCode() == obj2.hashCode()为false时,obj1.equals(obj2)必须为false
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐