开发者

Why is key (or value) of Map<String, String> not returned as String?

In the following short code snippet, Eclipse flags an error about the String key = pair.getKey(); and the String value = pair.getValue(); statements, saying that

"Type mismatch: cannot convert from Object to String"

This is the relevant code:

    for (Map<String, String> dic : di开发者_如何学Ccs) {
        Iterator it = dic.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry pair = (Map.Entry)it.next();
            String key = pair.getKey();
            String value = pair.getValue();
        }               
    }

Why is that?

All examples I have seen so far, do not cast pair.getKey() or pair.getValue() to String, so I would like to understand what's happening before proceeding with a solution.


Try this:

for (Map<String, String> dic : dics) {
    Iterator<Map.Entry<String, String>> it = dic.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry<String, String> pair = it.next();
        String key = pair.getKey();
        String value = pair.getValue();
    }               
}

Or even better (internal working is identical, but this is less verbose):

for (Map<String, String> dic : dics) {
    for(Map.Entry<String, String> pair : dic.entrySet()){
        String key = pair.getKey();
        String value = pair.getValue();
    }               
}


You have not carried the types through the it or pair

Try this

for (Map<String, String> dic : dics) {
    for (Map.Entry<String, String> pair : dic.entrySet()) {
        String key = pair.getKey();
        String value = pair.getValue();
    }               
}


Try this:

for (Map<String, String> dic : dics) {
  Iterator<Map.Entry<String, String>> it = dic.entrySet().iterator();
  while (it.hasNext()) {
    Map.Entry<String, String> pair = it.next();
      String key = pair.getKey();
      String value = pair.getValue();
  }               

}


Basically the idea is that your iterator(it) and entry(pair) should also be generics-ized.

                Iterator<Entry<String, String>> it = dic.entrySet().iterator();
                while (it.hasNext()) {
                     Entry<String, String> pair = it.next();
                    String key = pair.getKey();
                    String value = pair.getValue();
                }        


You have the Entry as a raw unparametrized type type.

Use Entry<String, String> instead of the raw Entry.


Your declaration of Map.Entry is not parameterized by type.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜