[英]Java custom HashMap - Clear method
我已經為特殊的用例創建了自己的自定義HashMap,但是我缺少“清除”方法。
我在互聯網上只找到一種針對HashMaps的清晰方法的實現,但我只是無法解決。
誰能幫我? 我提供了自定義的HashMap和我在互聯網上找到的一個實現。
我的自定義HashMap:
public class LongToOSMNodeMap {
private Node[] table;
int MASK;
public LongToOSMNodeMap(int capacity) {
table = new Node[1 << capacity]; // there are 2^{capacity} table cells
MASK = table.length - 1;
}
public void put(long id, double lon, double lat) {
int position = Long.hashCode(id) & MASK;
table[position] = new Node(id, lon, lat, table[position]);
}
public Node get(long id) {
int position = Long.hashCode(id) & MASK;
for (Node n = table[position]; n != null; n = n.next) {
if (n.id == id) {
return n;
}
}
return null;
}
public void clear() {
}
class Node extends OSMNode {
long id;
Node next;
public Node(long id, double lon, double lat, Node n) {
super(lon, lat);
this.id = id;
this.next = n;
}
}
清除方法實現,我沒有得到,但是想自己實現:
public void clear() {
modCount++;
Entry[] tab = table;
for (int i = 0; i < tab.length; i++)
tab[i] = null;
size = 0;
}
public void clear() {
Arrays.fill(table, null);
// Or: table = new Node[table.length];
}
public void put(long id, double lon, double lat) {
int position = Long.hashCode(id) & MASK;
for (Node n = table[position]; n != null; n = n.next) {
if (n.id == id) {
return;
}
}
table[position] = new Node(id, lon, lat, table[position]);
}
您應該編輯您的問題以包括該引號-評論不會引起問題;)-但我將嘗試根據java.util.HashMap
進行回答:
整體使用。 我不明白如何使用它來清除自己的哈希圖。 此外,modCount和本地選項卡數組
modCount
用作檢測並發修改的方法,當您嘗試遍歷映射時使用該方法。 您可以在HashMap的nextNode()
方法中看到一個用例:
final Node<K,V> nextNode() {
...
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
...
}
本地tab
數組是出於性能原因; 看到這個答案 。
將值設置為null
只是為了幫助gc知道您不再引用這些值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.