LearnFrenzy
Sign in Take a free test

Generics · Generics Programs · Question 7

Generic bounded circular queue in Java Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

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));
    }
}

Output Verified by compiling and running

true true true false
boot true login 3
login view pay | empty=true

The internal Object[] plus a narrowly suppressed unchecked cast is the standard way to build array-backed generic collections (ArrayList does the same).

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links