import java.util.NoSuchElementException;
/**
* @author admin
* @version 1.0.0
* @ClassName CyclicArrayQueue.java
* @Description TODO
* @createTime 2021年08月21日 19:46:00
*/
public class CyclicArrayQueue<E> {
private int front;//队首
private int rear;//队尾
private E[] data;
//容量,但是循环队列中,要空出一个位置方便表示队列的状态。rear=front队列为空
private int maxSize;
//构造器
public CyclicArrayQueue(int capacity){//capacity为数组实际可以存储元素的大小
this.front=0;
this.rear=0;
this.maxSize=capacity+1;
this.data=(E[])new Object[maxSize];//不能直接用E[]造数组
}
//判断是否已经满了
public boolean isFull(){
return (rear+1)%maxSize==front;
}
//判断是否为空
public boolean isEmpty(){
return front==rear;
}
//获取大小
public int size(){
return (rear-front+maxSize)%maxSize;//复习的时候一定要看
}
//添加元素
public void add(E e){
if (e==null){
throw new NullPointerException("添加的元素不能为空");
}
if(isFull()){
throw new IllegalStateException("队列已经满了");
}
data[rear]=e;
rear=(rear+1)%maxSize;//取模,防止rear是最后一个位置导致溢出,满了取前面的位置
}
//取出队列第一个元素
public E get(){
if (isEmpty()){
throw new NoSuchElementException();
}
E e=data[front];
front=(front+1)%maxSize;
return e;
}
//查看队列第一个元素
public E peek(){
if (isEmpty()){
throw new NoSuchElementException();
}
return data[front];
}
@Override//重写toString方法
public String toString() {
StringBuffer buffer = new StringBuffer();
if(isEmpty()){
return buffer.append("[]").toString();
}
buffer.append("[");
for (int i = front; i < front + size(); i++) {
buffer.append(data[i%maxSize]).append(",");
}
// 删除最后一个逗号
buffer.deleteCharAt(buffer.length()-1);
buffer.append("]");
return buffer.toString();
}
}
这位老哥写得好https://blog.csdn.net/yuan_xw/article/details/104361435