2017-08-02 284 views
0

我想解決這個錯誤,但由於某種原因,無法找到問題來解決它。我在此代碼中使用Collection。如果任何人都可以指出我缺少的是什麼,那我會很有幫助的。我使用的集合只能遍歷數組或java.lang.Iterable的實例

Collection challenges = null; 
     Map challengesMap = new HashMap<String,String>(); 
     ForgotPasswordManager forgotPwdMgr = new ForgotPasswordManager(platform); 
     System.out.println("after ForgotPasswordManager(platform)...before getSecretQuestion()"); 
     challenges = forgotPwdMgr.getSecretQuestion(userID); 
     System.out.println("after getSecretQuestion()..."); 
     for (Object challenge : challenges) { 
      String challengeStr = (String)challenge; 
      System.out.println("doGetChallenges()...ChallengeStr = " + challengeStr); 
      challengesMap.put(challengeStr.trim(), ""); 
     } 

我在網上收到此錯誤Can only iterate over an array or an instance of java.lang.Iterable:這裏for (Object challenge : challenges)

+1

[錯誤:只能遍歷數組或java.lang.Iterable的實例](https://stackoverflow.com/questions/22425277/error-can-only-iterate-over-an -array或 - 一個實例-的-java的琅可迭代)。 [第二個答案](https://stackoverflow.com/a/22425341/4660897)解釋了這個問題。 –

回答

3

Collection類型引用:

Collection challenges = null; 

不是java.util.Collection接口,擴展接口Iterable
否則,你就沒有此錯誤消息:

Can only iterate over an array or an instance of java.lang.Iterable

在這一行:

for (Object challenge : challenges) { 

您使用的可能是一個自定義的Collection類。

所以要解決您的問題,請您自定義Collection類實現Iterable或更簡單:使用JDK java.util.Collection子類。

+0

可否詳細說一點我有點迷惑@davidxxx – newlearner

+0

好的。在導入中查看'Collection'類的包。你會看到這不是'java.util.Collection'。所以這意味着你使用你自己的'Collection'類。 – davidxxx

+0

我使用import.java.util.Collection當我點擊聲明類型時,它將我帶到Collection類@davidxxx – newlearner