user3712362
user3712362

Reputation: 21

Java HashMap, get(key) method doesnt work

I'm trying to create a PhoneBook class that uses a HashMap in Java. When I add an entry using the put() method in addContact(), it works fine, but when I try to retrieve values in the searchContact() method, none are returned. I'm not getting null values; HashMap definitely contains the key(s) I am searching for, but the values associated with the key(s) are not being returned. Thank you in advance.

Here is my code:

public class PhoneBookContactsImpl {

    private Map<String, List<String>> contactMap = new HashMap<String, List<String>>();

    public void addContact(String name, List<String> list) {        
        contactMap.put(name, list);
                //its working fine here
        System.out.println(contactMap.get(name));
    }

    public Map<String, List<String>> getContactMap() {

        Set set = contactMap.entrySet();
        Iterator i = contactMap.entrySet().iterator();
        while (i.hasNext()) {
            Map.Entry me = (Map.Entry) i.next();
            System.out.println(me.getKey() + " : ");
            List<String> nos = (List<String>) me.getValue();
            System.out.println("Nos = " + nos + " n ");
            System.out.println(nos.size());
        }
        return contactMap;
    }

    public List<String> searchContact(String name) throws NoDataFoundException {

        if (contactMap.isEmpty()) {
            System.out.println("Empty PhoneBook");
            throw new NoDataFoundException();
        } else {
            if (contactMap.containsValue(name))
                return contactMap.get(name);              
                                 //it doesnt retrieve valur from here
            else {
                System.out.println("No Entry for Specified Entry");
                throw new NoDataFoundException();
            }
        }
    }
}

Upvotes: 2

Views: 421

Answers (3)

Federico Piazza
Federico Piazza

Reputation: 31035

You are doing:

if (contactMap.containsValue(name))
     return contactMap.get(name);   

and you need to do:

if (contactMap.containsKey(name))
     return contactMap.get(name);   

Upvotes: 0

Oleg Sklyar
Oleg Sklyar

Reputation: 10092

As the other answer points out you should be checking containsKey because name is a key, not a value. But why not make the whole thing much easier:

public List<String> searchContact(String name) throws NoDataFoundException {
    List<String> result = contactMap.get(name);
    if (result == null) { 
        // empty map, or no matching value or value is null
        throw new NoDataFoundException();
    }
}

Upvotes: 1

Adam Yost
Adam Yost

Reputation: 3625

your if statement is checking if the phonebook has name as a value, so your get is never reached.

Try this:

if (contactMap.containsKey(name))
            return contactMap.get(name);    

Upvotes: 3

Related Questions