Adding the ".foreach" capability to a custom container class
I wrote my own container class for my game, similar to ArrayList but different in different ways, anyway I want to write a foreach method that will iterate over the backups array.
I know I could just use it Arrays.stream
, but I'm curious what it would look like to write a custom lambda implementation of the #foreach method to iterate over an array.
Who has the key? Thanks to
Example:
class Container<T> {
T[] array = new T[200];
}
Now, let's say I would like to do this:
Container<Fish> fishies = new Container();
fishies.forEach(fish->System::out);
source to share
You need to implement a method forEach
similar to the interface method Stream
in your class Container
:
void forEach(Consumer<? super T> action)
{
for (int i = 0; i < array.length; i++)
action.accept(array[i]);
}
This implementation forEach
is sequential, so it is much simpler than an implementation Stream
that can also be parallel.
I ignore the fact that the T[] array = new T[200];
compilation is not committing as that is a different issue.
source to share