2

I was wondering why I had this error when I tried to do this :

Map<Integer, List<String>> map = (Map<Integer, List<String>>) parameters;

for(Integer i : map.keySet()) {
    tableFiles.setWidget(row, 0, addPanelFile(String.valueOf(i)));
    row++;
    for(map.get(i)) {

    }
}

Why can't i be resolved to a variable ?

1
  • 1
    The easiest and most efficient way to iterate through a map if you need both the key and value is to iterate through the Set<Map.Entry<K, V>> returned by entrySet(). Then you don't need to do a get, you already have the value in the Entry. Commented Jun 13, 2011 at 12:49

2 Answers 2

10

The for-loop is malformed.

Change

for(((Map<Integer, List<String>>) parameters).get(i)) {

}

into

for(SomeType someVar : ((Map<Integer, List<String>>) parameters).get(i)) {

}

and you should get a better error-message.

Sign up to request clarification or add additional context in comments.

2 Comments

@Mark Peters : well, that's a typo. Edited
Thanks, I think I'm a bit tired, should have seen this
0

Something of this effect. foreach uses Iterator for iterations;

Map<Integer, List<String>> map = (Map<Integer, List<String>>) parameters;

for (Integer i : map.keySet()) {
    tableFiles.setWidget(row, 0, addPanelFile(String.valueOf(i)));
        row++;
    for (String s: map.get(i)) {

    }
}

4 Comments

You don't need to expose the iterator, keySet().iterator() does not return an Iterator<Iterator>, an Iterator is not an Iterable, and you want map not parameters in the inner loop.
Thanks, I think I'm a bit tired, should have seen this
@Mark Peters, thanks, but Map.get() returns a List<String>. Check the OP's edited question.
Elite: I know what that returns. I was talking about your use of keyIter, which is just wrong since keyIter is not an Iterable. Just use for (Integer i : map.keySet()) , which actually works and doesn't unnecessarily expose the Iterator. On the inner loop, it will fail because presumably parameters isn't declared as a Map<Integer, List<String>> or else the cast to map wouldn't be needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.