-
Notifications
You must be signed in to change notification settings - Fork 1
/
myCircularArray.java
93 lines (73 loc) · 1.97 KB
/
myCircularArray.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import java.lang.Exception;
import java.lang.*;
import java.util.Iterator;
public class myCircularArray {
public static void main(String args[]) {
myCircularArrayTest<String> arr = new myCircularArrayTest<String>(10);
arr.set(0, "aa");
arr.set(9, "bb");
System.out.println(arr.get(0));
System.out.println(arr.get(9));
}
}
class myCircularArrayTest<T> implements Iterable<T> {
private int head;
private T array[];
public Iterator<T> iterator() {
Iterator<T> iter = new myCircularArrayTestIter();
return iter;
}
public class myCircularArrayTestIter implements Iterator<T> {
int iterIndex = -1;
public myCircularArrayTestIter() {
return;
}
@Override
public boolean hasNext() {
if (iterIndex < array.length - 1)
return true;
else
return false;
}
@Override
public T next() {
int physicalIndex = transition(iterIndex + 1);
if (hasNext()) {
iterIndex++;
return array[physicalIndex];
} else
throw new java.lang.IndexOutOfBoundsException("exception.");
}
@Override
public void remove() {
throw new java.lang.IndexOutOfBoundsException("exception.");
}
}
public myCircularArrayTest (int size) {
if (0 >= size)
throw new java.lang.IndexOutOfBoundsException("exception.");
head = 0;
array = (T[]) new Object[size];
return;
}
private int transition(int logicIndex) {
if (0 > logicIndex)
logicIndex += array.length;
return (head + logicIndex) % array.length;
}
public void rotateBy(int rotation) {
head = transition(rotation);
}
public T get(int index) {
if ((index >= array.length) || (index < 0))
throw new java.lang.IndexOutOfBoundsException("exception.");
int physicalIndex = transition(index);
return array[physicalIndex];
}
public void set(int index, T value) {
if ((index >= array.length) || (index < 0))
throw new java.lang.IndexOutOfBoundsException("exception.");
int physicalIndex = transition(index);
array[physicalIndex] = value;
}
}