HashSet集合保证元素唯一性的源码分析

HashSet的底层实现是HashMap,添加元素时,是将元素存储到hashmap中的k的位置,而hashmap中的k值不能重复,所以hashset保证了存入元素的唯一性。
  • 以下是HashSet的add()方法;
public class HashSet<E>
    extends AbstractSet<E>
    implements Set<E>, Cloneable, java.io.Serializable
{
    static final long serialVersionUID = -5024744406713321676L;
    private transient HashMap<E,Object> map;

    // Dummy value to associate with an Object in the backing Map
    private static final Object PRESENT = new Object();
    /**
     * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
     * default initial capacity (16) and load factor (0.75).
     */
    public HashSet() {
        map = new HashMap<>();
    }
 	public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }
  • add()方法中调用了hashmap对象的put方法;添加元素时,将对象存入hashmap中的key的位置,value每次都为一个静态常量PRESENT作为key的虚拟值
public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

/**
     * Implements Map.put and related methods.
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to put
     * @param onlyIfAbsent if true, don't change existing value
     * @param evict if false, the table is in creation mode.
     * @return previous value, or null if none
     */
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

到了这里,恕我目前能力所限,就不能展开解说了。

参考其他资料,语言表述如下:
1、调用对象的hashcode()方法,获取对象的哈希值;
2、根据对象的哈希值,计算对象的存储位置;
3、该位置是否有元素存在:
-----------3.1、如果没有,则将元素存储到该位置。到此结束。
-----------3.2、如果有,遍历该位置所有元素,和新存入的元素比较哈希值是否相同:
----------------------------3.2.1、如果都不相同,则说明已有元素与新存入的元素均不相同(因为同一对象多次调用hashcode方法返回的哈希值是相同的),将元素存储到该位置。
----------------------------3.2.2、如果有相同的,则再次调用equals()方法比较对象的内容是否相等
-------------------------------------3.2.2.1、如果相等,则说明该元素重复,不存储。
-------------------------------------3.2.2.2、如果不相等,则存储到该位置。

hashset集合存储元素,要保证元素唯一性,需重写自定义对象的hashCode()和equals()方法!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值