[英]How to implement a Set Data Structure in Java?
我一直想知道您將如何在 Java 中實現一個 Set。我們能否像使用 LinkedList 和包含鍵和值的對象(單元格)實現 HashMap 一樣實現它? 您將如何處理唯一性部分?
基本上,一個 Set 只是一個只保存鍵的 Map。 因此,您應該了解映射算法。 注意:例如 HashSet 實際上只是 HashMap 的適配器。 HashSet 的添加方法僅使用 HashMap.put(value , SomeDummyValue)。
以下是解釋上述答案的代碼片段
public HashSet() { map = new HashMap<>(); }
private transient HashMap<E,Object> map;
// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
// Since PRESENT is a constant, for all keys we have same value in backup HashMap called map.
public Iterator<E> iterator() {
return map.keySet().iterator();
}
簡答:Map
首先是基礎
Set 數據結構有哪些特點?
O(1)
中。 如果我們仔細觀察,哪個數據結構可以實現它? 答案是Map
,因為我們只記錄當前的值。 我們可以在O(1)
時間內查詢。
class HashSetBasicImpl<K> {
static class Entry<K> {
private K key;
private Entry<K> next;
Entry(K key) {
key = key;
next = null;
}
}
private Entry<K>[] entries;
public HashSetBasicImpl() {
// fixed size
map =new Entry[100];
}
public boolean contains(K key) {
int idx = key.hashCode();
Entry<K> start = entries[idx];
while(start != null) {
if(start.key == key) {
return true;
}
start = start.next;
}
return false;
}
public boolean add(K key) {
Entry<K> entry = new Entry(key);
int idx = key.hashCode();
// check if entry exists
if(contains(key)) {
return false;
}
// add as first entry
start = entries[idx];
if(start == null) {
entries[idx]= new Entry(key);
return true;
}
// add as nth entry
Entry prev = null;
while(start != null) {
prev = start;
start = start.next;
}
prev.next = new Entry(key);
return true;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.