Class TreeBidiMap<K extends java.lang.Comparable<K>,​V extends java.lang.Comparable<V>>

  • Type Parameters:
    K - the type of the keys in this map
    V - the type of the values in this map
    All Implemented Interfaces:
    java.io.Serializable, java.util.Map<K,​V>, BidiMap<K,​V>, Get<K,​V>, IterableGet<K,​V>, IterableMap<K,​V>, OrderedBidiMap<K,​V>, OrderedMap<K,​V>, Put<K,​V>

    public class TreeBidiMap<K extends java.lang.Comparable<K>,​V extends java.lang.Comparable<V>>
    extends java.lang.Object
    implements OrderedBidiMap<K,​V>, java.io.Serializable
    Red-Black tree-based implementation of BidiMap where all objects added implement the Comparable interface.

    This class guarantees that the map will be in both ascending key order and ascending value order, sorted according to the natural order for the key's and value's classes.

    This Map is intended for applications that need to be able to look up a key-value pairing by either key or value, and need to do so with equal efficiency.

    While that goal could be accomplished by taking a pair of TreeMaps and redirecting requests to the appropriate TreeMap (e.g., containsKey would be directed to the TreeMap that maps values to keys, containsValue would be directed to the TreeMap that maps keys to values), there are problems with that implementation. If the data contained in the TreeMaps is large, the cost of redundant storage becomes significant. The DualTreeBidiMap and DualHashBidiMap implementations use this approach.

    This solution keeps minimizes the data storage by holding data only once. The red-black algorithm is based on TreeMap, but has been modified to simultaneously map a tree node by key and by value. This doubles the cost of put operations (but so does using two TreeMaps), and nearly doubles the cost of remove operations (there is a savings in that the lookup of the node to be removed only has to be performed once). And since only one node contains the key and value, storage is significantly less than that required by two TreeMaps.

    The Map.Entry instances returned by the appropriate methods will not allow setValue() and will throw an UnsupportedOperationException on attempts to call that method.

    Since:
    3.0 (previously DoubleOrderedMap v2.0)
    See Also:
    Serialized Form
    • Field Detail

      • rootNode

        private transient TreeBidiMap.Node<K extends java.lang.Comparable<K>,​V extends java.lang.Comparable<V>>[] rootNode
      • nodeCount

        private transient int nodeCount
      • modifications

        private transient int modifications
      • keySet

        private transient java.util.Set<K extends java.lang.Comparable<K>> keySet
      • valuesSet

        private transient java.util.Set<V extends java.lang.Comparable<V>> valuesSet
      • entrySet

        private transient java.util.Set<java.util.Map.Entry<K extends java.lang.Comparable<K>,​V extends java.lang.Comparable<V>>> entrySet
    • Constructor Detail

      • TreeBidiMap

        public TreeBidiMap()
        Constructs a new empty TreeBidiMap.
      • TreeBidiMap

        public TreeBidiMap​(java.util.Map<? extends K,​? extends V> map)
        Constructs a new TreeBidiMap by copying an existing Map.
        Parameters:
        map - the map to copy
        Throws:
        java.lang.ClassCastException - if the keys/values in the map are not Comparable or are not mutually comparable
        java.lang.NullPointerException - if any key or value in the map is null
    • Method Detail

      • size

        public int size()
        Returns the number of key-value mappings in this map.
        Specified by:
        size in interface Get<K extends java.lang.Comparable<K>,​V extends java.lang.Comparable<V>>
        Specified by:
        size in interface java.util.Map<K extends java.lang.Comparable<K>,​V extends java.lang.Comparable<V>>
        Returns:
        the number of key-value mappings in this map
        See Also:
        Map.size()
      • isEmpty

        public boolean isEmpty()
        Checks whether the map is empty or not.
        Specified by:
        isEmpty in interface Get<K extends java.lang.Comparable<K>,​V extends java.lang.Comparable<V>>
        Specified by:
        isEmpty in interface java.util.Map<K extends java.lang.Comparable<K>,​V extends java.lang.Comparable<V>>
        Returns:
        true if the map is empty
        See Also:
        Map.isEmpty()
      • containsKey

        public boolean containsKey​(java.lang.Object key)
        Checks whether this map contains the a mapping for the specified key.

        The key must implement Comparable.

        Specified by:
        containsKey in interface Get<K extends java.lang.Comparable<K>,​V extends java.lang.Comparable<V>>
        Specified by:
        containsKey in interface java.util.Map<K extends java.lang.Comparable<K>,​V extends java.lang.Comparable<V>>
        Parameters:
        key - key whose presence in this map is to be tested
        Returns:
        true if this map contains a mapping for the specified key
        Throws:
        java.lang.ClassCastException - if the key is of an inappropriate type
        java.lang.NullPointerException - if the key is null
        See Also:
        Map.containsKey(Object)
      • containsValue

        public boolean containsValue​(java.lang.Object value)
        Checks whether this map contains the a mapping for the specified value.

        The value must implement Comparable.

        Specified by:
        containsValue in interface Get<K extends java.lang.Comparable<K>,​V extends java.lang.Comparable<V>>
        Specified by:
        containsValue in interface java.util.Map<K extends java.lang.Comparable<K>,​V extends java.lang.Comparable<V>>
        Parameters:
        value - value whose presence in this map is to be tested
        Returns:
        true if this map contains a mapping for the specified value
        Throws:
        java.lang.ClassCastException - if the value is of an inappropriate type
        java.lang.NullPointerException - if the value is null
        See Also:
        Map.containsValue(Object)
      • get

        public V get​(java.lang.Object key)
        Gets the value to which this map maps the specified key. Returns null if the map contains no mapping for this key.

        The key must implement Comparable.

        Specified by:
        get in interface Get<K extends java.lang.Comparable<K>,​V extends java.lang.Comparable<V>>
        Specified by:
        get in interface java.util.Map<K extends java.lang.Comparable<K>,​V extends java.lang.Comparable<V>>
        Parameters:
        key - key whose associated value is to be returned
        Returns:
        the value to which this map maps the specified key, or null if the map contains no mapping for this key
        Throws:
        java.lang.ClassCastException - if the key is of an inappropriate type
        java.lang.NullPointerException - if the key is null
        See Also:
        Map.get(Object)
      • put

        public V put​(K key,
                     V value)
        Puts the key-value pair into the map, replacing any previous pair.

        When adding a key-value pair, the value may already exist in the map against a different key. That mapping is removed, to ensure that the value only occurs once in the inverse map.

          BidiMap map1 = new TreeBidiMap();
          map.put("A","B");  // contains A mapped to B, as per Map
          map.put("A","C");  // contains A mapped to C, as per Map
        
          BidiMap map2 = new TreeBidiMap();
          map.put("A","B");  // contains A mapped to B, as per Map
          map.put("C","B");  // contains C mapped to B, key A is removed
         

        Both key and value must implement Comparable.

        Specified by:
        put in interface BidiMap<K extends java.lang.Comparable<K>,​V extends java.lang.Comparable<V>>
        Specified by:
        put in interface java.util.Map<K extends java.lang.Comparable<K>,​V extends java.lang.Comparable<V>>
        Specified by:
        put in interface Put<K extends java.lang.Comparable<K>,​V extends java.lang.Comparable<V>>
        Parameters:
        key - key with which the specified value is to be associated
        value - value to be associated with the specified key
        Returns:
        the previous value for the key
        Throws:
        java.lang.ClassCastException - if the key is of an inappropriate type
        java.lang.NullPointerException - if the key is null
        See Also:
        Map.put(Object, Object)
      • putAll

        public void putAll​(java.util.Map<? extends K,​? extends V> map)
        Puts all the mappings from the specified map into this map.

        All keys and values must implement Comparable.

        Specified by:
        putAll in interface java.util.Map<K extends java.lang.Comparable<K>,​V extends java.lang.Comparable<V>>
        Specified by:
        putAll in interface Put<K extends java.lang.Comparable<K>,​V extends java.lang.Comparable<V>>
        Parameters:
        map - the map to copy from
        See Also:
        Map.putAll(Map)
      • remove

        public V remove​(java.lang.Object key)
        Removes the mapping for this key from this map if present.

        The key must implement Comparable.

        Specified by:
        remove in interface Get<K extends java.lang.Comparable<K>,​V extends java.lang.Comparable<V>>
        Specified by:
        remove in interface java.util.Map<K extends java.lang.Comparable<K>,​V extends java.lang.Comparable<V>>
        Parameters:
        key - key whose mapping is to be removed from the map.
        Returns:
        previous value associated with specified key, or null if there was no mapping for key.
        Throws:
        java.lang.ClassCastException - if the key is of an inappropriate type
        java.lang.NullPointerException - if the key is null
        See Also:
        Map.remove(Object)
      • clear

        public void clear()
        Removes all mappings from this map.
        Specified by:
        clear in interface java.util.Map<K extends java.lang.Comparable<K>,​V extends java.lang.Comparable<V>>
        Specified by:
        clear in interface Put<K extends java.lang.Comparable<K>,​V extends java.lang.Comparable<V>>
        See Also:
        Map.clear()
      • getKey

        public K getKey​(java.lang.Object value)
        Returns the key to which this map maps the specified value. Returns null if the map contains no mapping for this value.

        The value must implement Comparable.

        Specified by:
        getKey in interface BidiMap<K extends java.lang.Comparable<K>,​V extends java.lang.Comparable<V>>
        Parameters:
        value - value whose associated key is to be returned.
        Returns:
        the key to which this map maps the specified value, or null if the map contains no mapping for this value.
        Throws:
        java.lang.ClassCastException - if the value is of an inappropriate type
        java.lang.NullPointerException - if the value is null
      • removeValue

        public K removeValue​(java.lang.Object value)
        Removes the mapping for this value from this map if present.

        The value must implement Comparable.

        Specified by:
        removeValue in interface BidiMap<K extends java.lang.Comparable<K>,​V extends java.lang.Comparable<V>>
        Parameters:
        value - value whose mapping is to be removed from the map
        Returns:
        previous key associated with specified value, or null if there was no mapping for value.
        Throws:
        java.lang.ClassCastException - if the value is of an inappropriate type
        java.lang.NullPointerException - if the value is null
      • firstKey

        public K firstKey()
        Gets the first (lowest) key currently in this map.
        Specified by:
        firstKey in interface OrderedMap<K extends java.lang.Comparable<K>,​V extends java.lang.Comparable<V>>
        Returns:
        the first (lowest) key currently in this sorted map
        Throws:
        java.util.NoSuchElementException - if this map is empty
      • lastKey

        public K lastKey()
        Gets the last (highest) key currently in this map.
        Specified by:
        lastKey in interface OrderedMap<K extends java.lang.Comparable<K>,​V extends java.lang.Comparable<V>>
        Returns:
        the last (highest) key currently in this sorted map
        Throws:
        java.util.NoSuchElementException - if this map is empty
      • nextKey

        public K nextKey​(K key)
        Gets the next key after the one specified.

        The key must implement Comparable.

        Specified by:
        nextKey in interface OrderedMap<K extends java.lang.Comparable<K>,​V extends java.lang.Comparable<V>>
        Parameters:
        key - the key to search for next from
        Returns:
        the next key, null if no match or at end
      • previousKey

        public K previousKey​(K key)
        Gets the previous key before the one specified.

        The key must implement Comparable.

        Specified by:
        previousKey in interface OrderedMap<K extends java.lang.Comparable<K>,​V extends java.lang.Comparable<V>>
        Parameters:
        key - the key to search for previous from
        Returns:
        the previous key, null if no match or at start
      • keySet

        public java.util.Set<K> keySet()
        Returns a set view of the keys contained in this map in key order.

        The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress, the results of the iteration are undefined.

        The set supports element removal, which removes the corresponding mapping from the map. It does not support the add or addAll operations.

        Specified by:
        keySet in interface Get<K extends java.lang.Comparable<K>,​V extends java.lang.Comparable<V>>
        Specified by:
        keySet in interface java.util.Map<K extends java.lang.Comparable<K>,​V extends java.lang.Comparable<V>>
        Returns:
        a set view of the keys contained in this map.
        See Also:
        Map.keySet()
      • values

        public java.util.Set<V> values()
        Returns a set view of the values contained in this map in key order. The returned object can be cast to a Set.

        The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress, the results of the iteration are undefined.

        The set supports element removal, which removes the corresponding mapping from the map. It does not support the add or addAll operations.

        Specified by:
        values in interface BidiMap<K extends java.lang.Comparable<K>,​V extends java.lang.Comparable<V>>
        Specified by:
        values in interface Get<K extends java.lang.Comparable<K>,​V extends java.lang.Comparable<V>>
        Specified by:
        values in interface java.util.Map<K extends java.lang.Comparable<K>,​V extends java.lang.Comparable<V>>
        Returns:
        a set view of the values contained in this map.
        See Also:
        Map.values()
      • entrySet

        public java.util.Set<java.util.Map.Entry<K,​V>> entrySet()
        Returns a set view of the entries contained in this map in key order. For simple iteration through the map, the MapIterator is quicker.

        The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress, the results of the iteration are undefined.

        The set supports element removal, which removes the corresponding mapping from the map. It does not support the add or addAll operations. The returned MapEntry objects do not support setValue.

        Specified by:
        entrySet in interface Get<K extends java.lang.Comparable<K>,​V extends java.lang.Comparable<V>>
        Specified by:
        entrySet in interface java.util.Map<K extends java.lang.Comparable<K>,​V extends java.lang.Comparable<V>>
        Returns:
        a set view of the values contained in this map.
        See Also:
        Map.entrySet()
      • mapIterator

        public OrderedMapIterator<K,​V> mapIterator()
        Description copied from interface: IterableGet
        Obtains a MapIterator over the map.

        A map iterator is an efficient way of iterating over maps. There is no need to access the entry set or use Map Entry objects.

         IterableMap<String,Integer> map = new HashedMap<String,Integer>();
         MapIterator<String,Integer> it = map.mapIterator();
         while (it.hasNext()) {
           String key = it.next();
           Integer value = it.getValue();
           it.setValue(value + 1);
         }
         
        Specified by:
        mapIterator in interface IterableGet<K extends java.lang.Comparable<K>,​V extends java.lang.Comparable<V>>
        Specified by:
        mapIterator in interface OrderedMap<K extends java.lang.Comparable<K>,​V extends java.lang.Comparable<V>>
        Returns:
        a map iterator
      • inverseBidiMap

        public OrderedBidiMap<V,​K> inverseBidiMap()
        Gets the inverse map for comparison.
        Specified by:
        inverseBidiMap in interface BidiMap<K extends java.lang.Comparable<K>,​V extends java.lang.Comparable<V>>
        Specified by:
        inverseBidiMap in interface OrderedBidiMap<K extends java.lang.Comparable<K>,​V extends java.lang.Comparable<V>>
        Returns:
        the inverse map
      • equals

        public boolean equals​(java.lang.Object obj)
        Compares for equals as per the API.
        Specified by:
        equals in interface java.util.Map<K extends java.lang.Comparable<K>,​V extends java.lang.Comparable<V>>
        Overrides:
        equals in class java.lang.Object
        Parameters:
        obj - the object to compare to
        Returns:
        true if equal
      • hashCode

        public int hashCode()
        Gets the hash code value for this map as per the API.
        Specified by:
        hashCode in interface java.util.Map<K extends java.lang.Comparable<K>,​V extends java.lang.Comparable<V>>
        Overrides:
        hashCode in class java.lang.Object
        Returns:
        the hash code value for this map
      • toString

        public java.lang.String toString()
        Returns a string version of this Map in standard format.
        Overrides:
        toString in class java.lang.Object
        Returns:
        a standard format string version of the map
      • doPut

        private void doPut​(K key,
                           V value)
        Put logic.
        Parameters:
        key - the key, always the main map key
        value - the value, always the main map value
      • doRemoveKey

        private V doRemoveKey​(java.lang.Object key)
      • doRemoveValue

        private K doRemoveValue​(java.lang.Object value)
      • lookup

        private <T extends java.lang.Comparable<T>> TreeBidiMap.Node<K,​V> lookup​(java.lang.Object data,
                                                                                       TreeBidiMap.DataElement dataElement)
        do the actual lookup of a piece of data
        Parameters:
        data - the key or value to be looked up
        dataElement - either TreeBidiMap.DataElement.KEY key} or the value.
        Returns:
        the desired Node, or null if there is no mapping of the specified data
      • compare

        private static <T extends java.lang.Comparable<T>> int compare​(T o1,
                                                                       T o2)
        Compare two objects
        Parameters:
        o1 - the first object
        o2 - the second object
        Returns:
        negative value if o1 < o2; 0 if o1 == o2; positive value if o1 > o2
      • doRedBlackInsert

        private void doRedBlackInsert​(TreeBidiMap.Node<K,​V> insertedNode,
                                      TreeBidiMap.DataElement dataElement)
        complicated red-black insert stuff. Based on Sun's TreeMap implementation, though it's barely recognizable any more
        Parameters:
        insertedNode - the node to be inserted
        dataElement - the KEY or VALUE int
      • doRedBlackDelete

        private void doRedBlackDelete​(TreeBidiMap.Node<K,​V> deletedNode)
        complicated red-black delete stuff. Based on Sun's TreeMap implementation, though it's barely recognizable any more
        Parameters:
        deletedNode - the node to be deleted
      • doRedBlackDeleteFixup

        private void doRedBlackDeleteFixup​(TreeBidiMap.Node<K,​V> replacementNode,
                                           TreeBidiMap.DataElement dataElement)
        complicated red-black delete stuff. Based on Sun's TreeMap implementation, though it's barely recognizable any more. This rebalances the tree (somewhat, as red-black trees are not perfectly balanced -- perfect balancing takes longer)
        Parameters:
        replacementNode - the node being replaced
        dataElement - the KEY or VALUE int
      • swapPosition

        private void swapPosition​(TreeBidiMap.Node<K,​V> x,
                                  TreeBidiMap.Node<K,​V> y,
                                  TreeBidiMap.DataElement dataElement)
        swap two nodes (except for their content), taking care of special cases where one is the other's parent ... hey, it happens.
        Parameters:
        x - one node
        y - another node
        dataElement - the KEY or VALUE int
      • checkNonNullComparable

        private static void checkNonNullComparable​(java.lang.Object o,
                                                   TreeBidiMap.DataElement dataElement)
        check if an object is fit to be proper input ... has to be Comparable and non-null
        Parameters:
        o - the object being checked
        dataElement - either TreeBidiMap.DataElement.KEY key} or the value.
        Throws:
        java.lang.NullPointerException - if o is null
        java.lang.ClassCastException - if o is not Comparable
      • checkKey

        private static void checkKey​(java.lang.Object key)
        check a key for validity (non-null and implements Comparable)
        Parameters:
        key - the key to be checked
        Throws:
        java.lang.NullPointerException - if key is null
        java.lang.ClassCastException - if key is not Comparable
      • checkValue

        private static void checkValue​(java.lang.Object value)
        check a value for validity (non-null and implements Comparable)
        Parameters:
        value - the value to be checked
        Throws:
        java.lang.NullPointerException - if value is null
        java.lang.ClassCastException - if value is not Comparable
      • checkKeyAndValue

        private static void checkKeyAndValue​(java.lang.Object key,
                                             java.lang.Object value)
        check a key and a value for validity (non-null and implements Comparable)
        Parameters:
        key - the key to be checked
        value - the value to be checked
        Throws:
        java.lang.NullPointerException - if key or value is null
        java.lang.ClassCastException - if key or value is not Comparable
      • modify

        private void modify()
        increment the modification count -- used to check for concurrent modification of the map through the map and through an Iterator from one of its Set or Collection views
      • grow

        private void grow()
        bump up the size and note that the map has changed
      • shrink

        private void shrink()
        decrement the size and note that the map has changed
      • insertValue

        private void insertValue​(TreeBidiMap.Node<K,​V> newNode)
                          throws java.lang.IllegalArgumentException
        insert a node by its value
        Parameters:
        newNode - the node to be inserted
        Throws:
        java.lang.IllegalArgumentException - if the node already exists in the value mapping
      • readObject

        private void readObject​(java.io.ObjectInputStream stream)
                         throws java.io.IOException,
                                java.lang.ClassNotFoundException
        Reads the content of the stream.
        Parameters:
        stream - the input stream
        Throws:
        java.io.IOException - if an error occurs while reading from the stream
        java.lang.ClassNotFoundException - if an object read from the stream can not be loaded
      • writeObject

        private void writeObject​(java.io.ObjectOutputStream stream)
                          throws java.io.IOException
        Writes the content to the stream for serialization.
        Parameters:
        stream - the output stream
        Throws:
        java.io.IOException - if an error occurs while writing to the stream