簡體   English   中英

Java HashMap,get(key)方法不起作用

[英]Java HashMap, get(key) method doesnt work

我正在嘗試創建一個在Java中使用HashMapPhoneBook類。 當我在addContact()使用put()方法添加條目時,它可以正常工作,但是當我嘗試在searchContact()方法中檢索值時,不會返回任何值。 我沒有得到空值; HashMap肯定包含我要搜索的鍵,但是未返回與鍵相關的值。 先感謝您。

這是我的代碼:

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

您的if語句正在檢查電話簿是否使用name作為值,因此永遠不會達到您的要求。

嘗試這個:

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

正如其他答案指出的那樣,您應該檢查containsKey因為name是鍵,而不是值。 但是,為什么不使整個過程變得容易得多:

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

您正在執行:

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

並且您需要執行以下操作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM