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).
Asked
Active
Viewed 768 times
0

Yoda
- 17,363
- 67
- 204
- 344
-
Have you considered a queue? But otherwise, no, a cyclic collection isn't in the standard Java libraries as far as I know. – awksp May 14 '14 at 22:18
-
1@user3580294 Queue is not cyclic as far as I remember. – Yoda May 14 '14 at 22:19
-
apache commons collection has one. – njzk2 May 14 '14 at 22:20
-
But you can make it behave like it's cyclic. Pop something off, do something with it, push it back on after. – awksp May 14 '14 at 22:20
-
4A common way is `next = (current + 1) % total` – Ypnypn May 14 '14 at 22:34
-
1See also http://stackoverflow.com/questions/7266042/java-ring-buffer – Raedwald May 14 '14 at 22:41
-
What @Ypnypn said. There is rarely a need to get any more complicated than that. – Hot Licks May 14 '14 at 23:07
1 Answers
0
You can make any Iterable
into a cyclic collection. Just keep requesting Iterator
s 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
-
Is it only I that read "make a new one!" like a little kid saying "let's have more cake!"? – Andrew Gies May 14 '14 at 23:14
-