java中的HashSet集合是怎么实现不重复的?

在做业务的时候经常会遇到需要对集合去重,最常用的就是HashSet。那HashSet是怎么实现的不重复存储的哪?各位看官往下看:

先看个最简单的构造方法

     * 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<>();
    }

很明显,HashSet底层是hashmap存储的。借大神的话

HashSet 就是HashMap的马甲       -----someone

很形象哈。

再看看add方法

// Dummy value to associate with an Object in the backing Map
 private transient HashMap<E,Object> map;
 private static final Object PRESENT = new Object();
/**
     * 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&nbsp;?&nbsp;e2==null&nbsp;:&nbsp;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;
    }

add方法的参数(要存储的value)作为HashMap的key,PRESENT(Object PRESENT = new Object();)作为固定value。

重点看key(敲黑板)

HashMap中的put方法

    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;
    }

这里边有两个看点:

  • HashMap中key存储是hash后的值,对于String类型的相同值的hash值是一致的(其他接触类型类似,自定义对象类型需要重写hashcode方法与equel方法)。换句话说相同的值在hashMap中的存储位置是一样的。
  • 基于上一点来看看怎么存储重复值的。如下代码对于hashMap中已经存在的key,key不变,新value覆盖就value。对于HashSet而言新旧value都是PRESENT对象,所以set在存储的时候就不会重复。
            if (e != null) { // existing mapping for key
              V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }

所以hashset中存储的值输出的顺序和存储的先后顺序不一致,而是按照值的hash顺序输出。

总结:

通过分析HashSet的实现原理,可以肯定的是它的去重效率是很高的,前提是去重对象需要有hashcode、equel方法的实现。除此外HashMap所拥有的大多数特性都适用于HashSet。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 实际上,HashSet 和 HashMap 之间有很多相似之处,对于 HashSet 而言,系统采用 Hash 算...
    曹振华阅读 2,526评论 1 37
  • 一、基本数据类型 注释 单行注释:// 区域注释:/* */ 文档注释:/** */ 数值 对于byte类型而言...
    龙猫小爷阅读 4,289评论 0 16
  • 平凡的世界,我看了三遍,每一次都会哭,每一次都有不同的感觉,那种魅力好像永远都是那么强,让人无法忽视。 路...
    在泛黄的书卷中寻找未来阅读 723评论 0 12
  • 铜匠。接触了新鲜的生活,为了摆脱自己的环境,学习知识很快,发现通过捧人踩人能更快摆脱原有生活,学起来更快。 裴魁山...
    eightly阅读 336评论 0 0
  • 那年的自己,或是天真无邪,抑或是年少轻狂,总有些初生牛犊不怕虎的狂傲。信誓旦旦,理直气壮地许下一个个美丽的诺言,说...
    我叫于曉曉曉曉曉曉阅读 283评论 0 0