亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Java數(shù)據(jù)結(jié)構(gòu)中的HashMap和HashSet詳解

 更新時間:2023年10月24日 09:12:13   作者:不是懶大王  
HashMap和HashSet都是存儲在哈希桶之中,通過本文我們可以先了解一些哈希桶是什么,本文結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友參考下吧

HashMap和HashSet都是存儲在哈希桶之中,我們可以先了解一些哈希桶是什么。

像這樣,一個數(shù)組數(shù)組的每個節(jié)點(diǎn)帶著一個鏈表,數(shù)據(jù)就存放在鏈表結(jié)點(diǎn)當(dāng)中。哈希桶插入/刪除/查找節(jié)點(diǎn)的時間復(fù)雜度是O(1)

map代表存入一個key值,一個val值。map可多次存儲,當(dāng)?shù)诙尾迦霑r,會更新val值。

set代表只存入一個key值,但在實(shí)際源碼中,set的底層其實(shí)也是靠map來實(shí)現(xiàn)的。set只能存入數(shù)據(jù)一次,當(dāng)?shù)诙尾迦霑r,若哈希桶中存在元素則返回false。

下面是代碼實(shí)現(xiàn)

// 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ù)個數(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,插入一個新的結(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)于Java數(shù)據(jù)結(jié)構(gòu)中的HashMap和HashSet的文章就介紹到這了,更多相關(guān)java HashMap和HashSet內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論