10

Why this code isn't working? In my mind the next() method should move the cursor for the next item of the list...

List<string> listX = new List<String> {'A','B','C'};
while(listX.iterator().hasNext())
    system.debug(listX.iterator().next());

When I try to run it I receive a error message of exceed a governor limit of CPU time. It's happend because the next() method doesn't move the cursor for the next list item. Every time returns "A".

15

You are returning a new instance of your iterator() every single time your while statement is called. It is simply restarting every time it is called. Try:

List<string> listX = new List<String> {'A','B','C'};
Iterator<String> iter = listX.iterator();
while(iter.hasNext())
    system.debug(iter.next());

The above code just grabs a single instance of your Iterator object and allows you to process the values.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.