队列
满的条件是
(nextIndex
+1)
% capacity==firstIndex;
队列为空的条件是firIndex==nextIndex;
数组总是会空一个元素以满足上面两个条件;好处是提取元素和追加元素的复杂度都是O(1);
package com.myTest.queue;
import java.util.concurrent.locks.ReentrantLock;
public class CurrentArrayQueue<E> {
public static void main(String[] args) {
CurrentArrayQueue<Integer> queue = new CurrentArrayQueue<>(5);
queue.offer(1);
queue.offer(2);
queue.offer(3);
queue.offer(4);
queue.poll();
queue.offer(5);
queue.poll();
queue.offer(6);
queue.poll();
queue.offer(7);
queue.poll();
queue.offer(10);
System.out.println(queue);
}
private static ReentrantLock lock;
//队列头元素所在的索引
private static int firstIndex;
//队列的下一个元素的索引,默认 firstIndex==nextIndex 则为empty;
private static int nextIndex;
//初始化数组大小
private static int capacity;
private static Object[] elements;
public CurrentArrayQueue(int capacity) {
lock = new ReentrantLock();
firstIndex=0;
nextIndex=0;
elements=new Object[capacity];
this.capacity=capacity;
}
/**
* 追加元素
* @param e
* @return
*/
public Boolean offer(E e){
if(e==null){
throw new NullPointerException();
}
if((nextIndex+1)%capacity==firstIndex){
throw new ArrayIndexOutOfBoundsException();
}
lock.lock();
try{
if((nextIndex+1)%capacity!=firstIndex){
//如果队列没有满
elements[nextIndex]=e;
nextIndex=(nextIndex+1)%capacity;
}
}finally {
lock.unlock();
}
return true;
}
/**
* 检索并删除头元素
*/
public E poll(){
if(firstIndex==nextIndex){
return null;
}
lock.lock();
E element=null;
try{
element = (E)elements[firstIndex];
elements[firstIndex]=null;
firstIndex=(firstIndex+1)%capacity;
}finally {
lock.unlock();
}
return element;
}
@Override
public String toString() {
String result="[";
for (Object object:elements) {
result=result+","+object;
}
result=result.replaceFirst(",","");
result=result+"]";
return result;
}
}