function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion

Question on Sample Custom Iterator

Below is an example provided in the Apex manual that shows a custom iterator.  There is a line that I find confusing found in the method called "next()":


         if(i == 8){ i++; return null;}


Does anyone know what this is for?  I am inclined to dismiss it.  However, maybe there is something that I don't understand about the "iterable" and "iterator" interfaces.


If anyone has insights, please let me know.









global class CustomIterable implements Iterator<Account>{
List<Account> accs {get; set;}
Integer i {get; set;}
public CustomIterable(){
accs = [SELECT id, name, numberofEmployees FROM Account WHERE name = 'false'];
i = 0;
global boolean hasNext(){
if(i >= accs.size())
return false;
return true;
global Account next(){
if(i == 8){ i++; return null;}
return accs[i-1];


I guess that line is there to prevent a user trying to access an index in the list that doesn't exist.


EX: the list has 7 items, you are trying to access the 8th items on the list.


I guess the 8 there should be accs.size(), like what they have in hasNext().


The test for i==8 is there to illustrate a next() method that does something other than always return the next element in an arbitrary list of size n.  In this case, next() returns null when the [8]th element is requested - meaning, no more elements in the list. Any other elements are ignored.


Kind of an artificial example