定长 fifo 队列 java
时间: 2023-10-11 15:27:52 浏览: 41
在 Java 中,可以使用数组来实现定长 FIFO 队列。以下是一个示例代码:
```java
public class FixedFifoQueue<T> {
private T[] queue;
private int head;
private int tail;
private int size;
public FixedFifoQueue(int capacity) {
this.queue = (T[]) new Object[capacity];
this.head = 0;
this.tail = 0;
this.size = 0;
}
public void enqueue(T item) {
if (size == queue.length) {
throw new IllegalStateException("Queue is full");
}
queue[tail] = item;
tail = (tail + 1) % queue.length;
size++;
}
public T dequeue() {
if (size == 0) {
throw new IllegalStateException("Queue is empty");
}
T item = queue[head];
queue[head] = null;
head = (head + 1) % queue.length;
size--;
return item;
}
public boolean isEmpty() {
return size == 0;
}
public boolean isFull() {
return size == queue.length;
}
public int size() {
return size;
}
}
```
在这个队列中,enqueue() 方法用于将元素添加到队列尾部,dequeue() 方法用于从队列头部移除元素并返回它。如果队列已满,将会抛出一个 IllegalStateException 异常;如果队列为空,将会抛出同样的异常。isEmpty() 方法用于判断队列是否为空,isFull() 方法用于判断队列是否已满,size() 方法用于获取队列中元素的数量。