2013-01-31 35 views
0

Possible Duplicate:
How do I iterate over each Entry in a Map?失敗遍歷地圖在JSP

我下面這個解決方案沒有效果:https://stackoverflow.com/a/1835742/666468

我想輸出這些地圖:

//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 
    } 

但我得到這個錯誤:只能迭代一個數組或java.lang.Iterable的實例

I imp orted java.util.Iterator以及但沒有運氣。

p.s.我希望我可以安裝和使用JSTL,但這不是我的電話。

+1

image.getImageTagAttributes()'返回什麼?一個'Map'有一個鍵/值對機制。您需要使用'EntrySet'來遍歷'Map'。 – Lion

+0

按照以下解決方案中的建議使用迭代器: http://stackoverflow.com/questions/672916/how-to-get-image-height-and-width-using-java – Zafer

+2

你是怎麼錯過'entrySet( )'在你找到答案中的方法? – BalusC

回答

2

不知道你從哪裏得到Image班,但如果image.getImageTagAttributes()返回Map<String, String>那麼也許試試吧s)

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 
} 
0

您無法迭代每個循環的Map。

獲取地圖對象鍵集,然後迭代它。

然後在for循環中嘗試從地圖中檢索每個鍵的值。

0

因爲這不是正確的方法來遍歷一個地圖:

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 
    } 

,或者你可以interate這樣:

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 
    } 

在我的答案,我想這image.getImageTagAttributes();回報Map<String,String>