如何在java中创建一个2路地图 [英] How to create a 2 way map in java

查看:87
本文介绍了如何在java中创建一个2路地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个数据结构,以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(现在是 Guava )包含一个 BiMap 与几个实现界面。

The Google Collections (now a part of Guava) contains an BiMap interface with a few implementations.

BiMap 文档:


一个bimap(或双向地图)是
映射保留
的值的唯一性以及
键的唯一性。这个约束允许bimaps
支持一个反向视图,这是
另一个bimap包含与这个bimap相同的
条目,但
反转的键和值。

A bimap (or "bidirectional map") is a map that preserves the uniqueness of its values as well as that of its keys. This constraint enables bimaps to support an "inverse view", which is another bimap containing the same entries as this bimap but with reversed keys and values.

BiMap.inverse 方法似乎返回一个 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 方法文档:


返回此
bimap的反向视图,它将每个bimap的
值映射到其关联的ke y。两个
bimaps由相同的数据支持;
任何更改将出现在
其他。

Returns the inverse view of this bimap, which maps each of this bimap's values to its associated key. The two bimaps are backed by the same data; any changes to one will appear in the other.

这篇关于如何在java中创建一个2路地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆