0

I needed an implementation of a bi-directional map in Java so I tried to use BiMap and BidiMap from Guava and Commons. However, the inverse view capability is not maintained after a modification on an element. Here is an example with BiMap (same behavior with BidiMap) :

BiMap<Set<String>, Set<String>> map = HashBiMap.create();

Set<String> foo = new HashSet<>();
foo.add("foo");

Set<String> bar = new HashSet<>();
bar.add("bar");

map.put(foo, bar);

map.get(foo); // returns [bar], ok
map.inverse().get(map.get(foo)); // returns [foo], ok

map.get(foo).add("someString");

map.get(foo); // returns [bar, someString], ok
map.inverse().get(map.get(foo)); // returns null, not ok <=

Of course this behavior can be expected for an implementation using HashMaps but it illustrates the problem.

So the question is, is there a bi-directional data structure which can handle this kind of situation, with elements of arbitrary types, and still have a better average time complexity than an array of pairs?

EDIT : I'm not trying to solve this problem or avoid it, this is more of an academic question. I just want to know if such a data structure exists. That is, a data structure allowing bi-directional binding, mutable keys and with reasonable time complexity.

Bastien
  • 658
  • 1
  • 9
  • 24
  • Instead of changing the object in the map, or in addition, perhaps you should re-add it to the map to re-adjust the keys. – RealSkeptic Aug 31 '15 at 13:45
  • Or wrap the `Set<>` in some object that is stable wrt. hashCode & comparability. E.g. simply `class Wrapper { Set<> wrapped = .. }` – zapl Aug 31 '15 at 13:52

1 Answers1

3

Your trouble is not with bidirectional maps, but with the assumption that you are allowed to modify a map key. Keys are in fact fundamentally required to be stable at least regarding the behavior of their equals and hashCode methods (in case of a hashtable-backed map) or their comparison method (in case of a binary tree-backed map).

Perhaps you can consider removing an element, changing it, then inserting it back—that's one way to meet the constraints of implementation.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
  • Thank you but I'm not trying to solve this problem or avoid it, this is more of an academic question. I just wanted to know if such a data structure exists. That is, a data structure allowing bi-directional binding, mutable keys and with reasonable time complexity. – Bastien Aug 31 '15 at 13:54
  • 1
    If you mean a structure that can work in spite of its internals being messed with from the outside, then of course it doesn't exist. The structure _must_ know when you're changing the keys---and if it does, then hashtable is already the structure that satisfies your requirement. – Marko Topolnik Aug 31 '15 at 13:58