开发者

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

开发者 https://www.devze.com 2022-12-23 17:17 出处:网络
I try to do it in the following way: public String getValue(String service, String parameter) { String inputKey = servi开发者_如何学Pythonce + \":\" + parameter;

I try to do it in the following way:

public String getValue(String service, String parameter) {
    String inputKey = servi开发者_如何学Pythonce + ":" + 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 e.g.:

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


Firstoff,The method is equals() Secondly, cast itr.next() to string instead of Set.

0

精彩评论

暂无评论...
验证码 换一张
取 消