java集合框架之HashSet

starlin 677 2018-05-09

HashSet介绍

对于HashSet而言,它是基于HashMap来实现的,底层采用HashMap来保存元素,若对Hashmap很熟悉,那么HashSet就很容易了

本文源码均为JDK1.8

HashSet源码解析

定义

HashSet继承至AbstractSet,实现Set、Cloneable、Cloneable接口。其中Set接口是一种不包含重复元素的Collection,维持自己内部的排序。

public class HashSet<E>
    extends AbstractSet<E>
    implements Set<E>, Cloneable, java.io.Cloneable

属性

//基于HashMap实现,底层使用HashMap保存所有元素
private transient HashMap<E,Object> map;

//定义一个Object对象
private static final Object PRESENT = new Object();

构造函数

可以明显的看到内部都是基于HashMap的,除了最后一个构造函数,只有在使用LinkedHashSet时才起作用,这个有点意思

    /**
     * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
     * default initial capacity (16) and load factor (0.75).
     */
     //构造一个空的set,
     //初始化一个空的HashMap,并使用默认初始容量为16和加载因子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
     */
     //构造一个包含指定 collection 中的元素的新 set。
    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
     */
     //构造一个新的空 set,其底层 HashMap 实例具有指定的初始容量和指定的加载因子
    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
     */
     //构造一个新的空 set,其底层 HashMap 实例具有指定的初始容量和默认的加载因子(0.75)。
    public HashSet(int initialCapacity) {
        map = new HashMap<>(initialCapacity);
    }


    /**
     * Constructs a new, empty linked hash set.  (This package private
     * constructor is only used by LinkedHashSet.) The backing
     * HashMap instance is a LinkedHashMap with 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
     * @param      dummy             ignored (distinguishes this
     *             constructor from other int, float constructor.)
     * @throws     IllegalArgumentException if the initial capacity is less
     *             than zero, or if the load factor is nonpositive
     */
     //该构造函数只有在使用LinkedHashSet才起作用,不对外提供的
    HashSet(int initialCapacity, float loadFactor, boolean dummy) {
        map = new LinkedHashMap<>(initialCapacity, loadFactor);
    }

方法

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&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
     */
     
    /**  
    * 如果此set中尚未包含指定元素,则添加指定元素。  
    * 更确切地讲,如果此 set 没有包含满足(e==null ? e2==null : e.equals(e2))  
    * 的元素e2,则向此set 添加指定的元素e。  
    * 如果此set已包含该元素,则该调用不更改set并返回false。  
    *
    * 底层实际将将该元素作为key放入HashMap。  
    * 由于HashMap的put()方法添加key-value对时,当新放入HashMap的Entry中key  
    * 与集合中原有Entry的key相同(hashCode()返回值相等,通过equals比较也返回true),  
    * 新添加的Entry的value会将覆盖原来Entry的value,但key不会有任何改变,  
    * 因此如果向HashSet中添加一个已经存在的元素时,新添加的集合元素将不会被放入HashMap中,  
    * 原来的元素也不会有任何改变,这也就满足了Set中元素不重复的特性。  
    * @param e 将添加到此set中的元素。  
    * @return 如果此set尚未包含指定元素,则返回true。  
    */   
    public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }

remove()方法

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

    /**  
    * 如果指定元素存在于此set中,则将其移除。  
    * 更确切地讲,如果此set包含一个满足(o==null ? e==null : o.equals(e))的元素e,  
    * 则将其移除。如果此set已包含该元素,则返回true  
    * (或者:如果此set因调用而发生更改,则返回true)。(一旦调用返回,则此set不再包含该元素)。  
    *  
    * 底层实际调用HashMap的remove方法删除指定Entry。  
    * @param o 如果存在于此set中则需要将其移除的对象。  
    * @return 如果set包含指定元素,则返回true。  
    */    
    public boolean remove(Object o) {
        return map.remove(o)==PRESENT;
    }

clear()方法

    /**
     * Removes all of the elements from this set.
     * The set will be empty after this call returns.
     */
     
    /**  
    * 从此set中移除所有元素。此调用返回后,该set将为空。  
    *  
    * 底层实际调用HashMap的clear方法清空Entry中所有元素。  
    */   
    public void clear() {
        map.clear();
    }

contains()方法

    /**
     * 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
     */
     
    /**  
    * 如果此set包含指定元素,则返回true。  
    * 更确切地讲,当且仅当此set包含一个满足(o==null ? e==null : o.equals(e))  
    * 的e元素时,返回true。  
    *  
    * 底层实际调用HashMap的containsKey判断是否包含指定key。  
    * @param o 在此set中的存在已得到测试的元素。  
    * @return 如果此set包含指定元素,则返回true。  
    */    
    public boolean contains(Object o) {
        return map.containsKey(o);
    }

iterator()方法

    /**
     * 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
     */
     
    /**  
    * 返回对此set中元素进行迭代的迭代器。返回元素的顺序并不是特定的。  
    *   
    * 底层实际调用底层HashMap的keySet来返回所有的key。  
    * 可见HashSet中的元素,只是存放在了底层HashMap的key上,  
    * value使用一个static final的Object对象标识。  
    * @return 对此set中元素进行迭代的Iterator。  
    */     
    public Iterator<E> iterator() {
        return map.keySet().iterator();
    }

与TreeSet区别

  1. TreeSet 是二差树(红黑树的树据结构)实现的,Treeset中的数据是自动排好序的,不允许放入null值
  2. HashSet 是哈希表实现的,HashSet中的数据是无序的,可以放入null,但只能放入一个null,两者中的值都不能重复,就如数据库中唯一约束
  3. HashSet要求放入的对象必须实现HashCode()方法,放入的对象,是以hashcode码作为标识的,而具有相同内容的String对象,hashcode是一样,所以放入的内容不能重复。但是同一个类的对象可以放入不同的实例。

适用场景分析:HashSet是基于Hash算法实现的,其性能通常都优于TreeSet。为快速查找而设计的Set,我们通常都应该使用HashSet,在我们需要排序的功能时,我们才使用TreeSet。

总结

因HashSet底层采用HashMap来实现,所以实现起来很简单


# java集合