From a4464bb67476d9ffe234e37c4bd2d587af6bec53 Mon Sep 17 00:00:00 2001 From: Amal Bijoy Date: Tue, 7 Apr 2026 12:12:33 +0530 Subject: [PATCH] Enhance bounded queue demo with expected-vs-got checks --- Data-Structures/Queue/BoundedQueue.java | 32 +++++++++++++++++++++---- 1 file changed, 27 insertions(+), 5 deletions(-) diff --git a/Data-Structures/Queue/BoundedQueue.java b/Data-Structures/Queue/BoundedQueue.java index 0e6ba63..a93ed02 100644 --- a/Data-Structures/Queue/BoundedQueue.java +++ b/Data-Structures/Queue/BoundedQueue.java @@ -1,15 +1,37 @@ +import java.util.NoSuchElementException; import java.util.concurrent.ArrayBlockingQueue; public class BoundedQueue { + private static void printCheck(String label, Object expected, Object got) { + System.out.println(label + " -> Expected: " + expected + " | Got: " + got); + } + public static void main(String[] args) { - ArrayBlockingQueue boundedQueue = new ArrayBlockingQueue<>(2); - System.out.println("The elements are: "); + ArrayBlockingQueue boundedQueue = new ArrayBlockingQueue<>(2); + + printCheck("Initial queue", "[]", boundedQueue.toString()); + boundedQueue.add(10); boundedQueue.add(20); + printCheck("After adding 10, 20", "[10, 20]", boundedQueue.toString()); + boolean inserted = boundedQueue.offer(30); - if (!inserted) { - System.out.println("Insertion failed: queue capacity reached."); + printCheck("offer(30) when full", false, inserted); + + printCheck("peek() on non-empty queue", 10, boundedQueue.peek()); + printCheck("poll() on non-empty queue", 10, boundedQueue.poll()); + printCheck("Queue after poll()", "[20]", boundedQueue.toString()); + printCheck("remove() on non-empty queue", 20, boundedQueue.remove()); + printCheck("Queue after remove()", "[]", boundedQueue.toString()); + + printCheck("peek() on empty queue", null, boundedQueue.peek()); + printCheck("poll() on empty queue", null, boundedQueue.poll()); + + try { + boundedQueue.remove(); + printCheck("remove() on empty queue", "NoSuchElementException", "No exception"); + } catch (NoSuchElementException ex) { + printCheck("remove() on empty queue", "NoSuchElementException", ex.getClass().getSimpleName()); } - System.out.print(boundedQueue); } }