上篇中介紹了collection中arraylist和linkedlist和在資料結構中的分析。但在,由於collection是無論是基於陣列的arraylist還是基於鍊錶的linkedlist它都沒有辦法儲存有關係的資料,比如乙個人的姓名—身份證,這樣有關係的資料。因此就有了map介面。
arraylist和linkedlist的資料結構分析
map用於儲存具有對映關係的資料,因此map集合中儲存著兩種值,一組用於儲存key,另一組用來儲存value。並且key不允許重複。
下圖為map介面所衍生的類或者
幾個重要的引數
預設大小為16
載入因子:這裡涉及到map的擴容機制,也就是map的擴容時機,舉例當map大小為100,但裡面有74個元素,當再次新增的時候,map就會擴容。再比如說預設大小為16,當map中元素有16*0.75=12的時候,就擴容。這樣減小map擴容的次數和。
table 為map的大小,但不是實際元素的個數。
size為map中當前元素的個數。
/**
* 預設大小為16
*/static
final
int default_initial_capacity = 1
<< 4; // aka 16
/** * 載入因子為0.75
*/static
final
float default_load_factor = 0.75f;
/*** map中儲存的元素,可以進行擴容
*/transient entry table = (entry) empty_table;
/*** map中元素的個數
*/transient
int size;
構造方法中幾個預設值。
public
hashmap(int initialcapacity, float loadfactor)
public
hashmap(int initialcapacity)
/*** 預設大小為16
* 預設載入因子 (0.75).
*/public
hashmap()
public
hashmap(map extends k, ? extends v> m)
當我們給put()方法傳遞鍵和值時,我們先對鍵呼叫hashcode()方法,返回的hashcode用於找到bucket位置來儲存entry物件
如果key中值已經存在,那會再次新增會覆蓋以前的value
public v put(k key, v value)
if (key == null)
return putfornullkey(value);
int hash = hash(key);
int i = indexfor(hash, table.length);
for (entrye = table[i]; e != null; e = e.next)
}modcount++;
addentry(hash, key, value, i);
return
null;
}
新增元素,如果到載入因子0.75時,會擴容。將map*2,並把原來map中的元素放入到新的擴容後的map中。
resize(2 * table.length);
void resize(int newcapacity)
entry newtable = new entry[newcapacity];
transfer(newtable, inithashseedasneeded(newcapacity));
table = newtable;
threshold = (int)math.min(newcapacity * loadfactor, maximum_capacity + 1);
}
public v get(object key)
通過計算key的hashcode,再通過hashcode找出value。
final entrygetentry(object key)
int hash = (key == null) ? 0 : hash(key);
for (entrye = table[indexfor(hash, table.length)];
e != null;
e = e.next)
return
null;
}
從上面的**中可以看出hashmap中是用陣列為基礎,資料中每個元素鍊錶來實現,也就是陣列+鍊錶,如圖
從上表可以看出在陣列中,每乙個元素都是linkedlist
1、hashcode相同說明是不是同乙個物件?
hashcode相同,並不能說明是同乙個物件!因為他們hashcode相同,所以bucket的位置相同,hashmap真正的儲存物件是用的linkedlist儲存物件,這個entry(key,value)也就是儲存在linkedlist中。
2、hashmap與hashtable的區別
其他比較好的部落格
C 演算法與資料結構之map
管理元素集合的stl容器大致分為兩類。一類是有順序的集合,稱為序列式容器 另一類是經過排序的集合,稱為關聯式容器。序列式容器會將新新增的元素置於特定為位置,這個位置由插入的時間和地點決定,與元素本身的值無關。前面介紹過的vector和list就是很有代表性的序列式容器。相對地,關聯式容器會依據特定的...
資料結構 map的學習
main.cpp map使用 created by 劉鑫偉 on 14 7 25.include include includeusing namespace std int main 清空map中的資料可以用clear 函式,判定map中是否有資料可以用empty 函式,它返回true則說明是空m...
Python實現Map資料結構
class hashtable def init self 初始化兩個list,乙個用來儲存鍵值,乙個用來儲存值 self.size 11 self.slots none self.size self.data none self.size 定義hash函式,使用餘數法 def hashfuncti...