I'm looking for a good way, to build a limited linked list. If the linked list is "full", the first element will be removed and the new one will be added. So I always have the "newest" "limit-size" elements.
This is implemented in the following way:
private int maxSize;
public LimitedLinkedList(int maxSize) {
this.maxSize = maxSize;
}
@Override
public synchronized boolean add(E object) {
boolean success = super.add(object);
while (this.size() >= maxSize) {
removeFirst();
}
return success;
}
Now I have the following problem: I need to calculate the average of the linked-list. This is the moment, where I randomly get the concurrent modification exception or an index-out-of-bounds exception. My method for average:
public synchronized static double movingAverage(
LinkedList<AverageObject> valueList) {
if (valueList.isEmpty()) {
return 0;
}
double sum = 0;
int m = 0;
for (int i = 0; i < valueList.size(); i++) {
AverageObject object= valueList.get(i);
sum += object.value;
m++;
}
sum = (m != 0) ? sum / m : sum;
return sum;
}
Do you know a good way to avoid concurrent modification exceptions?
My only idea is, to calculate the average, everytime the list is changed, so I don't have to iterate through it, when I want to have the average.