Java clear()
The clear() method in Java Queue removes all elements from the queue, making it completely empty. This method is inherited from the Collection interface and provides a convenient way to reset a queue without creating a new instance.
Syntax
queueName.clear()
Parameters:
- This method does not take any parameters.
Return value:
- The method does not return any value (
void).
Example 1: Basic Queue Clear
This example demonstrates the fundamental usage of the clear() method with a LinkedList implementation of Queue:
import java.util.LinkedList;import java.util.Queue;public class QueueClearBasic {public static void main(String[] args) {// Create a queue using LinkedList implementationQueue<String> queue = new LinkedList<>();// Add elements to the queuequeue.offer("First");queue.offer("Second");queue.offer("Third");queue.offer("Fourth");// Display the original queueSystem.out.println("Original queue: " + queue);System.out.println("Queue size before clear: " + queue.size());// Clear all elements from the queuequeue.clear();// Display the queue after clearingSystem.out.println("Queue after clear: " + queue);System.out.println("Queue size after clear: " + queue.size());}}
The output of this code is:
Original queue: [First, Second, Third, Fourth]Queue size before clear: 4Queue after clear: []Queue size after clear: 0
This example creates a queue, adds four string elements, displays the original content, clears the queue, and then shows the empty result. The clear() method removes all elements but keeps the queue structure intact for future use.
Example 2: Task Processing System
This example illustrates how clear() can be utilized in a task processing system to reset the task queue after completing a batch of operations:
import java.util.LinkedList;import java.util.Queue;public class TaskProcessingSystem {public static void main(String[] args) {// Create a task queueQueue<String> taskQueue = new LinkedList<>();// Add tasks to the queuetaskQueue.offer("Process Payment");taskQueue.offer("Send Email");taskQueue.offer("Update Database");taskQueue.offer("Generate Report");taskQueue.offer("Backup Data");System.out.println("Tasks in queue: " + taskQueue);System.out.println("Total tasks: " + taskQueue.size());// Process all taskswhile (!taskQueue.isEmpty()) {String currentTask = taskQueue.poll();System.out.println("Processing: " + currentTask);}System.out.println("All tasks completed. Queue status: " + taskQueue);// Add new batch of taskstaskQueue.offer("Daily Cleanup");taskQueue.offer("System Maintenance");System.out.println("New tasks added: " + taskQueue);// Clear the queue for emergency resetSystem.out.println("Emergency reset triggered!");taskQueue.clear();System.out.println("Queue after emergency clear: " + taskQueue);System.out.println("Ready for new tasks: " + taskQueue.isEmpty());}}
The output of this code is:
Tasks in queue: [Process Payment, Send Email, Update Database, Generate Report, Backup Data]Total tasks: 5Processing: Process PaymentProcessing: Send EmailProcessing: Update DatabaseProcessing: Generate ReportProcessing: Backup DataAll tasks completed. Queue status: []New tasks added: [Daily Cleanup, System Maintenance]Emergency reset triggered!Queue after emergency clear: []Ready for new tasks: true
This example demonstrates a realistic scenario where a task processing system uses clear() for emergency resets or batch completions. The method provides a quick way to empty the queue without affecting its functionality.
Example 3: Cache Management System
This example illustrates how clear() is useful in cache management systems where periodic cache clearing is necessary for memory optimization:
import java.util.PriorityQueue;import java.util.Queue;public class CacheManagementSystem {public static void main(String[] args) {// Create a priority queue for cache managementQueue<Integer> cacheQueue = new PriorityQueue<>();// Simulate adding cache entries with priority valuescacheQueue.offer(10); // Low prioritycacheQueue.offer(5); // High prioritycacheQueue.offer(15); // Lower prioritycacheQueue.offer(3); // Highest prioritycacheQueue.offer(12); // Medium prioritySystem.out.println("Cache entries (priority order): " + cacheQueue);System.out.println("Cache size: " + cacheQueue.size());System.out.println("Highest priority item: " + cacheQueue.peek());// Simulate cache usageSystem.out.println("\nProcessing cache entries:");Queue<Integer> tempQueue = new PriorityQueue<>(cacheQueue);while (!tempQueue.isEmpty()) {System.out.println("Accessing cache entry: " + tempQueue.poll());}// Check memory usage and clear cache if neededboolean memoryThresholdExceeded = true; // Simulated conditionif (memoryThresholdExceeded) {System.out.println("\nMemory threshold exceeded. Clearing cache...");cacheQueue.clear();System.out.println("Cache cleared successfully.");System.out.println("Current cache size: " + cacheQueue.size());System.out.println("Cache is empty: " + cacheQueue.isEmpty());// Cache is now ready for new entriesSystem.out.println("\nCache system ready for new entries.");}}}
The output of this code is:
Cache entries (priority order): [3, 5, 15, 10, 12]Cache size: 5Highest priority item: 3Processing cache entries:Accessing cache entry: 3Accessing cache entry: 5Accessing cache entry: 10Accessing cache entry: 12Accessing cache entry: 15Memory threshold exceeded. Clearing cache...Cache cleared successfully.Current cache size: 0Cache is empty: trueCache system ready for new entries.
The following text explains how the clear() method works with different Queue implementations, such as PriorityQueue. This method is particularly useful in cache management systems where there is a need to periodically clear cached data to free up memory.
Frequently Asked Questions
1. Does the clear() method destroy the queue object?
No, the clear() method only removes all elements from the queue but preserves the queue structure. You can continue using the same queue instance after clearing it.
2. What is the time complexity of the clear() method?
The time complexity is typically O(n) where n is the number of elements in the queue, as it needs to remove each element. However, some implementations may optimize this operation.
3. Can I use clear() on thread-safe queue implementations?
Yes, the clear() method works with thread-safe queue implementations like LinkedBlockingQueue and ConcurrentLinkedQueue. The operation remains thread-safe in these implementations.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Java on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
- Beginner Friendly.17 hours