0

I am looking for cyclic collection in Java. I have some players in Array (they wait for their turn) but I would like to change Array to cyclic collection so it will be easier to get next player.(I know how it can be done otherwise, but I'd like to use cyclic collection already prepared in Java).

Yoda
  • 17,363
  • 67
  • 204
  • 344

1 Answers1

0

You can make any Iterable into a cyclic collection. Just keep requesting Iterators forever.

class Ring<T> implements Iterable<T> {
    // Source of all Iterators.
    final Iterable<T> it;
    // Current Iterator we are consuming.
    Iterator<T> i;

    public Ring(Iterable<T> it) {
        this.it = it;
        i = it.iterator();
    }

    @Override
    public Iterator<T> iterator() {
        return new Iterator<T> () {

            @Override
            public boolean hasNext() {
                // There's always a next for a Ring.
                return true;
            }

            @Override
            public T next() {
               if ( !i.hasNext() ) {
                   // Iterator is exhausted - make a new one!
                   i = it.iterator();
               }
               return i.next();
            }

        };
    }
}

public void test() {
    Ring<String> r = new Ring<>(Arrays.asList("One", "Two", "Three"));
    int printed = 0;
    for (String s : r) {
        System.out.println(s);
        if (++printed > 10) {
            break;
        }
    }
}

Note that there is a strange edge case when the wrapped Iterable delivers empty iterators but I leave that detail to the student.

OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213