-
Notifications
You must be signed in to change notification settings - Fork 0
/
MyIterator.java
75 lines (63 loc) · 1.84 KB
/
MyIterator.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package ru.kpfu.itis.barakhov.units;
import java.util.Arrays;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Objects;
public class MyIterator<T> implements Iterator<T> {
private static final String ERROR_MESSAGE = "error message here";
private final T[] data;
private int cursor;
private final int length;
public MyIterator(T[] data, int size) {
this.data = data;
cursor = -1;
length = size;
}
@Override
public boolean hasNext() {
return cursor < length - 1;
}
@Override
public T next() {
if (hasNext()) {
return data[++cursor];
}
throw new NoSuchElementException(ERROR_MESSAGE);
}
public void remove() {
try {
T el = data[cursor + 1];
if (el == null) {
throw new NoSuchElementException(ERROR_MESSAGE);
}
} catch (ArrayIndexOutOfBoundsException ex) {
throw new NoSuchElementException(ERROR_MESSAGE);
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof MyIterator)) return false;
MyIterator<?> that = (MyIterator<?>) o;
return cursor == that.cursor &&
getLength() == that.getLength() &&
Arrays.equals(data, that.data);
}
@Override
public int hashCode() {
int result = Objects.hash(cursor, getLength());
result = 31 * result + Arrays.hashCode(data);
return result;
}
@Override
public String toString() {
return "MyIterator { " +
"data = " + Arrays.toString(data) +
", cursor = " + cursor +
", length = " + length +
" }";
}
public int getLength() {
return length;
}
}