lots of exercises in java... from https://github.com/exercism/java

CircularBuffer.java 900B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import java.util.LinkedList;
  2. import java.util.Queue;
  3. class CircularBuffer<T> {
  4. private Queue<T> buffer;
  5. private int capacity;
  6. CircularBuffer(int size) {
  7. this.buffer = new LinkedList<>();
  8. this.capacity = size;
  9. }
  10. T read() throws BufferIOException {
  11. if (this.buffer.size() == 0) {
  12. throw new BufferIOException("Tried to read from empty buffer");
  13. }
  14. return this.buffer.remove();
  15. }
  16. void write(T data) throws BufferIOException {
  17. if (this.buffer.size() == this.capacity) {
  18. throw new BufferIOException("Tried to write to full buffer");
  19. }
  20. this.buffer.add(data);
  21. }
  22. void overwrite(T data) {
  23. if (this.buffer.size() == this.capacity) {
  24. this.buffer.remove();
  25. }
  26. this.buffer.add(data);
  27. }
  28. void clear() {
  29. this.buffer.clear();
  30. }
  31. }