简体   繁体   中英

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();
            }
        }
    }
}

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);    

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();
    }
}

You are doing:

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

and you need to do:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM