If it reaches this maximum value, I want to delete the oldest object (index 0)
Then do wordHist.remove(0) . This will remove the item with index 0.
To be precise:
wordHist.add(new Word("hello")); if (wordHist.size() > MAX_SIZE) wordHist.remove(0);
At the same time, like user658991, you should know that this is a linear operation, i.e. time is proportional to the number of items in the list.
You can do this all the time using the LinkedList add and removeFirst .
Another option is to wrap an array or ArrayList in a class called something like CircularArrayList . In circular list structures, you will override the oldest item when adding a new one.
Edit:
Your code works fine:
import java.util.*; class Test { static int WORDHIST_MAX_COUNT = 3; static List<String> wordHist = new ArrayList<String>(); public static void add(String currentWord) {
Print
i: 0, word: a i: 1, word: b i: 2, word: c i: 0, word: b <-- b is now at index 0. i: 1, word: c i: 2, word: d
source share