Any time you want to be able to do a reverse lookup without having to populate two maps. For instance a phone directory where you would like to lookup the phone number by name, but would also like to do a reverse lookup to get the name from the number.
Problems that we use a BiMap to solve
문제
I'm reviewing the capabilities of Googles Guava API and I ran into a data structure that I haven't seen used in my 'real world programming' experience, namely, the BiMap. Is the only benefit of this construct the ability to quickly retrieve a key, for a given value? Are there any problems where the solution is best expressed using a BiMap?
해결책
다른 팁
Louis mentioned the memory savings possible in a BiMap
implementation. That's the only thing that you can't get by wrapping two Map
instances. Still, if you let us wrap the Map
instances for you, we can take care of a few edges cases. (You could handle all these yourself, but why bother? :))
- If you call
put(newKey, existingValue)
, we'll error out immediately to keep the two maps in sync, rather than adding the entry to one map before realizing that it conflicts with an existing mapping in the other. (We provideforcePut
if you do want to override the existing value.) We provide similar safeguards for insertingnull
or other invalid values. BiMap
views keep the two maps in sync: If you remove an element from theentrySet
of the originalBiMap
, its corresponding entry is also removed from the inverse. We do the same kind of thing inEntry.setValue
.- We handle serialization: A
BiMap
and its inverse stay "connected," and the entries are serialized only once. - We provide a smart implementation of
inverse()
so thatfoo.inverse().inverse()
returnsfoo
, rather than a wrapper of a wrapper. - We override
values()
to return aSet
. This set is identical to what you'd get frominverse().keySet()
except that it maintains the same iteration order as the originalBiMap
.
제휴하지 않습니다 StackOverflow