summaryrefslogtreecommitdiff
path: root/src/main/java/bjc/data/CircularIterator.java
diff options
context:
space:
mode:
authorbculkin2442 <bjculkin@mix.wvu.edu>2019-07-02 18:05:22 -0400
committerbculkin2442 <bjculkin@mix.wvu.edu>2019-07-02 18:05:22 -0400
commit843329de434bb334d90927c4d22345373a388530 (patch)
treeb0ad1f764bd29ff43841e1095a5b58194c20cb37 /src/main/java/bjc/data/CircularIterator.java
parentac36f171a3cebb0993cc28548635e3f654f8e325 (diff)
Rename package root
The package root is now bjc, not io.github.bculkin2442.
Diffstat (limited to 'src/main/java/bjc/data/CircularIterator.java')
-rw-r--r--src/main/java/bjc/data/CircularIterator.java79
1 files changed, 79 insertions, 0 deletions
diff --git a/src/main/java/bjc/data/CircularIterator.java b/src/main/java/bjc/data/CircularIterator.java
new file mode 100644
index 0000000..6842b26
--- /dev/null
+++ b/src/main/java/bjc/data/CircularIterator.java
@@ -0,0 +1,79 @@
+package bjc.data;
+
+import java.util.Iterator;
+
+/**
+ * An iterator that repeats elements from a provided iterable.
+ *
+ * @author EVE
+ *
+ * @param <E>
+ * The type of the iterable.
+ */
+public class CircularIterator<E> implements Iterator<E> {
+ /* The iterable, and our current iterator into it. */
+ private Iterable<E> source;
+ private Iterator<E> curr;
+
+ /* Our current element. */
+ private E curElm;
+
+ /*
+ * Should we actually get new iterators, or just repeat the last
+ * element?
+ */
+ private boolean doCircle;
+
+ /**
+ * Create a new circular iterator.
+ *
+ * @param src
+ * The iterable to iterate from.
+ *
+ * @param circ
+ * Should we actually do circular iteration, or just
+ * repeat the terminal element?
+ */
+ public CircularIterator(final Iterable<E> src, final boolean circ) {
+ source = src;
+ curr = source.iterator();
+
+ doCircle = circ;
+ }
+
+ /**
+ * Create a new circular iterator that does actual circular iteration.
+ *
+ * @param src
+ * The iterable to iterate from.
+ */
+ public CircularIterator(final Iterable<E> src) {
+ this(src, true);
+ }
+
+ @Override
+ public boolean hasNext() {
+ /* We always have something. */
+ return true;
+ }
+
+ @Override
+ public E next() {
+ if (!curr.hasNext()) {
+ if (!doCircle) {
+ return curElm;
+ }
+
+ curr = source.iterator();
+ }
+
+ curElm = curr.next();
+
+ return curElm;
+ }
+
+ @Override
+ public void remove() {
+ curr.remove();
+ }
+}