0

I have a private arraylist with classes that include two longs, a float and a BigDecimal. As new data comes in I currently am removing the oldest element, shifiting all other elements over, and then adding the newest element. I think this is taking up a lot of memory uncessearly. So is there anyway to make this a circle, so I don't need to shift over elements in the array?

I'll include the relevenat parts of my code below:

private ArrayList<privStat> MyList = new ArrayList<privStat>();
public class privStat {
   long Stat1;
   long Stat2;
   float Stat3;
   BigDecimal Stat4;
}

NewStat = new privStat(//new message)
if (MyList.size() - 1 < 10) {
   MyList.add(NewStat);
} else {
   Mylist.remove(0);
   Mylist.add(NewStat);
}
Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138

3 Answers3

2

Sounds like you're trying to implement a queue in Java. Read this.

Java also provides a LinkedList class which can be easily implemented as a queue. Here's an example.

CFL_Jeff
  • 2,589
  • 3
  • 31
  • 49
1

Why not use a first-in, first-out data structure such as a Queue like LinkedList? This will allow you to add at the back of the queue, and remove from the front. Both operations will take constant time.

smessing
  • 4,330
  • 1
  • 22
  • 19
1

If I understood question right, you have to see to Queue class, I think it work more efficiently behind the scenes. (http://docs.oracle.com/javase/6/docs/api/java/util/Queue.html)

Or you can use array and mod operation (but it will be a circle, not queue):

PrivStat[] privStats=new PrivStat[10]();
int i=0;

and use next code for add:

privStats[i]=newStat;
i=(++i) % 10;
MikhailSP
  • 3,233
  • 1
  • 19
  • 29