简书 賈小強
转载请注明原创出处,谢谢!
package com.lab1.test1;
import java.util.Iterator;
public class ArrayQueue<Item> implements Iterable<Item> {
private int n;
private int first;
private int last;
@SuppressWarnings("unchecked")
private Item[] a = (Item[]) new Object[2];
@Override
public Iterator<Item> iterator() {
return new ListIterator();
}
private class ListIterator implements Iterator<Item> {
int i = 0;
@Override
public boolean hasNext() {
return i < n;
}
@Override
public Item next() {
Item item = a[(first + i) % a.length];
i++;
return item;
}
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
for (Item item : this) {
builder.append(item + " ");
}
return builder.toString();
}
private boolean isEmpty() {
return n == 0;
}
private int size() {
return n;
}
private void enqueue(Item item) {
if (n == a.length) {
resize(a.length * 2);
}
a[last++] = item;
n++;
if (last == a.length) {
last = 0;
}
}
private Item dequeue() {
Item item = a[first];
a[first] = null;
first++;
if (first == a.length) {
first = 0;
}
n--;
if (n > 0 && n == a.length / 4) {
resize(a.length / 2);
}
return item;
}
@SuppressWarnings("unchecked")
private void resize(int capacity) {
Item[] temp = (Item[]) new Object[capacity];
for (int i = 0; i < n; i++) {
temp[i] = a[(first + i) % a.length];
}
a = temp;
first=0;
last=n;
}
public static void main(String[] args) {
ArrayQueue<String> queue = new ArrayQueue<>();
System.out.println(queue);
System.out.println(queue.size());
System.out.println(queue.isEmpty());
queue.enqueue("bill");
queue.enqueue("jack");
queue.enqueue("lucy");
System.out.println(queue);
System.out.println(queue.size());
System.out.println(queue.isEmpty());
queue.dequeue();
queue.dequeue();
System.out.println(queue);
System.out.println(queue.size());
System.out.println(queue.isEmpty());
}
}
输出
0
true
bill jack lucy
3
false
lucy
1
false
Happy learning !!