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

2 Answers 2

16

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.

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