hasan's blog (বল্গ)

work for fun!!!

Archive for September 12th, 2006

Java Limited list

with one comment

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();
    }

}

Written by nhm tanveer hossain khan

September 12, 2006 at 6:26 pm

Posted in Java