0

I am creating a phone book API in Java. Every name in my phone book is mapped to a set of phone numbers & address. I want to build a search function which can search an entry in my phone book using a search parameter as a name or as the phone number itself.

My approach has been to add all my entries to a:

Map <String, PhoneNumber> book = new HashMap <String,PhoneNumber>();
book.put("Name1",new PhoneNumber(new Integer(12345),new Integer(123456));
book.get("Name1");
// PhoneNumber is my class which can have different types of phone numbers

I want to search by both the name which is the key and also by the value. I cannot do that using a HashMap. Is there a way to do it better to implement an efficient searching process?

4
  • 1
    Don't represent phone numbers as integers. You cannot represent leading zeros or # with an integer. Commented Sep 26, 2010 at 8:19
  • Good catch @thorbjorn. Further, phone numbers aren't really numbers - it makes no sense to do math on a phone number. Therefore, it isn't a number even if it looks like one. So we what see here could be a generic 'lookup' class, and a 'phone book' subclass that applies a 'the key must be a numeric string' rule. Commented Sep 26, 2010 at 12:21
  • @Tony, the "key must be numeric string" does not allow for #'s. Commented Sep 26, 2010 at 13:49
  • By '#' do you mean 'the key must be comprised of characters between 0 and 9 inclusive'? If so, I think we're saying the same thing. Commented Sep 26, 2010 at 14:06

1 Answer 1

2

Don't use a Map for your phone book. It's too limited. Instead create a PhoneBook class. Within that class have 2 Maps, one for the by-name searching and one for the by-number searching. Create an add() routine that adds Info to both maps.

public class PhoneBook {
   private Map<String,Info> byNumber;
   private Map<String,Info> byName;
}

Where "Info" is a class that tells you everything about the person.

Sign up to request clarification or add additional context in comments.

1 Comment

The above assumes names are unique. That's unrealistic of course. If they aren't, you'd likely have: private Map<String,List<Info>> byName; so you get a list of all people with that name.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.