Java中可用数组或链表实现泛型队列,需支持FIFO、enqueue/dequeue/peek/isEmpty;数组版用循环结构避免扩容,链表版更直观易懂,推荐初学使用。

Java 中可以用 数组 或 链表 实现一个简单的泛型队列,核心是支持泛型类型参数、遵循 FIFO(先进先出)原则,并提供基本的入队(enqueue)、出队(dequeue)、查看队首(peek)和判空(isEmpty)操作。
用数组实现泛型循环队列
避免频繁扩容和元素移动,采用循环数组更高效。需维护头索引(front)、尾索引(rear)和当前大小(或容量),注意判空与判满条件:
- 判空:`size == 0` 或 `front == rear`(初始状态)
- 判满:`(rear + 1) % capacity == front`(牺牲一个位置区分空/满)
- 入队:`array[rear] = item; rear = (rear + 1) % capacity; size++`
- 出队:`T item = array[front]; front = (front + 1) % capacity; size--`
用链表实现泛型队列(推荐初学)
更直观,无需处理索引和扩容逻辑。定义内部节点类,维护头(head)和尾(tail)引用:
Java项目代码review工具。分析Git变更+完整调用链路上下文,推断业务需求,进行多维度评分和分类汇总,生成完整PRD文档。包含细粒度Java代码审查清单(Null安全、异常处理、Streams、并发、equals/hashCode、资源管理、API设计、性能、MyBatis/ORM、事务边界、SQL/DD...
- 入队:新建节点,`tail.next = newNode; tail = newNode;`(若队列为空,同时更新 head)
- 出队:`T data = head.data; head = head.next;`(若出队后 head 为 null,则 tail 也置 null)
- peek:直接返回 `head.data`(非 null 时)
- isEmpty:`head == null`
完整示例(链表版)
以下是一个简洁可运行的泛型队列实现:
立即学习“Java免费学习笔记(深入)”;
public class SimpleQueue<T> {
private static class Node<T> {
T data;
Node<T> next;
Node(T data) { this.data = data; }
}
private Node<T> head;
private Node<T> tail;
private int size;
public void enqueue(T item) {
Node<T> newNode = new Node<>(item);
if (tail == null) {
head = tail = newNode;
} else {
tail.next = newNode;
tail = newNode;
}
size++;
}
public T dequeue() {
if (isEmpty()) throw new RuntimeException("Queue is empty");
T data = head.data;
head = head.next;
if (head == null) tail = null; // 队列变空
size--;
return data;
}
public T peek() {
if (isEmpty()) throw new RuntimeException("Queue is empty");
return head.data;
}
public boolean isEmpty() { return head == null; }
public int size() { return size; }
}
使用方式:SimpleQueue<String> q = new SimpleQueue<>(); q.enqueue("hello"); String s = q.dequeue();
注意事项
- 泛型类声明必须写成
class SimpleQueue<T>,方法中才能使用T - 不能用
new T[capacity]创建泛型数组,需用(T[]) new Object[capacity](带警告,但安全)或改用ArrayList<T> - 若需线程安全,可加
synchronized,或基于java.util.concurrent.ConcurrentLinkedQueue扩展 - 实际项目优先使用
java.util.Queue接口及其实现类(如LinkedList、ArrayDeque)

















