RuneHive-Game
Loading...
Searching...
No Matches
ArrayIterator.java
Go to the documentation of this file.
1package com.runehive.util;
2
3import com.google.common.collect.PeekingIterator;
4
5import java.util.ArrayList;
6import java.util.Iterator;
7
8/**
9 * An {@link Iterator} implementation that will iterate over the elements in
10 * an array without the overhead of the {@link ArrayList}s {@code withdraw}
11 * operation.
12 * @param <E> the type of array being iterated over.
13 * @author lare96 <http://github.com/lare96>
14 */
15public final class ArrayIterator<E> implements PeekingIterator<E> {
16
17 /**
18 * The array that is storing the elements.
19 */
20 private final E[] array;
21
22 /**
23 * The current index that the iterator is iterating over.
24 */
25 private int index;
26
27 /**
28 * The last index that the iterator iterated over.
29 */
30 private int lastIndex = -1;
31
32 /**
33 * Creates a new {@link ArrayIterator}.
34 * @param array the array that is storing the elements.
35 */
36 public ArrayIterator(E[] array) {
37 this.array = array;
38 }
39
40 @Override
41 public boolean hasNext() {
42 return !(index + 1 > array.length);
43 }
44
45 @Override
46 public E peek() {
47 return array[index];
48 }
49
50 @Override
51 public E next() {
52 if(index >= array.length)
53 throw new ArrayIndexOutOfBoundsException("There are no elements left to iterate over!");
55 index++;
56 return array[lastIndex];
57 }
58
59 @Override
60 public void remove() {
61 if(lastIndex == -1)
62 throw new IllegalStateException("This method can only be called once after \"next\".");
63 array[lastIndex] = null;
64 lastIndex = -1;
65 }
66}
final E[] array
The array that is storing the elements.
int lastIndex
The last index that the iterator iterated over.
int index
The current index that the iterator is iterating over.
ArrayIterator(E[] array)
Creates a new ArrayIterator.