Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding ".foreach" capability to a custom container class

Tags:

java

java-8

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);
like image 560
Hobbyist Avatar asked Aug 08 '26 15:08

Hobbyist


1 Answers

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.

like image 162
Eran Avatar answered Aug 11 '26 05:08

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!