java数组实现队列,其中包含入队,出队,判断队列是否为空,是否为满,展示队列元素,展示队列长度的方法,队列元素类型为object,只用数组,不用集合
时间: 2024-09-29 07:11:10 浏览: 45
在Java中,我们可以使用数组来实现一个基于数组的简单队列。这里是一个基础的示例,假设队列最大容量为`MAX_SIZE`:
```java
public class ArrayQueue<T> {
private static final int MAX_SIZE = 10;
private T[] queueData; // 数组存储数据
private int front = -1, rear = -1; // 前端和后端指针
public ArrayQueue() {
this.queueData = (T[]) new Object[MAX_SIZE];
}
// 入队操作(Enqueue)
public void enqueue(T item) {
if (isFull()) {
throw new IllegalStateException("Queue is full");
}
rear = (rear + 1) % MAX_SIZE; // 使用环形数组,更新后端
queueData[rear] = item;
if (front == -1) {
front = rear; // 如果队列为空,更新前端
}
}
// 出队操作(Dequeue)
public T dequeue() {
if (isEmpty()) {
throw new IllegalStateException("Queue is empty");
}
T removedItem = queueData[front]; // 保存并移除前端元素
front = (front + 1) % MAX_SIZE; // 更新前端
if (front == rear) { // 队列变空
rear = -1;
}
return removedItem;
}
// 判断队列是否为空
public boolean isEmpty() {
return front == -1;
}
// 判断队列是否已满
public boolean isFull() {
return rear == (front + MAX_SIZE - 1) % MAX_SIZE; // 环形数组判断条件
}
// 展示队列元素(仅适用于非空队列)
public String displayElements() {
if (isEmpty()) {
return "Queue is empty";
}
StringBuilder sb = new StringBuilder();
for (int i = front; i != rear; i = (i + 1) % MAX_SIZE) {
sb.append(queueData[i]).append(", ");
}
sb.setLength(sb.length() - 2); // 去掉最后一个逗号
return sb.toString();
}
// 获取队列长度(实际长度)
public int size() {
if (isEmpty()) {
return 0;
} else {
return (rear - front + MAX_SIZE) % MAX_SIZE;
}
}
}
```
这个队列实现了基本的入队、出队功能,并且包含了判断队空、队满以及查看队列内容的方法。请注意,这是一个非常基础的实现,实际应用中可能需要添加更多的错误处理机制。
阅读全文
相关推荐

















