Java Limited list

sometimes, you may need a list objects which is limited by its’ fixed length.
let’s think: you need a maximum 10 items list.
if more value is added it will remove the last one and append on top of the list.

this code snap could be used for such purpose:

public class LimitedListCacheObject {

    private int listSize = 20;
    private LinkedList list = new LinkedList();

    public LimitedListCacheObject() { }

    public int getListSize() { return listSize; }

    public void setListSize(int listSize) { this.listSize = listSize; }

    public LinkedList getList() { return list; }

    public synchronized void addItem( Object o ) {
        _clearListLastItem();
        getList().addFirst( o );
    }

    private void _clearListLastItem() {
        if( getList().size() == listSize )
            // remove last item from the list
            getList().removeLast();
    }

}

my tweets

 

September 2006
S S M T W T F
« Aug   Oct »
 1
2345678
9101112131415
16171819202122
23242526272829
30  

Flickr Photos

@kamalapur over bridge

@kamalapur station

cox's bazaar trip oct 09

cox's bazaar trip oct 09

cast ur vote!

More Photos
Follow

Get every new post delivered to your Inbox.