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'};

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".

2 Answers 2


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();

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

List<String> baby = new List<String> {'aman','Anu','Anurag','Akshu'};
List<String> Action = new List <String> {'crying','sleeping','burping','playing'};
Iterator <String> babyIterator = baby.iterator();
Iterator <String>actIterator = Action.iterator();
while(babyIterator.hasNext() && actIterator.hasNext())
    String babyItem = babyIterator.next();
    String ActionItem = actIterator.next();
    system.debug(babyItem + ActionItem);

always provide same argument or data collection type provided in "<>"to the Iterator so it will work.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .