Sorted hash table (map, dictionary) data structure design

前端 未结 6 943
猫巷女王i
猫巷女王i 2020-12-29 00:14

Here\'s a description of the data structure:

It operates like a regular map with get, put, and remove methods, but has a

6条回答
  •  再見小時候
    2020-12-29 00:24

    What you're looking at is a hashtable with pointers in the entries to the next entry in sorted order. It's a lot like the LinkedHashMap in java except that the links are tracking a sort order rather than the insertion order. You can actually implement this totally by wrapping a LinkedHashMap and having the implementation of sort transfer the entries from the LinkedHashMap into a TreeMap and then back into a LinkedHashMap.

    Here's an implementation that sorts the entries in an array list rather than transferring to a tree map. I think the sort algorithm used by Collection.sort will do a good job of merging the new entries into the already sorted portion.

    public class SortaSortedMap,V> implements Map {
    
        private LinkedHashMap innerMap;
    
        public SortaSortedMap() {
            this.innerMap = new LinkedHashMap();
        }
    
        public SortaSortedMap(Map map) {
            this.innerMap = new LinkedHashMap(map);
        }
    
        public Collection values() {
            return innerMap.values();
        }
    
        public int size() {
            return innerMap.size();
        }
    
        public V remove(Object key) {
            return innerMap.remove(key);
        }
    
        public V put(K key, V value) {
            return innerMap.put(key, value);
        }
    
        public Set keySet() {
            return innerMap.keySet();
        }
    
        public boolean isEmpty() {
            return innerMap.isEmpty();
        }
    
        public Set> entrySet() {
            return innerMap.entrySet();
        }
    
        public boolean containsKey(Object key) {
            return innerMap.containsKey(key);
        }
    
        public V get(Object key) {
            return innerMap.get(key);
        }
    
        public boolean containsValue(Object value) {
            return innerMap.containsValue(value);
        }
    
        public void clear() {
            innerMap.clear();
        }
    
        public void putAll(Map m) {
            innerMap.putAll(m);
        }
    
        public void sort() {
            List> entries = new ArrayList>(innerMap.entrySet());
            Collections.sort(entries, new KeyComparator());
            LinkedHashMap newMap = new LinkedHashMap();
            for (Map.Entry e: entries) {
                newMap.put(e.getKey(), e.getValue());
            }
            innerMap = newMap;
        }
    
        private class KeyComparator implements Comparator> {
    
            public int compare(Entry o1, Entry o2) {
                return o1.getKey().compareTo(o2.getKey());
            }
    
        }
    
    }
    

提交回复
热议问题