问题描述
我需要一个数据结构,以1:1的关系存储string-int值对,并且可以从任何一种方式查找对应的
I need a data structure to store string-int value pairs in an 1:1 relationship, and being able too look up from either way their counterpart.
I用Hashtable和String数组写了一个类,并将数据存储2次并使用内建的函数进行查找。
I wrote a class with a Hashtable and a String array and stored the data 2 times and used the built in functions for lookup.
我的问题是有更好的方法完成这个而且更好的是,我的意思是高效,而不是存储数据2次,最好不要编写一堆代码:P。
My question is that is there a nicer way to accomplish this? And by nicer I mean being efficient and not storing the data 2 times, and preferably without writing a ton of code either :P.
推荐答案
p>看起来你可能正在寻找一个折价。
It seems like you may be looking for a bimap.
Google Collections(现在是)包含一个与几个实现界面。
The Google Collections (now a part of Guava) contains an BiMap
interface with a few implementations.
从 BiMap
文档:
方法似乎返回一个 Map
将值作为键,并将键作为值,以便 Map
可用于调用 get
上的值并检索一个密钥。
The BiMap.inverse
method appears to return a Map
with the values as the keys, and the keys as the values, so that Map
can be used to call get
on the value and retrieve a key.
另外由 Map > inverse 是基础数据的视图,因此不需要复制原始数据。
In addition the Map
returned by inverse
is a view of the underlying data, so it does not have to make extra copies of the original data.
从 BiMap.inverse
方法文档:
这篇关于如何在java中创建一个2路地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!