java hashset實(shí)現(xiàn)原理及工作原理

java hashset實(shí)現(xiàn)原理及工作原理

長(zhǎng)沙達(dá)內(nèi)教育      2022-04-07 02:14:01     7

java hashset實(shí)現(xiàn)原理及工作原理,概述ThisclassimplementstheSetinterface,backedbyahashtable(actuallyaHashMapinstance).Itmakesnoguaranteesastotheiterationo

課程價(jià)格 請(qǐng)咨詢

上課時(shí)段: 授課校區(qū):

詳細(xì)介紹

 

概述

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 Mapprivate 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。

 

以上就是長(zhǎng)沙達(dá)內(nèi)教育java培訓(xùn)機(jī)構(gòu)的小編針對(duì)“Java hashset實(shí)現(xiàn)原理及工作原理”的內(nèi)容進(jìn)行的回答,希望對(duì)大家有所幫助,如有疑問,請(qǐng)?jiān)诰€咨詢,有專業(yè)老師隨時(shí)為你服務(wù)。

 

培訓(xùn)啦提醒您:交易時(shí)請(qǐng)核實(shí)對(duì)方資質(zhì),對(duì)于過大宣傳或承諾需謹(jǐn)慎!任何要求預(yù)付定金、匯款等方式均存在風(fēng)險(xiǎn),謹(jǐn)防上當(dāng)。