Class TreeBidiMap
- All Implemented Interfaces:
Map
,BidiMap
,IterableMap
,OrderedBidiMap
,OrderedMap
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 java util 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:
- Commons Collections 3.0 (previously DoubleOrderedMap v2.0)
- Version:
- $Revision: 1713173 $ $Date: 2015-11-07 21:31:09 +0100 (Sat, 07 Nov 2015) $
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescription(package private) static class
A view of this map.(package private) static class
A node used to store the data.(package private) static class
A node used to store the data.(package private) static class
A view of this map.(package private) static class
An iterator over the map.(package private) static class
An iterator over the map. -
Field Summary
FieldsModifier and TypeFieldDescriptionprivate static final String[]
private Set
private static final int
private TreeBidiMap.Inverse
private static final int
private static final int
private Set
private static final int
private int
private int
private static final int
private TreeBidiMap.Node[]
private static final int
private static final int
private Set
-
Constructor Summary
ConstructorsConstructorDescriptionConstructs a new empty TreeBidiMap.TreeBidiMap
(Map map) Constructs a new TreeBidiMap by copying an existing Map. -
Method Summary
Modifier and TypeMethodDescriptionprivate static void
check a key for validity (non-null and implements Comparable)private static void
checkKeyAndValue
(Object key, Object value) check a key and a value for validity (non-null and implements Comparable)private static void
checkNonNullComparable
(Object o, int index) check if an object is fit to be proper input ...private static void
checkValue
(Object value) check a value for validity (non-null and implements Comparable)void
clear()
Removes all mappings from this map.private static int
compare
(Comparable o1, Comparable o2) Compare two objectsboolean
containsKey
(Object key) Checks whether this map contains the a mapping for the specified key.boolean
containsValue
(Object value) Checks whether this map contains the a mapping for the specified value.private static void
copyColor
(TreeBidiMap.Node from, TreeBidiMap.Node to, int index) copy the color from one node to another, dealing with the fact that one or both nodes may, in fact, be nullprivate boolean
Compares for equals as per the API.private Object
doGet
(Comparable obj, int index) Common get logic, used to get by key or get by valueprivate int
doHashCode
(int type) Gets the hash code value for this map as per the API.private Object
doPut
(Comparable key, Comparable value, int index) Common put logic, differing only in the return value.private void
doRedBlackDelete
(TreeBidiMap.Node deletedNode) complicated red-black delete stuff.private void
doRedBlackDeleteFixup
(TreeBidiMap.Node replacementNode, int index) complicated red-black delete stuff.private void
doRedBlackInsert
(TreeBidiMap.Node insertedNode, int index) complicated red-black insert stuff.private Object
doRemove
(Comparable o, int index) Remove by object (remove by key or remove by value)private String
doToString
(int type) Gets the string form of this map as per AbstractMap.entrySet()
Returns a set view of the entries contained in this map in key order.boolean
Compares for equals as per the API.firstKey()
Gets the first (lowest) key currently in this map.Gets the value to which this map maps the specified key.private static TreeBidiMap.Node
getGrandParent
(TreeBidiMap.Node node, int index) get a node's grandparent.Returns the key to which this map maps the specified value.private static TreeBidiMap.Node
getLeftChild
(TreeBidiMap.Node node, int index) get a node's left child.private static TreeBidiMap.Node
getParent
(TreeBidiMap.Node node, int index) get a node's parent.private static TreeBidiMap.Node
getRightChild
(TreeBidiMap.Node node, int index) get a node's right child.private static TreeBidiMap.Node
greatestNode
(TreeBidiMap.Node node, int index) Find the greatest node from a given node.private void
grow()
bump up the size and note that the map has changedint
hashCode()
Gets the hash code value for this map as per the API.private void
insertValue
(TreeBidiMap.Node newNode) insert a node by its valueGets the inverse map for comparison.Gets the inverse map for comparison.private static boolean
isBlack
(TreeBidiMap.Node node, int index) is the specified black red? if the node does not exist, sure, it's black, thank youboolean
isEmpty()
Checks whether the map is empty or not.private static boolean
isLeftChild
(TreeBidiMap.Node node, int index) is this node its parent's left child? mind you, the node, or its parent, may not exist.private static boolean
isRed
(TreeBidiMap.Node node, int index) is the specified node red? if the node does not exist, no, it's black, thank youprivate static boolean
isRightChild
(TreeBidiMap.Node node, int index) is this node its parent's right child? mind you, the node, or its parent, may not exist.keySet()
Returns a set view of the keys contained in this map in key order.lastKey()
Gets the last (highest) key currently in this map.private static TreeBidiMap.Node
leastNode
(TreeBidiMap.Node node, int index) Find the least node from a given node.private TreeBidiMap.Node
lookup
(Comparable data, int index) do the actual lookup of a piece of dataprivate static void
makeBlack
(TreeBidiMap.Node node, int index) force a node (if it exists) blackprivate static void
makeRed
(TreeBidiMap.Node node, int index) force a node (if it exists) redGets an iterator over the map entries.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 viewsprivate TreeBidiMap.Node
nextGreater
(TreeBidiMap.Node node, int index) get the next larger node from the specified nodeGets the next key after the one specified.private TreeBidiMap.Node
nextSmaller
(TreeBidiMap.Node node, int index) get the next larger node from the specified nodeprivate static int
oppositeIndex
(int index) Get the opposite index of the specified indexGets an ordered iterator over the map entries.previousKey
(Object key) Gets the previous key before the one specified.Puts the key-value pair into the map, replacing any previous pair.void
Puts all the mappings from the specified map into this map.Removes the mapping for this key from this map if present.removeValue
(Object value) Removes the mapping for this value from this map if present.private void
rotateLeft
(TreeBidiMap.Node node, int index) do a rotate left.private void
rotateRight
(TreeBidiMap.Node node, int index) do a rotate right.private void
shrink()
decrement the size and note that the map has changedint
size()
Returns the number of key-value mappings in this map.private void
swapPosition
(TreeBidiMap.Node x, TreeBidiMap.Node y, int index) swap two nodes (except for their content), taking care of special cases where one is the other's parent ...toString()
Returns a string version of this Map in standard format.values()
Returns a set view of the values contained in this map in key order.Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
Methods inherited from interface java.util.Map
compute, computeIfAbsent, computeIfPresent, forEach, getOrDefault, merge, putIfAbsent, remove, replace, replace, replaceAll
-
Field Details
-
KEY
private static final int KEY- See Also:
-
VALUE
private static final int VALUE- See Also:
-
MAPENTRY
private static final int MAPENTRY- See Also:
-
INVERSEMAPENTRY
private static final int INVERSEMAPENTRY- See Also:
-
SUM_OF_INDICES
private static final int SUM_OF_INDICES- See Also:
-
FIRST_INDEX
private static final int FIRST_INDEX- See Also:
-
NUMBER_OF_INDICES
private static final int NUMBER_OF_INDICES- See Also:
-
dataName
-
rootNode
-
nodeCount
private int nodeCount -
modifications
private int modifications -
keySet
-
valuesSet
-
entrySet
-
inverse
-
-
Constructor Details
-
TreeBidiMap
public TreeBidiMap()Constructs a new empty TreeBidiMap. -
TreeBidiMap
Constructs a new TreeBidiMap by copying an existing Map.- Parameters:
map
- the map to copy- Throws:
ClassCastException
- if the keys/values in the map are not Comparable or are not mutually comparableNullPointerException
- if any key or value in the map is null
-
-
Method Details
-
size
public int size()Returns the number of key-value mappings in this map. -
isEmpty
public boolean isEmpty()Checks whether the map is empty or not. -
containsKey
Checks whether this map contains the a mapping for the specified key.The key must implement
Comparable
.- Specified by:
containsKey
in interfaceMap
- 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:
ClassCastException
- if the key is of an inappropriate typeNullPointerException
- if the key is null
-
containsValue
Checks whether this map contains the a mapping for the specified value.The value must implement
Comparable
.- Specified by:
containsValue
in interfaceMap
- 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:
ClassCastException
- if the value is of an inappropriate typeNullPointerException
- if the value is null
-
get
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 interfaceMap
- 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:
ClassCastException
- if the key is of an inappropriate typeNullPointerException
- if the key is null
-
put
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 interfaceBidiMap
- Specified by:
put
in interfaceMap
- Parameters:
key
- key with which the specified value is to be associatedvalue
- value to be associated with the specified key- Returns:
- the previous value for the key
- Throws:
ClassCastException
- if the key is of an inappropriate typeNullPointerException
- if the key is null
-
putAll
Puts all the mappings from the specified map into this map.All keys and values must implement
Comparable
. -
remove
Removes the mapping for this key from this map if present.The key must implement
Comparable
.- Specified by:
remove
in interfaceMap
- 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:
ClassCastException
- if the key is of an inappropriate typeNullPointerException
- if the key is null
-
clear
public void clear()Removes all mappings from this map. -
getKey
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 interfaceBidiMap
- 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:
ClassCastException
- if the value is of an inappropriate typeNullPointerException
- if the value is null
-
removeValue
Removes the mapping for this value from this map if present.The value must implement
Comparable
.- Specified by:
removeValue
in interfaceBidiMap
- 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:
ClassCastException
- if the value is of an inappropriate typeNullPointerException
- if the value is null
-
firstKey
Gets the first (lowest) key currently in this map.- Specified by:
firstKey
in interfaceOrderedMap
- Returns:
- the first (lowest) key currently in this sorted map
- Throws:
NoSuchElementException
- if this map is empty
-
lastKey
Gets the last (highest) key currently in this map.- Specified by:
lastKey
in interfaceOrderedMap
- Returns:
- the last (highest) key currently in this sorted map
- Throws:
NoSuchElementException
- if this map is empty
-
nextKey
Gets the next key after the one specified.The key must implement
Comparable
.- Specified by:
nextKey
in interfaceOrderedMap
- Parameters:
key
- the key to search for next from- Returns:
- the next key, null if no match or at end
-
previousKey
Gets the previous key before the one specified.The key must implement
Comparable
.- Specified by:
previousKey
in interfaceOrderedMap
- Parameters:
key
- the key to search for previous from- Returns:
- the previous key, null if no match or at start
-
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.
-
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.
-
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.
-
mapIterator
Gets an iterator over the map entries.For this map, this iterator is the fastest way to iterate over the entries.
- Specified by:
mapIterator
in interfaceBidiMap
- Specified by:
mapIterator
in interfaceIterableMap
- Returns:
- an iterator
-
orderedMapIterator
Gets an ordered iterator over the map entries.This iterator allows both forward and reverse iteration over the entries.
- Specified by:
orderedMapIterator
in interfaceOrderedMap
- Returns:
- an iterator
-
inverseBidiMap
Gets the inverse map for comparison.- Specified by:
inverseBidiMap
in interfaceBidiMap
- Specified by:
inverseBidiMap
in interfaceOrderedBidiMap
- Returns:
- the inverse map
-
inverseOrderedBidiMap
Gets the inverse map for comparison.- Specified by:
inverseOrderedBidiMap
in interfaceOrderedBidiMap
- Returns:
- the inverse map
-
equals
Compares for equals as per the API. -
hashCode
public int hashCode()Gets the hash code value for this map as per the API. -
toString
Returns a string version of this Map in standard format. -
doGet
Common get logic, used to get by key or get by value- Parameters:
obj
- the key or value that we're looking forindex
- the KEY or VALUE int- Returns:
- the key (if the value was mapped) or the value (if the key was mapped); null if we couldn't find the specified object
-
doPut
Common put logic, differing only in the return value.- Parameters:
key
- the key, always the main map keyvalue
- the value, always the main map valueindex
- the KEY or VALUE int, for the return value only- Returns:
- the previously mapped value
-
doRemove
Remove by object (remove by key or remove by value)- Parameters:
o
- the key, or value, that we're looking forindex
- the KEY or VALUE int- Returns:
- the key, if remove by value, or the value, if remove by key. null if the specified key or value could not be found
-
lookup
do the actual lookup of a piece of data- Parameters:
data
- the key or value to be looked upindex
- the KEY or VALUE int- Returns:
- the desired Node, or null if there is no mapping of the specified data
-
nextGreater
get the next larger node from the specified node- Parameters:
node
- the node to be searched fromindex
- the KEY or VALUE int- Returns:
- the specified node
-
nextSmaller
get the next larger node from the specified node- Parameters:
node
- the node to be searched fromindex
- the KEY or VALUE int- Returns:
- the specified node
-
oppositeIndex
private static int oppositeIndex(int index) Get the opposite index of the specified index- Parameters:
index
- the KEY or VALUE int- Returns:
- VALUE (if KEY was specified), else KEY
-
compare
Compare two objects- Parameters:
o1
- the first objecto2
- the second object- Returns:
- negative value if o1 < o2; 0 if o1 == o2; positive value if o1 > o2
-
leastNode
Find the least node from a given node.- Parameters:
node
- the node from which we will start searchingindex
- the KEY or VALUE int- Returns:
- the smallest node, from the specified node, in the specified mapping
-
greatestNode
Find the greatest node from a given node.- Parameters:
node
- the node from which we will start searchingindex
- the KEY or VALUE int- Returns:
- the greatest node, from the specified node
-
copyColor
copy the color from one node to another, dealing with the fact that one or both nodes may, in fact, be null- Parameters:
from
- the node whose color we're copying; may be nullto
- the node whose color we're changing; may be nullindex
- the KEY or VALUE int
-
isRed
is the specified node red? if the node does not exist, no, it's black, thank you- Parameters:
node
- the node (may be null) in questionindex
- the KEY or VALUE int
-
isBlack
is the specified black red? if the node does not exist, sure, it's black, thank you- Parameters:
node
- the node (may be null) in questionindex
- the KEY or VALUE int
-
makeRed
force a node (if it exists) red- Parameters:
node
- the node (may be null) in questionindex
- the KEY or VALUE int
-
makeBlack
force a node (if it exists) black- Parameters:
node
- the node (may be null) in questionindex
- the KEY or VALUE int
-
getGrandParent
get a node's grandparent. mind you, the node, its parent, or its grandparent may not exist. no problem- Parameters:
node
- the node (may be null) in questionindex
- the KEY or VALUE int
-
getParent
get a node's parent. mind you, the node, or its parent, may not exist. no problem- Parameters:
node
- the node (may be null) in questionindex
- the KEY or VALUE int
-
getRightChild
get a node's right child. mind you, the node may not exist. no problem- Parameters:
node
- the node (may be null) in questionindex
- the KEY or VALUE int
-
getLeftChild
get a node's left child. mind you, the node may not exist. no problem- Parameters:
node
- the node (may be null) in questionindex
- the KEY or VALUE int
-
isLeftChild
is this node its parent's left child? mind you, the node, or its parent, may not exist. no problem. if the node doesn't exist ... it's its non-existent parent's left child. If the node does exist but has no parent ... no, we're not the non-existent parent's left child. Otherwise (both the specified node AND its parent exist), check.- Parameters:
node
- the node (may be null) in questionindex
- the KEY or VALUE int
-
isRightChild
is this node its parent's right child? mind you, the node, or its parent, may not exist. no problem. if the node doesn't exist ... it's its non-existent parent's right child. If the node does exist but has no parent ... no, we're not the non-existent parent's right child. Otherwise (both the specified node AND its parent exist), check.- Parameters:
node
- the node (may be null) in questionindex
- the KEY or VALUE int
-
rotateLeft
do a rotate left. standard fare in the world of balanced trees- Parameters:
node
- the node to be rotatedindex
- the KEY or VALUE int
-
rotateRight
do a rotate right. standard fare in the world of balanced trees- Parameters:
node
- the node to be rotatedindex
- the KEY or VALUE int
-
doRedBlackInsert
complicated red-black insert stuff. Based on Sun's TreeMap implementation, though it's barely recognizable any more- Parameters:
insertedNode
- the node to be insertedindex
- the KEY or VALUE int
-
doRedBlackDelete
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
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 replacedindex
- the KEY or VALUE int
-
swapPosition
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 nodey
- another nodeindex
- the KEY or VALUE int
-
checkNonNullComparable
check if an object is fit to be proper input ... has to be Comparable and non-null- Parameters:
o
- the object being checkedindex
- the KEY or VALUE int (used to put the right word in the exception message)- Throws:
NullPointerException
- if o is nullClassCastException
- if o is not Comparable
-
checkKey
check a key for validity (non-null and implements Comparable)- Parameters:
key
- the key to be checked- Throws:
NullPointerException
- if key is nullClassCastException
- if key is not Comparable
-
checkValue
check a value for validity (non-null and implements Comparable)- Parameters:
value
- the value to be checked- Throws:
NullPointerException
- if value is nullClassCastException
- if value is not Comparable
-
checkKeyAndValue
check a key and a value for validity (non-null and implements Comparable)- Parameters:
key
- the key to be checkedvalue
- the value to be checked- Throws:
NullPointerException
- if key or value is nullClassCastException
- 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
insert a node by its value- Parameters:
newNode
- the node to be inserted- Throws:
IllegalArgumentException
- if the node already exists in the value mapping
-
doEquals
Compares for equals as per the API.- Parameters:
obj
- the object to compare totype
- the KEY or VALUE int- Returns:
- true if equal
-
doHashCode
private int doHashCode(int type) Gets the hash code value for this map as per the API.- Parameters:
type
- the KEY or VALUE int- Returns:
- the hash code value for this map
-
doToString
Gets the string form of this map as per AbstractMap.- Parameters:
type
- the KEY or VALUE int- Returns:
- the string form of this map
-