A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 何洪森 黑马帝   /  2012-2-8 22:34  /  2108 人查看  /  5 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 何森 于 2012-2-9 12:52 编辑

在hashset中不允许出现重复对象,在hashset中又是怎样判定元素是否重复的呢?
是通过equals()还是通过hashCode()在?

点评

/** * Returns <tt>true</tt> if this map contains a mapping for the * specified key. * * @param key The key whose presence in this map is to be tested * @return <tt>...   发表于 2017-10-23 09:17

评分

参与人数 1技术分 +1 收起 理由
唐秀启 + 1

查看全部评分

5 个回复

倒序浏览
先通过hashCode判断 若存在 再使用equals判断 若两种方法都一样、
hashset就会认为这是重复元素,并不允许存入,即:
hs.add(element)的返回值为false

评分

参与人数 1技术分 +1 收起 理由
唐秀启 + 1

查看全部评分

回复 使用道具 举报
这就牵涉到hashSet的存放原理了,hashSet会根据hashCode将元素分到若干个区中,一个区中的元素的值不能equals相等,不同的区里面的元素是可以equals相等的,如果hashcode值相等(在一个区中),并且equals相等,会被认为是相同的元素,就不能进行存放,所以是通过hashCode和equals方法共同进行判断的

评分

参与人数 1技术分 +1 收起 理由
唐秀启 + 1

查看全部评分

回复 使用道具 举报
本帖最后由 彭沛东 于 2012-2-9 00:10 编辑
  1.     public V put(K key, V value) {
  2.         if (key == null)
  3.             return putForNullKey(value);
  4.         int hash = hash(key.hashCode());
  5.         int i = indexFor(hash, table.length);
  6.         for (Entry<K,V> e = table[i]; e != null; e = e.next) {
  7.             Object k;
  8.             if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
  9.                 V oldValue = e.value;
  10.                 e.value = value;
  11.                 e.recordAccess(this);
  12.                 return oldValue;
  13.             }
  14.         }
复制代码
为了保证HashSet中的对象不会出现重复值,在被存放元素的类中必须要重写hashCode()和equals()这两个方法。

评分

参与人数 1技术分 +1 收起 理由
唐秀启 + 1 赞一个!

查看全部评分

回复 使用道具 举报
    /**
     * Returns <tt>true</tt> if this map contains a mapping for the
     * specified key.
     *
     * @param   key   The key whose presence in this map is to be tested
     * @return <tt>true</tt> if this map contains a mapping for the specified
     * key.
     */
    public boolean containsKey(Object key) {
        return getEntry(key) != null;
    }

    /**
     * Returns the entry associated with the specified key in the
     * HashMap.  Returns null if the HashMap contains no mapping
     * for the key.
     */
    final Entry<K,V> getEntry(Object key) {
        int hash = (key == null) ? 0 : hash(key);
        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 != null && key.equals(k))))
                return e;
        }
        return null;
    }
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马