From f2957bf7ea227e9521d08e8da3e2f2ed1473cd6e Mon Sep 17 00:00:00 2001 From: priyank-sriv Date: Mon, 15 Jun 2020 01:17:30 +0530 Subject: [PATCH] circular buffer implementation --- .../circularbuffer/CircularBuffer.java | 73 +++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 data-structures/src/main/java/com/baeldung/circularbuffer/CircularBuffer.java diff --git a/data-structures/src/main/java/com/baeldung/circularbuffer/CircularBuffer.java b/data-structures/src/main/java/com/baeldung/circularbuffer/CircularBuffer.java new file mode 100644 index 0000000000..c36831636f --- /dev/null +++ b/data-structures/src/main/java/com/baeldung/circularbuffer/CircularBuffer.java @@ -0,0 +1,73 @@ +package com.baeldung.circularbuffer; + +public class CircularBuffer { + + private int capacity, writeIndex, readIndex; + private E[] data; + + @SuppressWarnings("unchecked") + public CircularBuffer(int capacity) { + + this.capacity = capacity; + this.data = (E[]) new Object[capacity]; + + this.readIndex = 0; + this.writeIndex = -1; + } + + public boolean offer(E element) { + + if (!isFull()) { + + writeIndex += 1; + int nextWriteIndex = writeIndex % capacity; + data[nextWriteIndex] = element; + + return true; + } + + return false; + } + + public E poll() { + + if (!isEmpty()) { + + int nextReadIndex = readIndex % capacity; + readIndex += 1; + + return data[nextReadIndex]; + } + + return null; + } + + public E peek() { + + if (!isEmpty()) { + + return data[readIndex % capacity]; + } + + return null; + } + + public int capacity() { + return capacity; + } + + public int size() { + + return (writeIndex - readIndex) + 1; + } + + public boolean isEmpty() { + + return writeIndex < readIndex; + } + + public boolean isFull() { + + return size() >= capacity; + } +}