谈谈ArrayQueueArrayQueue 是一个循环队列(Queue),继承了 AbstractList 抽象类,内
简述
ArrayQueue
是一个循环队列(Queue),继承了 AbstractList
抽象类,内部通过数组的方式来实现。
源码
package com.sun.jmx.remote.internal;
import java.util.AbstractList;
import java.util.Iterator;
public class ArrayQueue<T> extends AbstractList<T> {
// 初始化必须要传入长度
public ArrayQueue(int capacity) {
this.capacity = capacity + 1;
this.queue = newArray(capacity + 1);
this.head = 0;
this.tail = 0;
}
// 队列扩容
public void resize(int newcapacity) {
int size = size();
if (newcapacity < size)
throw new IndexOutOfBoundsException("Resizing would lose data");
newcapacity++;
if (newcapacity == this.capacity)
return;
T[] newqueue = newArray(newcapacity);
// 这里将原队列(数组)的数据拷贝到新的队列(数组)中
for (int i = 0; i < size; i++)
newqueue[i] = get(i); // 重写了get()方法,实现了从原队列的头部获取数据;
this.capacity = newcapacity;
this.queue = newqueue;
this.head = 0; // 将队列的头移回到第一个位置;
this.tail = size; // 将尾指针指向当前队列最后一个元素的下一个位置;
}
@SuppressWarnings("unchecked")
private T[] newArray(int size) {
return (T[]) new Object[size];
}
// 添加到队列后面
public boolean add(T o) {
queue[tail] = o;
int newtail = (tail + 1) % capacity; // 通过除余来实现下标的循环;
if (newtail == head)
throw new IndexOutOfBoundsException("Queue full");
tail = newtail;
return true; // we did add something
}
// 删除首位元素
public T remove(int i) {
if (i != 0)
throw new IllegalArgumentException("Can only remove head of queue");
if (head == tail)
throw new IndexOutOfBoundsException("Queue empty");
T removed = queue[head];
queue[head] = null;
head = (head + 1) % capacity; // 通过除余来实现下标的循环;
return removed;
}
// 重写了List的get()方法,按照队列顺序依次获取元素
public T get(int i) {
int size = size();
if (i < 0 || i >= size) {
final String msg = "Index " + i + ", queue size " + size;
throw new IndexOutOfBoundsException(msg);
}
int index = (head + i) % capacity;
return queue[index];
}
public int size() {
// Can't use % here because it's not mod: -3 % 2 is -1, not +1.
int diff = tail - head;
if (diff < 0)
diff += capacity;
return diff;
}
private int capacity; // 当前队列的大小,不可变
private T[] queue; // 队列数组
private int head; // 队列首个元素所在的位置
private int tail; // 队列最后一个元素所在的位置
}
整理一下,resize()
:扩容队列(将旧队列的数据复制到新队列)。add()
:添加数据到列尾。remove()
:删除队首元素。
就这么看代码,或许有些朋友会不明白里面的指针是怎么操作的,下面我们看张图。假设有个长度为8的
ArrayQueue
,里面放满数据(7个),标记0-7。删除数据,head会向指向1
,把0
位置数据置为null(队列是先进先出)。再插入数据,tail则会指向0
newtail = (tail + 1) % capacity
也就是说,整个ArrayQueue是循环的,删除元素总是把head指向的内存地址置为null,添加元素总是插在tail指向的位置,整个存储结构虽然是连续的一段内存,但却像是一个圆环。
转载自:https://juejin.cn/post/6952767846766084104