elementAtE method
Returns the element at the specified index.
Iterates over the entire enumerable until it reaches the element on the
iteration matching the given index
. elementAtE will then return that
value. If the iteration reaches the end of the enumerable before arriving
at index
, an ElementNotFoundError
will be thrown.
If the underlying collection is a ListEnumerable
, this method will instead
short-circuit into an indexer call to the List
as an O(1) operation. If
index
is greater than or equal to the length of the list, an
ElementNotFoundError
will be thrown.
The value of index
must be a non-negative integer.
The elementAtE method will short-circuit after reaching the element at
index
and will not iterate further over the enumerable. In the worst
case, it will iterate over the entire enumerable.
Implementation
T elementAtE(int index) {
RangeError.checkNotNegative(index);
if (this is ListEnumerable) {
if (index >= this.length) throw EnumerableError.elementNotFound();
return (this as ListEnumerable)[index];
}
final iterator = this.iterator;
int currentIndex = 0;
while (iterator.moveNext()) {
if (currentIndex == index) return iterator.current;
currentIndex++;
}
throw EnumerableError.elementNotFound();
}