Advertisement
Guest User

RingBuffer

a guest
Jan 27th, 2021
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.39 KB | None | 0 0
  1. public class RingBuffer {
  2.     private int capacity;
  3.     private final BigDecimal[] data;
  4.     private int lastEntryIndex;
  5.  
  6.     public RingBuffer(int capacity) {
  7.         this.capacity = capacity;
  8.         this.data = new BigDecimal[capacity];
  9.     }
  10.  
  11.     public void setElement(BigDecimal element) {
  12.         int oldestElementIndex = getOldestElementIndex();
  13.         if (!isFull()) {
  14.             for (int i = 0; i < data.length; i++) {
  15.                 if (data[i] == null) {
  16.                     data[i] = element;
  17.                     lastEntryIndex = i;
  18.                     break;
  19.                 }
  20.             }
  21.         } else {
  22.             data[oldestElementIndex] = element;
  23.         }
  24.     }
  25.  
  26.     public int getOldestElementIndex() {
  27.         int oldestEntryIndex;
  28.         if ((lastEntryIndex == data.length - 1) || !isFull()) {
  29.             oldestEntryIndex = 0;
  30.         } else oldestEntryIndex = lastEntryIndex + 1;
  31.         return oldestEntryIndex;
  32.     }
  33.  
  34.     public boolean isFull() {
  35.         boolean hasNoNulls = false;
  36.         for (int i = 0; i < data.length; i++) {
  37.             hasNoNulls = data[i] != null;
  38.         }
  39.         return hasNoNulls;
  40.     }
  41.  
  42.     public int getCapacity() {
  43.         return capacity;
  44.     }
  45.  
  46.     public void setCapacity(int capacity) {
  47.         this.capacity = capacity;
  48.     }
  49.  
  50.     public BigDecimal[] getData() {
  51.         return data;
  52.     }
  53.  
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement