I would like to create a list in java that while adding new element, will check if limit was reached. If it was, delete oldest element.
I was thinking about making child of ArrayList and overriding add(Object). In there i would make that:
if(size() + 1 > MAX)
remove(get(0));
super.add(newObject);
Any better way?
There are probably a number of solutions to this, but I think that yours is a suitable approach if you make one change: your underlying implementation class should be a LinkedList, not an ArrayList. The reason is that when you call remove on an ArrayList every element after the removed value must be shifted up (making remove(0) the very worst case!). However this is not a problem for a LinkedList.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With