Java – data structure with bidirectional o (1) lookup Hash table?
I'm implementing a system. I have a list. Everyone has a phone number I need to be able to take a name and find a phone number, or take a phone number and find a name
I know I can do this through two hash tables - one from name to phone number and one from phone number to name Then I can look in any direction at O (1) time However, it seems that I have stored too much data - twice for each name and phone number
Is there any way to do this more effectively? What data structure should I use to store names and phone numbers?
If relevant, I use java coding
Thank you.
Solution
Java does not provide a two - way hash table out of the box Unless you are willing to use a third-party library (which will hide two hash tables for you) or re implement an important part of HashMap < K, V > your solution that relies on two hash tables is as good
Not necessarily: you can use the same object representing the phone number, in which case the phone number will have an object with two objects stored in two hash tables