I have the following custom iterator class that iterates over a list of Accounts (accounts):
public class CustomIterator implements Iterator<Account>{
private List<Account> accounts;
private Integer currentIndex;
public CustomIterator(List<Account> accounts){
this.accounts = accounts;
this.currentIndex = 0;
}
public Boolean hasNext(){
return currentIndex < accounts.size();
}
public Account next(){
if(hasNext()) {
return accounts[currentIndex++];
} else {
throw new NoSuchElementException('Iterator has no more elements.');
}
}
public void add(Account acc) {
accounts.add(acc);
}
}
I would like to be able to insert elements into accounts after instantiating the iterator, so I defined an instance method called add(Account) that takes an Account object as its only argument and appends it to accounts.
However, calling this method results in an error:
List<Account> accs = [SELECT Id, Name, NumberOfEmployees FROM Account LIMIT 3];
Iterator<Account> iter = new CustomIterator(accs);
Account acc = [SELECT Id, Name, NumberOfEmployees FROM Account LIMIT 1];
iter.add(acc); // Error: Method does not exist or incorrect signature: void add(Account) from the type System.Iterator<Account>
Is this by design or am I missing something in the declaration of add or accounts? (A similar example makes use of the global modifier instead of public. Here, accounts is declared as a read/write property and does not have any modifiers.)
I've read that classes that implement an interface can have their own methods in addition to those declared in the interface, so I'm not sure what's causing the error.
iterof the correct class to call the method. – Phil W Mar 05 '23 at 15:21