1、数组大小需确定
2、队列满时数组有一个空间无法利用
import java.util.Arrays;
/**
* @author: zxh
* @date: 2021/5/24 14:07
*/
public class QueueArray {
private String[] items;
private int count;
private int head;
private int tail;
public QueueArray(int count) {
items = new String[count];
this.count = count;
head = 0;
tail = 0;
}
public boolean add(String item){
if (tail == count || (tail + 1) % count == head){
return false;
}
items[tail] = item;
tail = (tail + 1) % count;
return true;
}
public String get(){
if (tail == head){
return null;
}
String item = items[head];
items[head] = null;
head = (head + 1) % count;
return item;
}
@Override
public String toString() {
return "QueueArray{" +
"items=" + Arrays.toString(items) +
'}';
}
public static void main(String[] args) {
QueueArray queueArray = new QueueArray(8);
for (int i = 0; i < 7; i++) {
queueArray.add(i+"");
}
System.out.println(queueArray);
System.out.println(queueArray.get());
System.out.println(queueArray.get());
System.out.println(queueArray);
queueArray.add("7");
queueArray.add("8");
System.out.println(queueArray);
}
}
QueueArray{items=[0, 1, 2, 3, 4, 5, 6, null]}
0
1
QueueArray{items=[null, null, 2, 3, 4, 5, 6, null]}
QueueArray{items=[8, null, 2, 3, 4, 5, 6, 7]}