HashSet以及LinkedHashSet源碼淺析

HashSet類(lèi)定義
public class HashSet<E>
    extends AbstractSet<E>
    implements Set<E>, Cloneable, java.io.Serializable{}

主要是繼承了AbstractSet,實(shí)現(xiàn)了Set接口旅薄。

主要成員變量
    private transient HashMap<E,Object> map;
    // Dummy value to associate with an Object in the backing Map
    private static final Object PRESENT = new Object();

我們知道set是一個(gè)無(wú)重復(fù)元素的集合瘟判,那么元素到底是如何保存呢蕉扮?實(shí)質(zhì)是保存在一個(gè)HashMap里整胃,這里使用的是map的key來(lái)保存元素,而map里面所有的value都是下方的PRESENT這個(gè)對(duì)象喳钟。

主要構(gòu)造方法
  /**
     * 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);
    }

HashSet的構(gòu)造方法比較靈活屁使,第一個(gè)是最簡(jiǎn)單的構(gòu)造方法;第二個(gè)是使用一個(gè)Collection來(lái)初始化map奔则,注意方法里調(diào)整了HashMap的初始容量蛮寂;第三個(gè)是根據(jù)參數(shù)設(shè)定初始大小和loadFactor;第四種就是指定了初始大小易茬。

主要方法
   /**
     * 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;
    }

添加元素方法很簡(jiǎn)單,map.put(e, PRESENT)==null;酬蹋,如果之前存在e了及老,那么返回false,如果不存在,返回true

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

刪除元素方法也很簡(jiǎn)單范抓,使用map.remove(o)即可骄恶。

 public boolean contains(Object o) {
        return map.containsKey(o);
    }

查詢(xún)是否存在該元素。

public boolean isEmpty() {
        return map.isEmpty();
    }

HashSet是否為空

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

返回iterator匕垫。

注意的地方

HashSet就是使用HashMap實(shí)現(xiàn)的僧鲁,HashMap不是線程安全的,HashSet同樣也不是線程安全的象泵,接下來(lái)需要分析HashMap這個(gè)類(lèi)寞秃。

LinkedHashSet類(lèi)定義
public class LinkedHashSet<E>
    extends HashSet<E>
    implements Set<E>, Cloneable, java.io.Serializable {
}

可以看到,LinkedHashSet繼承了HashSet偶惠,我們知道春寿,LinkedHashSet是保持插入順序的一種Set,那么是如何保證呢忽孽?請(qǐng)看構(gòu)造方法绑改。

主要構(gòu)造方法
 public LinkedHashSet(int initialCapacity, float loadFactor) {
        super(initialCapacity, loadFactor, true);
    }

    /**
     * Constructs a new, empty linked hash set with the specified initial
     * capacity and the default load factor (0.75).
     *
     * @param   initialCapacity   the initial capacity of the LinkedHashSet
     * @throws  IllegalArgumentException if the initial capacity is less
     *              than zero
     */
    public LinkedHashSet(int initialCapacity) {
        super(initialCapacity, .75f, true);
    }

    /**
     * Constructs a new, empty linked hash set with the default initial
     * capacity (16) and load factor (0.75).
     */
    public LinkedHashSet() {
        super(16, .75f, true);
    }

    /**
     * Constructs a new linked hash set with the same elements as the
     * specified collection.  The linked hash set is created with an initial
     * capacity sufficient to hold the elements in the specified collection
     * and the default load factor (0.75).
     *
     * @param c  the collection whose elements are to be placed into
     *           this set
     * @throws NullPointerException if the specified collection is null
     */
    public LinkedHashSet(Collection<? extends E> c) {
        super(Math.max(2*c.size(), 11), .75f, true);
        addAll(c);
    }

可以看到,構(gòu)造方法均是調(diào)用了父類(lèi)方法扒腕,具體是哪個(gè)父類(lèi)方法呢绢淀?

   /**
     * 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
     */
    HashSet(int initialCapacity, float loadFactor, boolean dummy) {
        map = new LinkedHashMap<>(initialCapacity, loadFactor);
    }

這個(gè)構(gòu)造方法的說(shuō)明里提到了,此方法僅提供給LinkedHashSet瘾腰,里面是用LinkedHashMap來(lái)代替了HashMap。
HashSet和LinkedHashSet背后都是map覆履,所以需要研究下map系列蹋盆。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市硝全,隨后出現(xiàn)的幾起案子栖雾,更是在濱河造成了極大的恐慌,老刑警劉巖伟众,帶你破解...
    沈念sama閱讀 219,427評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件析藕,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡凳厢,警方通過(guò)查閱死者的電腦和手機(jī)账胧,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,551評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)先紫,“玉大人治泥,你說(shuō)我怎么就攤上這事≌诰” “怎么了居夹?”我有些...
    開(kāi)封第一講書(shū)人閱讀 165,747評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我准脂,道長(zhǎng)劫扒,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,939評(píng)論 1 295
  • 正文 為了忘掉前任狸膏,我火速辦了婚禮粟关,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘环戈。我一直安慰自己闷板,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,955評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布院塞。 她就那樣靜靜地躺著遮晚,像睡著了一般。 火紅的嫁衣襯著肌膚如雪拦止。 梳的紋絲不亂的頭發(fā)上县遣,一...
    開(kāi)封第一講書(shū)人閱讀 51,737評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音汹族,去河邊找鬼萧求。 笑死,一個(gè)胖子當(dāng)著我的面吹牛顶瞒,可吹牛的內(nèi)容都是我干的夸政。 我是一名探鬼主播,決...
    沈念sama閱讀 40,448評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼榴徐,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼守问!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起坑资,我...
    開(kāi)封第一講書(shū)人閱讀 39,352評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤耗帕,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后袱贮,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體仿便,經(jīng)...
    沈念sama閱讀 45,834評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,992評(píng)論 3 338
  • 正文 我和宋清朗相戀三年攒巍,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了嗽仪。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,133評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡窑业,死狀恐怖钦幔,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情常柄,我是刑警寧澤鲤氢,帶...
    沈念sama閱讀 35,815評(píng)論 5 346
  • 正文 年R本政府宣布搀擂,位于F島的核電站,受9級(jí)特大地震影響卷玉,放射性物質(zhì)發(fā)生泄漏哨颂。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,477評(píng)論 3 331
  • 文/蒙蒙 一相种、第九天 我趴在偏房一處隱蔽的房頂上張望威恼。 院中可真熱鬧,春花似錦寝并、人聲如沸箫措。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,022評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)斤蔓。三九已至,卻和暖如春镀岛,著一層夾襖步出監(jiān)牢的瞬間弦牡,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,147評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工漂羊, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留驾锰,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,398評(píng)論 3 373
  • 正文 我出身青樓走越,卻偏偏與公主長(zhǎng)得像椭豫,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子买喧,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,077評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容