shz.core.queue.a.ZArrayQueue Maven / Gradle / Ivy
package shz.core.queue.a;
import shz.core.constant.ArrayConstant;
import shz.core.function.BooleanConsumer;
import java.util.Objects;
/**
* 元素类型为boolean基于循环动态数组的队列
*
* 24+n(n为元素个数)=es
*
* B=56+n+对齐填充
*/
public class ZArrayQueue extends ArrayQueue {
private static final long serialVersionUID = -8358172019805696725L;
protected boolean[] es;
public ZArrayQueue(int capacity) {
super(capacity);
es = new boolean[this.capacity];
}
public ZArrayQueue() {
this(DEFAULT_CAPACITY);
}
public static ZArrayQueue of(int capacity) {
return new ZArrayQueue(capacity);
}
public static ZArrayQueue of() {
return new ZArrayQueue();
}
@Override
protected final void resize(int capacity) {
boolean[] temp = new boolean[capacity];
for (int i = 0; i < size; ++i) temp[i] = es[(i + head) % this.capacity];
this.capacity = capacity;
head = 0;
tail = size;
es = temp;
}
@Override
protected final void setNull(int i) {
es[i] = false;
}
public final void offer(boolean e) {
beforeOffer();
es[tail] = e;
afterOffer();
}
public final boolean poll() {
checkEmpty();
boolean e = es[head];
afterPoll();
return e;
}
public final boolean head() {
checkEmpty();
return es[head];
}
public final boolean tail() {
checkEmpty();
return es[tail == 0 ? capacity - 1 : tail - 1];
}
public final boolean get(int idx) {
if (idx < 0 || idx >= size) throw new IndexOutOfBoundsException();
return es[(head + idx) % capacity];
}
public final boolean[] toArray() {
if (size == 0) return ArrayConstant.EMPTY_BOOLEAN_ARRAY;
boolean[] array = new boolean[size];
int idx = 0;
int current = head;
while (current != tail) {
array[idx++] = es[current];
current = (current + 1) % capacity;
}
return array;
}
public final void forEach(BooleanConsumer action) {
Objects.requireNonNull(action);
int current = head;
while (current != tail) {
action.accept(es[current]);
current = (current + 1) % capacity;
}
}
}