A Recent Items List in Java
Over the last few months, I have been tinkering around with a genealogy app for Java - which you can find at https://github.com/sjmeunier/arbor-familiae.
One of the features I implemented was a list of recently viewed individuals, and while implementing that I discovered a few useful methods in Java’s list classes, which made this a piece of cake.
The principle of a recent list is a simple list, constrained by a maximum size, where new items are added to the front of the list (index 0), and any items exceeding the max length are removed.
One tricky thing that popped up, is that when adding an item to the list, it should check that the item is not already in the list. If so, the item should be moved to the front of the list, and only one instance of that value should ever be in the list.
In the code below, almost all the magic happens in the addItem() method. This method, as described above, removes an existing item, if it already occurs, adds the item at position 0, and finally removes the last item if the size exceeds the maximum.
This can all be implemented using arrays, instead of a list, but the extra methods of being able to add or remove items at certain positions without having to update the rest of the list independantly makes lists a very clean implementation.