队列结构,源码分析
public ArrayQueue(int capacity) {
//容量
this.capacity = capacity + 1;
//队列
this.queue = newArray(capacity + 1);
//头指针
this.head = 0;
//尾指针
this.tail = 0;
}
public boolean add(T o) {
//加到队尾
queue[tail] = o;
//为0 代表和容量一样大小,满了
int newtail = (tail + 1) % capacity;
if (newtail == head)
throw new IndexOutOfBoundsException("Queue full");
//新的尾指针
tail = newtail;
return true; // we did add something
}
//改变队列大小
public void resize(int newcapacity) {
// 保存数据的个数
int size = size();
//如果新的size比数据量小,就要丢数据,抛出异常
if (newcapacity < size)
throw new IndexOutOfBoundsException("Resizing would lose data");
//新的容量+1
newcapacity++;
//如果扩容后的size和当前容量相同,返回
if (newcapacity == this.capacity)
return;
//创建新队列
T[] newqueue = newArray(newcapacity);
//复制队列
for (int i = 0; i < size; i++)
newqueue[i] = get(i);
//赋值
this.capacity = newcapacity;
this.queue = newqueue;
this.head = 0;
this.tail = size;
}