简体   繁体   English

Java中具有hashmap实现的电话簿

[英]Phone book with hashmap implementation in java

I have to make an app that would simulate a phone book in java, using hash map(s). 我必须制作一个使用哈希映射在Java中模拟电话簿的应用程序。 I want to implement 2 methods for search(enter a name to get a number and enter a number to get a name). 我想实现2种搜索方法(输入名称以获取数字并输入数字以获取名称)。

Is there any way to make both methods work with only 1 hash map defined like this HashMap<Person, Number> pb = new HashMap<>(); 是否有任何方法可以使这两种方法仅与定义的1个哈希映射一起工作,例如HashMap<Person, Number> pb = new HashMap<>(); (where Person and Number are classes)? (Person和Number是类)?

No you need 2 Maps in this case Map<Person, Number> and Map<Number, Person> if you want to have a fast access to your data with only one map you would need to iterate over the values which is of course much slower. 否,在这种情况下,您不需要2个Maps Map<Person, Number>Map<Number, Person>如果只想通过一张地图快速访问数据,则需要迭代这些值,这当然要慢得多。

You can also use a BiMap from Google guava to do both with one map 您也可以使用来自Google番石榴的BiMap来处理一张地图

A bimap (or "bidirectional map") is a map that preserves the uniqueness of its values as well as that of its keys. bimap(或“双向地图”)是一种保留其值以及其键的唯一性的地图。 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可以支持“反向视图”,这是另一个bimap,它包含与此bimap相同的条目,但具有相反的键和值

This can be done via a BidiMap (Bidirectional map) available with apache commons collection. 这可以通过apache commons集合中可用的BidiMap(双向地图)来完成。 See https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/BidiMap.html for more details. 有关更多详细信息,请参见https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/BidiMap.html But, in this case, names and numbers has to be unique. 但是,在这种情况下,名称和数字必须唯一。 If it is not possible, then you will either have to maintain two maps or use one map and iterate the values. 如果不可能,那么您要么必须维护两个映射,要么使用一个映射并迭代值。

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

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