java-集合框架HashSet

Posted 智公博客

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java-集合框架HashSet相关的知识,希望对你有一定的参考价值。

一、概述

1.HashSet 继承AbstractSet抽象类、实现Set接口,内部通过Hash table(HashMap) 实现

2.元素无序,可以有一个NULL元素

3.一般操作(add、remove、contains、size)不考虑元素的Hash函数时间,是常量时间复杂度

4.迭代器时间相当于 元素的size + 背后HashMap的容量(capacity),所以如果需要经常迭代的场景,减少初始空间和加大负载扩容因子(load factor)

5.非同步,非线程安全,与其他非同步集合一样,迭代器并发修改是 fast-fail 机制,抛出 ConcurrentModificationException

6.如果需要同步的集合,可以通过工具类方法 Collections.synchronizedSet 封装一个

二、源码分析

1、变量

private transient HashMap<E,Object> map;

// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();

类成员变量就一个map,就是HashSet背后的实现,另外一个 Object PRESENT 用于这个map的value,所有元素的value都是这个对象,key才是HashSet的每个元素

2、构造函数

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

    /**
     * Constructs a new set containing the elements in the specified
     * collection.  The <tt>HashMap</tt> is created with default load factor
     * (0.75) and an initial capacity sufficient to contain the elements in
     * the specified collection.
     *
     * @param c the collection whose elements are to be placed into this set
     * @throws NullPointerException if the specified collection is null
     */
    public HashSet(Collection<? extends E> c) 
        map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16));
        addAll(c);
    

    /**
     * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
     * the specified initial capacity and the specified load factor.
     *
     * @param      initialCapacity   the initial capacity of the hash map
     * @param      loadFactor        the load factor of the hash map
     * @throws     IllegalArgumentException if the initial capacity is less
     *             than zero, or if the load factor is nonpositive
     */
    public HashSet(int initialCapacity, float loadFactor) 
        map = new HashMap<>(initialCapacity, loadFactor);
    

    /**
     * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
     * the specified initial capacity and default load factor (0.75).
     *
     * @param      initialCapacity   the initial capacity of the hash table
     * @throws     IllegalArgumentException if the initial capacity is less
     *             than zero
     */
    public HashSet(int initialCapacity) 
        map = new HashMap<>(initialCapacity);
    

可以看出所有的构造函数,都是初始一个HashMap,关于HashMap的capacity和 load factor 参数可以看本系列的HashMap专门文章;这里有一点需要注意的,从一个Collection创建一个HashSet时,capacity是计算了初始容量然后才addAll,就是为了防止这个Collection size 超过默认的HashMap capacity,避免一开始就要扩容

三、其他一些方法

    /**
     * Returns an iterator over the elements in this set.  The elements
     * are returned in no particular order.
     *
     * @return an Iterator over the elements in this set
     * @see ConcurrentModificationException
     */
    public Iterator<E> iterator() 
        return map.keySet().iterator();
    

    /**
     * Returns the number of elements in this set (its cardinality).
     *
     * @return the number of elements in this set (its cardinality)
     */
    public int size() 
        return map.size();
    

    /**
     * Returns <tt>true</tt> if this set contains no elements.
     *
     * @return <tt>true</tt> if this set contains no elements
     */
    public boolean isEmpty() 
        return map.isEmpty();
    

    /**
     * Returns <tt>true</tt> if this set contains the specified element.
     * More formally, returns <tt>true</tt> if and only if this set
     * contains an element <tt>e</tt> such that
     * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>.
     *
     * @param o element whose presence in this set is to be tested
     * @return <tt>true</tt> if this set contains the specified element
     */
    public boolean contains(Object o) 
        return map.containsKey(o);
    

    /**
     * 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;
    

    /**
     * Removes the specified element from this set if it is present.
     * More formally, removes an element <tt>e</tt> such that
     * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>,
     * if this set contains such an element.  Returns <tt>true</tt> if
     * this set contained the element (or equivalently, if this set
     * changed as a result of the call).  (This set will not contain the
     * element once the call returns.)
     *
     * @param o object to be removed from this set, if present
     * @return <tt>true</tt> if the set contained the specified element
     */
    public boolean remove(Object o) 
        return map.remove(o)==PRESENT;
    

可以看到,这所有方法都已经是操作HashMap的了,没有什么可以分析了;

另外HashSet实现了Cloneable接口

    /**
     * Returns a shallow copy of this <tt>HashSet</tt> instance: the elements
     * themselves are not cloned.
     *
     * @return a shallow copy of this set
     */
    public Object clone() 
        try 
            HashSet<E> newSet = (HashSet<E>) super.clone();
            newSet.map = (HashMap<E, Object>) map.clone();
            return newSet;
         catch (CloneNotSupportedException e) 
            throw new InternalError();
        
    

这个复制只是一个浅复制,map里面的元素是没有复制的,所有并不要求元素实现Cloneable

三、总结

从源码可以清晰看到,HashSet其实就是简单通过一个HashMap实现,没有自己特殊的实现

以上是关于java-集合框架HashSet的主要内容,如果未能解决你的问题,请参考以下文章

Java集合框架中的Hashtable、HashMap、HashSet、哈希表概念

Java8集合框架——HashSet源码分析

java集合框架笔记HashSetHashMap

Java自学-集合框架 ArrayList和HashSet的区别

java-集合框架HashSet

java-集合框架HashSet