Implement a generic fixed-capacity circular queue (ring buffer) with offer, poll, peek and size, using an Object array internally with a safe unchecked cast; test with log messages.
Solution
Main.java
class RingBuffer<E> {
private final Object[] data; // cannot be new E[n]
private int head, size;
RingBuffer(int capacity) { data = new Object[capacity]; }
boolean offer(E e) {
if (size == data.length) return false;
data[(head + size) % data.length] = e;
size++;
return true;
}
@SuppressWarnings("unchecked") // safe: only E values are ever stored
E poll() {
if (size == 0) return null;
E e = (E) data[head];
data[head] = null;
head = (head + 1) % data.length;
size--;
return e;
}
@SuppressWarnings("unchecked")
E peek() { return size == 0 ? null : (E) data[head]; }
int size() { return size; }
}
public class Main {
public static void main(String[] args) {
RingBuffer<String> logs = new RingBuffer<>(3);
System.out.println(logs.offer("boot") + " " + logs.offer("login") + " " + logs.offer("view") + " " + logs.offer("pay"));
System.out.println(logs.poll() + " " + logs.offer("pay") + " " + logs.peek() + " " + logs.size());
StringBuilder sb = new StringBuilder();
String s;
while ((s = logs.poll()) != null) sb.append(s).append(' ');
System.out.println(sb.toString().trim() + " | empty=" + (logs.size() == 0));
}
}
The internal Object[] plus a narrowly suppressed unchecked cast is the standard way to build array-backed generic collections (ArrayList does the same).
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!