Repository: TheAlgorithms/Java
Pull request #5354 (2024-08-20 22:16:35)

refactor: `CircularQueue`
Make CircularQueue generic.
Readability improvements.
Added tests.

<!--
Thank you for your contribution!
In order to reduce the number of notifications sent to the maintainers, please:
- create your PR as draft, cf. https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests#draft-pull-requests,
- make sure that all of the CI checks pass,
- mark your PR as ready for review, cf. https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/changing-the-stage-of-a-pull-request#marking-a-pull-request-as-ready-for-review
-->

<!-- For completed items, change [ ] to [x] -->

- [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Java/blob/master/CONTRIBUTING.md).
- [x] This pull request is all my own work -- I have not plagiarized it.
- [x] All filenames are in PascalCase.
- [x] All functions and variable names follow Java naming conventions.
- [x] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations.
- [x] All new code is formatted with `clang-format -i --style=file path/to/your/file.java`

codecov-commenter: ## [Codecov](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5354?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) Report
Attention: Patch coverage is `65.00000%` with `14 lines` in your changes missing coverage. Please review.
> Project coverage is 44.60%. Comparing base [(`f5c0314`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/f5c0314111f5973748862e21d6e7ccbb9e53a3ee?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) to head [(`63c0312`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/63c0312c0125c074fb4022029043301864be18ec?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).

| [Files](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5354?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) | Patch % | Lines |
|---|---|---|
| [...lgorithms/datastructures/queues/CircularQueue.java](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5354?src=pr&el=tree&filepath=src%2Fmain%2Fjava%2Fcom%2Fthealgorithms%2Fdatastructures%2Fqueues%2FCircularQueue.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms#diff-c3JjL21haW4vamF2YS9jb20vdGhlYWxnb3JpdGhtcy9kYXRhc3RydWN0dXJlcy9xdWV1ZXMvQ2lyY3VsYXJRdWV1ZS5qYXZh) | 65.00% | [14 Missing :warning: ](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5354?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) |

<details><summary>Additional details and impacted files</summary>


```diff
@@             Coverage Diff              @@
##             master    #5354      +/-   ##
============================================
+ Coverage     44.38%   44.60%   +0.22%     
- Complexity     2752     2765      +13     
============================================
  Files           522      522              
  Lines         15419    15413       -6     
  Branches       2942     2939       -3     
============================================
+ Hits           6843     6875      +32     
+ Misses         8282     8242      -40     
- Partials        294      296       +2     
```

</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5354?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).   
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).


Patch:
diff --git a/src/main/java/com/thealgorithms/datastructures/queues/CircularQueue.java b/src/main/java/com/thealgorithms/datastructures/queues/CircularQueue.java
index 48d9ffe9..c67817a6 100644
--- a/src/main/java/com/thealgorithms/datastructures/queues/CircularQueue.java
+++ b/src/main/java/com/thealgorithms/datastructures/queues/CircularQueue.java
@@ -2,106 +2,100 @@ package com.thealgorithms.datastructures.queues;
 
 // This program implements the concept of CircularQueue in Java
 // Link to the concept: (https://en.wikipedia.org/wiki/Circular_buffer)
-public class CircularQueue {
-
-    int[] arr;
-    int topOfQueue;
-    int beginningOfQueue;
-    int size;
+public class CircularQueue<T> {
+    private T[] array;
+    private int topOfQueue;
+    private int beginningOfQueue;
+    private final int size;
+    private int currentSize;
 
+    @SuppressWarnings("unchecked")
     public CircularQueue(int size) {
-        arr = new int[size];
-        topOfQueue = -1;
-        beginningOfQueue = -1;
+        this.array = (T[]) new Object[size];
+        this.topOfQueue = -1;
+        this.beginningOfQueue = -1;
         this.size = size;
+        this.currentSize = 0;
     }
 
     public boolean isEmpty() {
-        return beginningOfQueue == -1;
+        return currentSize == 0;
     }
 
     public boolean isFull() {
-        if (topOfQueue + 1 == beginningOfQueue) {
-            return true;
-        } else {
-            return topOfQueue == size - 1 && beginningOfQueue == 0;
-        }
+        return currentSize == size;
     }
 
-    public void enQueue(int value) {
+    public void enQueue(T value) {
         if (isFull()) {
-            System.out.println("The Queue is full!");
-        } else if (isEmpty()) {
+            throw new IllegalStateException("Queue is full");
+        }
+        if (isEmpty()) {
             beginningOfQueue = 0;
-            topOfQueue++;
-            arr[topOfQueue] = value;
-            System.out.println(value + " has been successfully inserted!");
-        } else {
-            if (topOfQueue + 1 == size) {
-                topOfQueue = 0;
-            } else {
-                topOfQueue++;
-            }
-            arr[topOfQueue] = value;
-            System.out.println(value + " has been successfully inserted!");
         }
+        topOfQueue = (topOfQueue + 1) % size;
+        array[topOfQueue] = value;
+        currentSize++;
     }
 
-    public int deQueue() {
+    public T deQueue() {
+        if (isEmpty()) {
+            throw new IllegalStateException("Queue is empty");
+        }
+        T removedValue = array[beginningOfQueue];
+        array[beginningOfQueue] = null; // Optional: Help GC
+        beginningOfQueue = (beginningOfQueue + 1) % size;
+        currentSize--;
         if (isEmpty()) {
-            System.out.println("The Queue is Empty!");
-            return -1;
-        } else {
-            int res = arr[beginningOfQueue];
-            arr[beginningOfQueue] = Integer.MIN_VALUE;
-            if (beginningOfQueue == topOfQueue) {
-                beginningOfQueue = -1;
-                topOfQueue = -1;
-            } else if (beginningOfQueue + 1 == size) {
-                beginningOfQueue = 0;
-            } else {
-                beginningOfQueue++;
-            }
-            return res;
+            beginningOfQueue = -1;
+            topOfQueue = -1;
         }
+        return removedValue;
     }
 
-    public int peek() {
+    public T peek() {
         if (isEmpty()) {
-            System.out.println("The Queue is Empty!");
-            return -1;
-        } else {
-            return arr[beginningOfQueue];
+            throw new IllegalStateException("Queue is empty");
         }
+        return array[beginningOfQueue];
     }
 
     public void deleteQueue() {
-        arr = null;
-        System.out.println("The Queue is deleted!");
+        array = null;
+        beginningOfQueue = -1;
+        topOfQueue = -1;
+        currentSize = 0;
+    }
+
+    public int size() {
+        return currentSize;
     }
 
     public static void main(String[] args) {
-        CircularQueue cq = new CircularQueue(5);
-        System.out.println(cq.isEmpty());
-        System.out.println(cq.isFull());
+        CircularQueue<Integer> cq = new CircularQueue<>(5);
+        System.out.println(cq.isEmpty()); // true
+        System.out.println(cq.isFull()); // false
         cq.enQueue(1);
         cq.enQueue(2);
         cq.enQueue(3);
         cq.enQueue(4);
         cq.enQueue(5);
 
-        System.out.println(cq.deQueue());
-        System.out.println(cq.deQueue());
-        System.out.println(cq.deQueue());
-        System.out.println(cq.deQueue());
-        System.out.println(cq.deQueue());
-        System.out.println(cq.isFull());
-        System.out.println(cq.isEmpty());
+        System.out.println(cq.deQueue()); // 1
+        System.out.println(cq.deQueue()); // 2
+        System.out.println(cq.deQueue()); // 3
+        System.out.println(cq.deQueue()); // 4
+        System.out.println(cq.deQueue()); // 5
+
+        System.out.println(cq.isFull()); // false
+        System.out.println(cq.isEmpty()); // true
         cq.enQueue(6);
         cq.enQueue(7);
         cq.enQueue(8);
-        System.out.println(cq.peek());
-        System.out.println(cq.peek());
+
+        System.out.println(cq.peek()); // 6
+        System.out.println(cq.peek()); // 6
+
         cq.deleteQueue();
     }
 }


Test patch:
diff --git a/src/test/java/com/thealgorithms/datastructures/queues/CircularQueueTest.java b/src/test/java/com/thealgorithms/datastructures/queues/CircularQueueTest.java
new file mode 100644
index 00000000..71dca8fd
--- /dev/null
+++ b/src/test/java/com/thealgorithms/datastructures/queues/CircularQueueTest.java
@@ -0,0 +1,106 @@
+package com.thealgorithms.datastructures.queues;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import org.junit.jupiter.api.Test;
+
+class CircularQueueTest {
+
+    @Test
+    void testEnQueue() {
+        CircularQueue<Integer> cq = new CircularQueue<>(3);
+        cq.enQueue(1);
+        cq.enQueue(2);
+        cq.enQueue(3);
+
+        assertEquals(1, cq.peek());
+        assertTrue(cq.isFull());
+    }
+
+    @Test
+    void testDeQueue() {
+        CircularQueue<Integer> cq = new CircularQueue<>(3);
+        cq.enQueue(1);
+        cq.enQueue(2);
+        cq.enQueue(3);
+
+        assertEquals(1, cq.deQueue());
+        assertEquals(2, cq.peek());
+        assertFalse(cq.isFull());
+    }
+
+    @Test
+    void testIsEmpty() {
+        CircularQueue<Integer> cq = new CircularQueue<>(3);
+        assertTrue(cq.isEmpty());
+
+        cq.enQueue(1);
+        assertFalse(cq.isEmpty());
+    }
+
+    @Test
+    void testIsFull() {
+        CircularQueue<Integer> cq = new CircularQueue<>(2);
+        cq.enQueue(1);
+        cq.enQueue(2);
+        assertTrue(cq.isFull());
+
+        cq.deQueue();
+        assertFalse(cq.isFull());
+    }
+
+    @Test
+    void testPeek() {
+        CircularQueue<Integer> cq = new CircularQueue<>(3);
+        cq.enQueue(1);
+        cq.enQueue(2);
+
+        assertEquals(1, cq.peek());
+        assertEquals(1, cq.peek()); // Ensure peek doesn't remove the element
+    }
+
+    @Test
+    void testDeleteQueue() {
+        CircularQueue<Integer> cq = new CircularQueue<>(3);
+        cq.enQueue(1);
+        cq.enQueue(2);
+        cq.deleteQueue();
+
+        org.junit.jupiter.api.Assertions.assertThrows(IllegalStateException.class, cq::peek);
+    }
+
+    @Test
+    void testEnQueueOnFull() {
+        CircularQueue<Integer> cq = new CircularQueue<>(2);
+        cq.enQueue(1);
+        cq.enQueue(2);
+
+        org.junit.jupiter.api.Assertions.assertThrows(IllegalStateException.class, () -> cq.enQueue(3));
+    }
+
+    @Test
+    void testDeQueueOnEmpty() {
+        CircularQueue<Integer> cq = new CircularQueue<>(2);
+        org.junit.jupiter.api.Assertions.assertThrows(IllegalStateException.class, cq::deQueue);
+    }
+
+    @Test
+    void testPeekOnEmpty() {
+        CircularQueue<Integer> cq = new CircularQueue<>(2);
+        org.junit.jupiter.api.Assertions.assertThrows(IllegalStateException.class, cq::peek);
+    }
+
+    @Test
+    void testSize() {
+        CircularQueue<Integer> cq = new CircularQueue<>(3);
+        cq.enQueue(1);
+        cq.enQueue(2);
+
+        assertEquals(2, cq.size());
+
+        cq.deQueue();
+        assertEquals(1, cq.size());
+    }
+}