更新時(shí)間:2020-08-17 16:50:29 來源:動(dòng)力節(jié)點(diǎn) 瀏覽3385次
概述
This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element.This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element.
HashSet是基于HashMap來實(shí)現(xiàn)的,操作很簡(jiǎn)單,更像是對(duì)HashMap做了一次“封裝”,而且只使用了HashMap的key來實(shí)現(xiàn)各種特性,我們先來感性的認(rèn)識(shí)一下這個(gè)結(jié)構(gòu):
HashSet set = new HashSet(); set.add("語文"); set.add("數(shù)學(xué)"); set.add("英語"); set.add("歷史"); set.add("政治"); set.add("地理"); set.add("生物"); set.add("化學(xué)");
其大致的結(jié)構(gòu)是這樣的:
private transient HashMap map; // Dummy value to associate with an Object in the backing Map private static final Object PRESENT = new Object();
map是整個(gè)HashSet的核心,而PRESENT則是用來造一個(gè)假的value來用的。Map有鍵和值,HashSet相當(dāng)于只有鍵,值都是相同的固定值,即PRESENT。
2. 基本操作
public boolean add(E e) { return map.put(e, PRESENT)==null; } public boolean remove(Object o) { return map.remove(o)==PRESENT; } public boolean contains(Object o) { return map.containsKey(o); } public int size() { return map.size(); }
基本操作也非常簡(jiǎn)單,就是調(diào)用HashMap的相關(guān)方法,其中value就是之前那個(gè)dummy的Object。
以上就是動(dòng)力節(jié)點(diǎn)java培訓(xùn)機(jī)構(gòu)的小編針對(duì)“Java hashset實(shí)現(xiàn)原理及工作原理”的內(nèi)容進(jìn)行的回答,希望對(duì)大家有所幫助,如有疑問,請(qǐng)?jiān)诰€咨詢,有專業(yè)老師隨時(shí)為你服務(wù)。
相關(guān)閱讀
0基礎(chǔ) 0學(xué)費(fèi) 15天面授
有基礎(chǔ) 直達(dá)就業(yè)
業(yè)余時(shí)間 高薪轉(zhuǎn)行
工作1~3年,加薪神器
工作3~5年,晉升架構(gòu)
提交申請(qǐng)后,顧問老師會(huì)電話與您溝通安排學(xué)習(xí)