Build a simple PhoneBook program.

PhoneBook.java 1.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import java.util.TreeMap;
  2. /**
  3. * Created by leon on 1/23/18.
  4. */
  5. public class PhoneBook {
  6. private TreeMap<String, String> phoneBook;
  7. private TreeMap<String, String> reversePhoneBook;
  8. public PhoneBook() {
  9. phoneBook = new TreeMap<String, String>();
  10. reversePhoneBook = new TreeMap<String, String>();
  11. }
  12. public void add(String name, String phoneNumber) {
  13. phoneBook.put(name, phoneNumber);
  14. reversePhoneBook.put(phoneNumber, name);
  15. }
  16. public void remove(String name) {
  17. String phoneNumber = phoneBook.get(name);
  18. phoneBook.remove(name);
  19. reversePhoneBook.remove(phoneNumber);
  20. }
  21. public String lookup(String name) {
  22. return phoneBook.get(name) != null ?
  23. phoneBook.get(name)
  24. :
  25. "N/A";
  26. }
  27. public String reverseLookup(String phoneNumber) {
  28. return reversePhoneBook.get(phoneNumber) != null ?
  29. reversePhoneBook.get(phoneNumber)
  30. :
  31. "N/A";
  32. }
  33. public TreeMap getPhoneBook() {
  34. return phoneBook;
  35. }
  36. public TreeMap getReversePhoneBook() {
  37. return reversePhoneBook;
  38. }
  39. }