简体   繁体   English

如何在哈希表中关联多个值-Java

[英]How to associate multiple values inside a hashtable - java

I am trying to implement a basic phonebook using a hashtable made from scratch i made but when adding a contact i will need to store atleast 2 informations, the name and number of each person. 我正在尝试使用从头开始制作的哈希表来实现基本的电话簿,但是添加联系人时,我将需要存储至少2条信息,即每个人的姓名和电话号码。

The problem is when adding the info into the hashtable i can only do it like x.insert(name) and x.insert(number) witch will result in 2 different keys and i cant find away to associate the two values within the hashtable. 问题是,当将信息添加到哈希表中时,我只能像x.insert(name)和x.insert(number)这样来做,这将导致2个不同的键,而我找不到在哈希表中关联这两个值的方法。 Is this even possible to do? 这有可能吗?

If needed i can provide the code. 如果需要,我可以提供代码。

PS: the hashtable i made has the methods: insert(y),remove(y),find(y),print() PS:我制作的哈希表具有以下方法:insert(y),remove(y),find(y),print()

Thanks in advance. 提前致谢。

as said by @hnefatl in a comment, create some class: 如@hnefatl在评论中所说,创建一些类:

public class PhoneBookInfos {
    public String Name;
    public String Number;
}

and your hashtable/HashMap would be: 并且您的hashtable / HashMap将是:

Map<Integer, PhoneBookInfos> myPhoneBook = new HashMap<Integer, PhoneBookInfos>();

updated after @hnefatl's comment @hnefatl评论后更新

The insert function could check to see if the key exists, retrieve the object, and then add the missing field, and add that object back into the hashtable. insert函数可以检查该键是否存在,检索对象,然后添加缺少的字段,然后将该对象添加回哈希表中。 Otherwise create the object with only the name or number, and add that into the hashtable. 否则,仅使用名称或数字创建对象,然后将其添加到哈希表中。

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

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