0

I am trying to solve this error, but for some reason, not able to find the issue to fix it. I am using Collection in this code. If anyone can point me out what actually I am missing, I would be a great help.

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

I am getting this error Can only iterate over an array or an instance of java.lang.Iterable on line: for (Object challenge : challenges)

Hussain Patel
  • 460
  • 3
  • 10
  • 24
newlearner
  • 95
  • 10
  • 1
    Possible duplicate of [Error: can only iterate over an array or an instance of java.lang.Iterable](https://stackoverflow.com/questions/22425277/error-can-only-iterate-over-an-array-or-an-instance-of-java-lang-iterable). The [second answer](https://stackoverflow.com/a/22425341/4660897) explains the problem. – Tot Zam Aug 02 '17 at 21:17

1 Answers1

3

The Collection type referenced here :

Collection challenges = null;

is not the java.util.Collection interface that extends the Iterable interface.
Otherwise you would have not this error message :

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

at this line :

for (Object challenge : challenges) {

You are using probably a custom Collection class.

So to solve your problem, make your custom custom Collection class implement Iterable or more simple : use JDK java.util.Collection subclasses.

davidxxx
  • 125,838
  • 23
  • 214
  • 215
  • can you elaborate little bit more i am little confuse @davidxxx – newlearner Aug 02 '17 at 21:21
  • Ok. Look at the package of the `Collection` class in your imports. You will see that is not `java.util.Collection`. So it means that you use your own `Collection` class. – davidxxx Aug 02 '17 at 21:25
  • i am using the import.java.util.Collection when i click on Declared type it brings me to the Collection class @davidxxx – newlearner Aug 03 '17 at 13:32
  • I suppose you have a `Collection` class in the package of the actual class that declares this code ? – davidxxx Aug 03 '17 at 14:45
  • i didn't define the Collection class in my code after importing it could that be the reason because i am only using collection on this piece of the code @davidxxx – newlearner Aug 03 '17 at 15:23
  • thank you so much @davidxxx i just made the little change in my two lines Collection challenges = null; Map challengesMap = new HashMap(); – newlearner Aug 03 '17 at 16:12