Queue Methods in Java
1. add(E e)
--------------------
- Description: Inserts the specified element at the end of the queue.
If it fails (due to capacity), it throws an exception (e.g., IllegalStateException).
- Example:
Queue<String> queue = new LinkedList<>();
[Link]("Apple");
[Link]("Banana");
[Link]("Cherry");
[Link](queue); // Output: [Apple, Banana, Cherry]
2. remove()
--------------------
- Description: Removes and returns the head of the queue.
If the queue is empty, it throws a NoSuchElementException.
- Example:
Queue<String> queue = new LinkedList<>();
[Link]("Apple");
[Link]("Banana");
[Link]("Cherry");
[Link]("Removed: " + [Link]()); // Output: Removed: Apple
[Link](queue); // Output: [Banana, Cherry]
3. peek()
--------------------
- Description: Returns the head of the queue without removing it.
If the queue is empty, it returns null.
- Example:
Queue<String> queue = new LinkedList<>();
[Link]("Apple");
[Link]("Banana");
[Link]("Head: " + [Link]()); // Output: Head: Apple
[Link](queue); // Output: [Apple, Banana]
4. isEmpty()
--------------------
- Description: Returns true if the queue is empty; otherwise false.
- Example:
Queue<String> queue = new LinkedList<>();
[Link]("Apple");
[Link]("Is queue empty? " + [Link]()); // Output: false
[Link]();
[Link]("Is queue empty? " + [Link]()); // Output: true
5. size()
--------------------
- Description: Returns the number of elements in the queue.
- Example:
Queue<String> queue = new LinkedList<>();
[Link]("Apple");
[Link]("Banana");
[Link]("Cherry");
[Link]("Queue size: " + [Link]()); // Output: Queue size: 3