3

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);
Eran
  • 359,724
  • 45
  • 626
  • 694
Hobbyist
  • 14,260
  • 8
  • 37
  • 89
  • 1
    You can't new `Generic`. http://stackoverflow.com/questions/2927391/whats-the-reason-i-cant-create-generic-array-types-in-java – chengpohi Jun 01 '15 at 06:15
  • http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/util/ArrayList.java#ArrayList.forEach%28java.util.function.Consumer%29 – Alexis C. Jun 01 '15 at 06:25
  • 1
    @Chengphoi (T[]) new Obejct[200]; – Hobbyist Jun 01 '15 at 06:40

2 Answers2

3

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.

Eran
  • 359,724
  • 45
  • 626
  • 694
2

I'd suggest you to create a method which returns the stream:

Stream<T> stream() {
    return Arrays.stream(array);
    // or probably Arrays.stream(array, 0, size); if it's used partially
}

This way the users will have not only forEach, but every operation supported by streams.

Tagir Valeev
  • 87,515
  • 18
  • 194
  • 305