A fully featured generic Queue implementation in Java using a singly linked list.
This queue follows the FIFO (First In, First Out) principle and supports common operations as well as useful utility methods for flexibility and convenience.
- Generic: works with any type (
Queue<T>) - Core queue operations:
enqueue(T item)— add an element to the rear of the queuedequeue()— remove and return the front elementpeek()— return (without removing) the front elementpeekLast()— return (without removing) the rear elementisEmpty()— check if the queue is emptysize()— number of elements in the queue
- Iterable: supports iteration from front to rear with enhanced for-loops
- Utility methods:
clear()— empties the queuecontains(T item)— checks if the queue contains a given element (supportsnull)remove(T item)— removes the first occurrence of a specified elementoffer(T item)— adds an element (alias forenqueue)poll()— removes and returns the front element or returnsnullif emptytoArray()— returns an array of elements in FIFO orderclone()— creates a shallow copy of the queuereverse()— reverses the order of elements in the queue
- Properly overrides
equals(Object)andhashCode() - Throws
NoSuchElementExceptionwhen dequeuing or peeking from an empty queue - Well documented with Javadoc comments
Queue<Integer> queue = new Queue<>();
queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);
System.out.println(queue.peek()); // Output: 10
while (!queue.isEmpty()) {
System.out.println(queue.dequeue()); // Dequeues and prints: 10, 20, 30
}The implementation comes with comprehensive unit tests using JUnit 5.
To run the tests:
- Ensure you have JUnit 5 set up in your build system (Maven, Gradle, or your IDE).
- Run
QueueTest.javaas a JUnit test suite. - Tests cover normal operations, edge cases (empty queue,
nullelements), and utility methods.
- Internally implemented with a singly linked list (
Node<T>) for dynamic size and efficient enqueue/dequeue. - Iterator returns elements from front to rear.
- Supports
nullelements safely in methods likecontains(),equals(), andhashCode(). clone()creates a shallow copy preserving element order.reverse()modifies the queue in-place reversing the element order.
Queue<String> names = new Queue<>();
names.enqueue("Alice");
names.enqueue("Bob");
names.enqueue("Charlie");
names.reverse();
for (String name : names) {
System.out.println(name);
}
// Prints:
// Charlie
// Bob
// Alicetrigologiaa
This project is released under the MIT License. Feel free to use, modify, and distribute.
For questions or contributions, please open an issue or contact the author.