更新時間:2020-08-17 16:50:29 來源:動力節點 瀏覽3320次
概述
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來實現的,操作很簡單,更像是對HashMap做了一次“封裝”,而且只使用了HashMap的key來實現各種特性,我們先來感性的認識一下這個結構:
HashSet set = new HashSet(); set.add("語文"); set.add("數學"); set.add("英語"); set.add("歷史"); set.add("政治"); set.add("地理"); set.add("生物"); set.add("化學");
其大致的結構是這樣的:
private transient HashMap map; // Dummy value to associate with an Object in the backing Map private static final Object PRESENT = new Object();
map是整個HashSet的核心,而PRESENT則是用來造一個假的value來用的。Map有鍵和值,HashSet相當于只有鍵,值都是相同的固定值,即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(); }
基本操作也非常簡單,就是調用HashMap的相關方法,其中value就是之前那個dummy的Object。
以上就是動力節點java培訓機構的小編針對“Java hashset實現原理及工作原理”的內容進行的回答,希望對大家有所幫助,如有疑問,請在線咨詢,有專業老師隨時為你服務。
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習