// 获取index索引位置的元素 public E get(int index){ if(index < 0 || index >= size) thrownew IllegalArgumentException("Get failed. Index is illegal."); return data[index]; }
public E getLast(){ return get(size - 1); }
public E getFirst(){ return get(0); }
// 修改index索引位置的元素为e publicvoidset(int index, E e){ if(index < 0 || index >= size) thrownew IllegalArgumentException("Set failed. Index is illegal."); data[index] = e; }
// 查找数组中是否有元素e publicbooleancontains(E e){ for(int i = 0 ; i < size ; i ++){ if(data[i].equals(e)) returntrue; } returnfalse; }
// 查找数组中元素e所在的索引,如果不存在元素e,则返回-1 publicintfind(E e){ for(int i = 0 ; i < size ; i ++){ if(data[i].equals(e)) return i; } return -1; }
// 从数组中删除index位置的元素, 返回删除的元素 public E remove(int index){ if(index < 0 || index >= size) thrownew IllegalArgumentException("Remove failed. Index is illegal.");
E ret = data[index]; for(int i = index + 1 ; i < size ; i ++) data[i - 1] = data[i]; size --; data[size] = null; // loitering objects != memory leak
@Override public E dequeue(){ return array.removeFirst(); }
@Override public E getFront(){ return array.getFirst(); }
@Override public String toString(){
StringBuilder res = new StringBuilder(); res.append("Queue: "); res.append("front [ "); for (int i = 0; i < array.getSize(); i++) { res.append(array.get(i)); if (i != array.getSize() - 1) res.append(", "); } res.append("] tail");
return res.toString(); }
publicstaticvoidmain(String[] args){ ArrayQueue<Integer> queue = new ArrayQueue <> (); System.out.println(); for (int i = 0; i < 100000; i++) { queue.enqueue(i); System.out.println(queue); if (i % 3 == 2) { queue.dequeue(); System.out.println(queue); } } } }
测试
复杂度分析
ArrayQueue<E>
void enqueue(E e)
O(1)均摊
E dequeue()
O(n)
E getFront
o(1)
int getSize
O(1)
boolean isEmpty()
O(1)
如果使用顺序队列的话,试想一下如果我们队列十分的大,那么我们需要耗费的时间是多少呢。
循环队列
队列首位相接的顺序存储结构。
通过这样的方法,我们成功避免了数据搬移操作。看起来不难理解在用数组实现的非循环队列中,队满的判断条件是 tail == n,队空的判断条件是 head == tail。那针对循环队列,如何判断队空和队满呢? 队列为空的判断条件仍然是 head == tail。但队列满的判断条件就稍微有点复杂了。
// 测试使用q运行opCount个enqueueu和dequeue操作所需要的时间,单位:秒 privatestaticdoubletestQueue(Queue<Integer> q, int opCount){
long startTime = System.nanoTime();
Random random = new Random(); for (int i = 0; i < opCount; i++) { q.enqueue(random.nextInt(Integer.MAX_VALUE)); } for (int i = 0; i < opCount; i++) { q.dequeue(); }