簡體   English   中英

如何在Java中實現一個集合數據結構?

[英]How to implement a Set Data Structure in Java?

我一直想知道您將如何在 Java 中實現一個 Set。我們能否像使用 LinkedList 和包含鍵和值的對象(單元格)實現 HashMap 一樣實現它? 您將如何處理唯一性部分?

Set內部實現了一個map,所以set中的每一個值都只是map中的一個key,所以它的唯一性得到了維護。

是鏈接。這樣您就可以清楚地了解 set 內部是如何工作的。 也很少堆棧答案。

基本上,一個 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 數據結構有哪些特點?

  1. 每個元素只存儲一次。
  2. 查詢 Set 中的項目應該是最快的,即在O(1)中。
  3. 如果要插入的項目已經存在於 Set 中,則不要插入。 如果不存在,則插入。

如果我們仔細觀察,哪個數據結構可以實現它? 答案是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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM