HashMap和HashSet都是存儲(chǔ)在哈希桶之中,我們可以先了解一些哈希桶是什么。
像這樣,一個(gè)數(shù)組數(shù)組的每個(gè)節(jié)點(diǎn)帶著一個(gè)鏈表,數(shù)據(jù)就存放在鏈表結(jié)點(diǎn)當(dāng)中。哈希桶插入/刪除/查找節(jié)點(diǎn)的時(shí)間復(fù)雜度是O(1)
map代表存入一個(gè)key值,一個(gè)val值。map可多次存儲(chǔ),當(dāng)?shù)诙尾迦霑r(shí),會(huì)更新val值。
set代表只存入一個(gè)key值,但在實(shí)際源碼中,set的底層其實(shí)也是靠map來(lái)實(shí)現(xiàn)的。set只能存入數(shù)據(jù)一次,當(dāng)?shù)诙尾迦霑r(shí),若哈希桶中存在元素則返回false。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-735637.html
下面是代碼實(shí)現(xiàn)文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-735637.html
// key-value 模型
public class HashBucket {
private static class Node {
private int key;
private int value;
Node next;
public Node(int key, int value) {
this.key = key;
this.value = value;
}
}
private Node[] array;
private int size; // 當(dāng)前的數(shù)據(jù)個(gè)數(shù)
private static final double LOAD_FACTOR = 0.75;
public int put(int key, int value) {
int index = key % array.length;
// 在鏈表中查找 key 所在的結(jié)點(diǎn)
// 如果找到了,更新
// 所有結(jié)點(diǎn)都不是 key,插入一個(gè)新的結(jié)點(diǎn)
for (Node cur = array[index]; cur != null; cur = cur.next) {
if (key == cur.key) {
int oldValue = cur.value;
cur.value = value;
return oldValue;
}
} N
ode node = new Node(key, value);
node.next = array[index];
array[index] = node;
size++;
if (loadFactor() >= LOAD_FACTOR) {
resize();
} r
eturn -1;
}
private void resize() {
Node[] newArray = new Node[array.length * 2];
for (int i = 0; i < array.length; i++) {
Node next;
for (Node cur = array[i]; cur != null; cur = next) {
next = cur.next;
int index = cur.key % newArray.length;
cur.next = newArray[index];
newArray[index] = cur;
}
} a
rray = newArray;
}
private double loadFactor() {
return size * 1.0 / array.length;
}
public HashBucket() {
array = new Node[8];
size = 0;
}
public int get(int key) {
int index = key % array.length;
Node head = array[index];
for (Node cur = head; cur != null; cur = cur.next) {
if (key == cur.key) {
return cur.value;
}
}
return -1;
}
}
到了這里,關(guān)于數(shù)據(jù)結(jié)構(gòu)---HashMap和HashSet的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!