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<>();
queue.add("Apple");
queue.add("Banana");
queue.add("Cherry");
System.out.println(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<>();
queue.add("Apple");
queue.add("Banana");
queue.add("Cherry");
System.out.println("Removed: " + queue.remove()); // Output: Removed: Apple
System.out.println(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<>();
queue.add("Apple");
queue.add("Banana");
System.out.println("Head: " + queue.peek()); // Output: Head: Apple
System.out.println(queue); // Output: [Apple, Banana]
4. isEmpty()
--------------------
- Description: Returns true if the queue is empty; otherwise false.
- Example:
Queue<String> queue = new LinkedList<>();
queue.add("Apple");
System.out.println("Is queue empty? " + queue.isEmpty()); // Output: false
queue.remove();
System.out.println("Is queue empty? " + queue.isEmpty()); // Output: true
5. size()
--------------------
- Description: Returns the number of elements in the queue.
- Example:
Queue<String> queue = new LinkedList<>();
queue.add("Apple");
queue.add("Banana");
queue.add("Cherry");
System.out.println("Queue size: " + queue.size()); // Output: Queue size: 3