0

Here's my idea on how to manage a simple circular buffer using arraylist. I've looked around and all the other circular lists seem overly complicated. If you don't worry about things like sorted lists then I think this is better, but I would like to get your feedback

public class CircularBuffer
{
   //the number of records in the circular arraylist. 
   //I've made the members static so everyone can use the same buffer
   private static ArrayList<Integer> circularList = new ArrayList<>();
   //the number of records in the circular arraylist
   private static final int circularArraySize = 30;

    //Use this function to add an element to the buffer
    public static void addElement(Integer item)
    {
        circularList.add(item);
        //Drop an old record if the size gets too big
        if (circularList.size() > circularArraySize)
        {
//Here is where I'm not sure. 
//If I remove index 0 from the list it should in theory be the oldest element in the list right?   
            circularList.remove(0);
        }
    }//end addCashup

    public static Integer getIndex(int index)
    {
       if (index > circularArraySize || index > circularList.size())
       {
          //handle out of bound index
       }
       return circularList.get(index);
    }
}
Bugz
  • 118
  • 1
  • 9
  • If this piece of code works, it better belongs on Code Review. – Eran Dec 10 '19 at 11:04
  • I think what you're doing is usually called ring buffer, here they're [discussing some](https://stackoverflow.com/questions/7266042/ring-buffer-in-java) – Curiosa Globunznik Dec 10 '19 at 11:20
  • Probably should fill in `//handle out of bound index` before posting to Code Review, but otherwise looks like a not off-topic question. – Peilonrayz Dec 10 '19 at 12:34

0 Answers0