简体   繁体   中英

How to make a loop over all keys of a HashMap?

I try to do it in the following way:

public String getValue(String service, String parameter) {
    String inputKey = service + ":" + parameter;
    Set keys = name2value.keySet();
    Iterator itr = keys.iterator();
    while (itr.hasNext()) {     
        if (inputKey.equal(itr.next())) {
            return name2value.get(inputKey);
        }
        return "";
    }
}

And I get an error message: cannot find symbol method.equal(java.lang.Object).

I think it is because itr.next() is not considered as a string. How can I solve this problem? I tried to replace Set keys by Set<String> keys . It did not help.

The method you want is called equals not equal .

However there are a few other flaws in your code.

Firstly you should not be looping through all keys in a Map to find a specific key, just use get and/or containsKey .

The second return is also wrong. It will return "" if the first key does not match. If you want to return "" when none of the keys match, the return should go at the end of the method eg:

public String getValue(String service, String parameter) {
    String inputKey = service + ":" + parameter;
    String value = name2value.get(inputKey);
    if (value == null) {
        return "";
    } else {
        return value;
    }
}

首先,方法是equals()其次,将itr.next()为字符串而不是Set。

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