I often need to store a fixed amount of frequently-changing information, like when I want to keep track of the last ten messages posted in a chat room or the five most recently viewed items in an online store.
In these situations I use a MaxSizeArrayCollection object I developed that works like a regular collection but with an enforced maximum size.
The beauty of this object is that it removes any need to manage the size or contents of the collection. No trimming, no sorting – no worries.
So how did I do it?
First off, I created a custom AS3 class that extends ArrayCollection and specifies a maximum size in the constructor. Second, I overrode the addItem() and addItemAt() methods to check the size of the collection before adding a new item.
When your collection is at its maximum size, you can take several actions depending on how to you want the collection to be maintained.
The method I used is to simply remove the first item in the collection before adding a new one (FIFO for those familiar with stacks and queues). This guarantees that my collection always contains the latest set of information.
Pretty nice huh?
Check out the sample code: