Regex Rookie
Regex Rookie

Reputation: 10662

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 : dics) {
        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.

Upvotes: 1

Views: 3727

Answers (6)

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 298978

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

Upvotes: 11

Suraj Chandran
Suraj Chandran

Reputation: 24791

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

Upvotes: 1

Thomas
Thomas

Reputation: 88707

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

}

Upvotes: 1

Andy Thomas
Andy Thomas

Reputation: 86419

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

Upvotes: 0

Jan Zyka
Jan Zyka

Reputation: 17888

You have the Entry as a raw unparametrized type type.

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

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533560

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

Upvotes: 8

Related Questions