hasan's blog (বল্গ)

work for fun!!!

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

One Response

Subscribe to comments with RSS.

  1. Im gonna check this out later on this week.
    Anyred, with the VB2005 there are a lot of interesting options to creat a list like that with almost no code.

    Redstar

    September 17, 2006 at 3:37 pm


Leave a Reply