Java Java Data Structures Efficiency! Using a Map to store Contact Methods

Jay Bhatt
Jay Bhatt
6,502 Points

How do I extract my answer from the if statement onto the return?

I am having trouble returning the value based on the key. My if statement looks good and I can retrieve the value based on the key but I do not know how to return that in the class.

Please help, it feels like a simple solution...

com/example/model/Contact.java
package com.example.model;

import java.util.Map;
import java.util.Set;
import java.util.HashMap;
import java.util.HashSet;

public class Contact {
  private String mFirstName;
  private String mLastName;
  private Map<String, String> mContactMethods;

  public Contact(String firstName, String lastName) {
    mFirstName = firstName;
    mLastName = lastName;
    /* This stores contact methods by name
     * eg:  "phone" => "(555) 555-1234"
     */
    mContactMethods = new HashMap<String, String>();
  }

  public void addContactMethod(String method, String value) {
    mContactMethods.put(method,value);

  }

  /**
   * Returns the available contact methods.  eg: phone, pager,
   *
   * @return The name of the contact methods that are available
   */
  public Set<String> getAvailableContactMethods() {
    Set<String> availableContacts = new HashSet<String>();
    availableContacts = mContactMethods.keySet();
    return availableContacts;

    // FIXME: This should return the current contact method names
  }

  /**
   * Returns the value for the contact method if it exists, 
   *
   * @param methodName  The name of the contact method to look up.
   * @return The name of the contact methods that are available
   */
  public String getContactInfo(String methodName) {
      if (mContactMethods.containsKey(methodName)) {
     result = mContactMethods.get(methodName);
    }
    return result;
  }

  public String getFirstName() {
    return mFirstName;
  }

  public String getLastName() {
    return mLastName;
  }

}

2 Answers

Hi

instead of this if (mContactMethods.containsKey(methodName)) { result = mContactMethods.get(methodName); } return result;

you can do this

if (mContactMethods.containsKey(methodName)) { return mContactMethods.get(methodName); }

If this answers your question, please mark the question as answered.

Thanks

Jay Bhatt
Jay Bhatt
6,502 Points

That does not work, since then the class will not return anything. I figured out a different way though, thanks anyways

Hi

Of course the class does not return anything

You are returning from method public String getContactInfo(String methodName) not the class

regardless ... glad you find a way.

Mark