简体   繁体   中英

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.

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. 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()

Thanks in advance.

as said by @hnefatl in a comment, create some class:

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

and your hashtable/HashMap would be:

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

updated after @hnefatl's comment

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. Otherwise create the object with only the name or number, and add that into the hashtable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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