Failure to Loop Through Map in JSP

Possible Duplicate:
How do I iterate over each Entry in a Map?

I'm following this solution to no effect: https://stackoverflow.com/a/1835742/666468

I am trying to output this Map:

//protected Map<String,String> getImageTagAttributes()
Image image = new Image(resource);
for (Map<String, String> foo : image.getImageTagAttributes()) {
        String key = foo.getKey();
        String value = foo.getValue();

        //output here
    }

But I get this error: Can only iterate over an array or an instance of java.lang.Iterable

I imported java.util.Iterator as well, but no luck.

ps I wish I could install and use JSTL, but it's not my call.


不知道你是从哪里得到这个Image类的,但是如果image.getImageTagAttributes()返回Map<String, String>那么可以试试这种方式

Image image = new Image(resource);
Map<String, String> map = image.getImageTagAttributes();
for (Map.Entry<String,String> foo : map.entrySet()) {
    String key = foo.getKey();
    String value = foo.getValue();

    //output here
}

You cannot iterate a Map in for each loop.

Get the map object keyset and then iterate it.

Then inside the for loop try retrieving the value for each key from the map.


Because this not the correct way to iterate over a Map :

    Image image = new Image(resource);
    Map<String, String> foo =  image.getImageTagAttributes();
    Set<String> key = foo.keyset(); 
     for ( k : keys ) {
           String value = foo.get(k);
        //output here
    }

or you can interate that way :

    Image image = new Image(resource);
    Map<String, String> foo =  image.getImageTagAttributes();
    Set<Map.Entry<String,String>> entries = foo.entrySet();

    for(Map.Entry<String, String> e : entries){
       String key  = e.getKey();
       String value = e.getValue();
        //output
    }

In my answer, I suppose that image.getImageTagAttributes(); returns a Map<String,String>

链接地址: http://www.djcxy.com/p/23976.html

上一篇: 在Java中迭代HashMap

下一篇: 无法在JSP中循环映射