I wrote my own container class for my game, similar to that of an ArrayList however different in quite a few ways, anyhow I want to write a foreach method that will iterate over the backing array.
I know that I could just use Arrays.stream however I'm curious as to how it would look to write a custom lambda implementation of the #foreach method for iteration over an array.
Anybody have a clue? Thanks
Example:
class Container<T> {
T[] array = new T[200];
}
Now for instance lets say I wanted to do this:
Container<Fish> fishies = new Container();
fishies.forEach(fish->System::out);
You need to implement a forEach method similar to that of the Stream interface in your Container class :
void forEach(Consumer<? super T> action)
{
for (int i = 0; i < array.length; i++)
action.accept(array[i]);
}
This forEach implementation is serial, so it's much simpler than the Stream implementations, which can also be parallel.
I'm ignoring the fact that T[] array = new T[200]; doesn't pass compilation, as that's a different issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With