简体   繁体   English

一致且高效的双向数据结构实现(Java)

[英]Consistent and efficient bi-directional data structure implementation (Java)

I needed an implementation of a bi-directional map in Java so I tried to use BiMap and BidiMap from Guava and Commons. 我需要用Java实现双向地图,因此我尝试使用Guava和Commons中的BiMap和BidiMap。 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的示例(与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. 当然,对于使用HashMaps的实现来说,这种行为是可以预期的,但是它说明了问题。

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. 即,一种数据结构允许双向绑定,可变密钥并具有合理的时间复杂度。

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). 实际上,从根本上要求键至少在其equalshashCode方法(在哈希表支持的映射的情况下)或其比较方法(在二进制树支持的映射的情况下)的行为方面保持稳定。

Perhaps you can consider removing an element, changing it, then inserting it back—that's one way to meet the constraints of implementation. 也许您可以考虑删除一个元素,进行更改,然后再将其插入回去,这是满足实现约束的一种方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM