-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathRingBuffer.java
More file actions
64 lines (53 loc) · 1.29 KB
/
Copy pathRingBuffer.java
File metadata and controls
64 lines (53 loc) · 1.29 KB
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
package bittrex;
import java.util.ArrayList;
import java.util.List;
public class RingBuffer<T> {
private final T[] data;
private final int total;
private int head = 0;
private int size = 0;
@SuppressWarnings("unchecked")
public RingBuffer(int size) {
data = (T[]) new Object[size];
this.total = size;
}
public void add(T t) {
data[head] = t;
head = (head + 1) % total;
if (size < total) {
size ++;
}
}
public List<T> list() {
// TODO array copy or s.th. like that to optimize ?
List<T> l = new ArrayList<>(size);
int idx = (head - 1 + total) % total;
for (int i = 0; i < size; i ++) {
l.add(data[idx--]);
if (idx < 0) {
idx += total;
}
}
return l;
}
public T last() {
if (isEmpty()) {
return null;
}
int idx = head - 1;
if (idx < 0) {
idx = 0;
}
return data[idx];
}
public boolean isEmpty() {
return size == 0;
}
public void clear() {
head = 0;
size = 0;
for (int i = 0; i < data.length; i++) {
data[i] = null;
}
}
}