开发者

Fixed size data structure in java

I want a data structure(multi-threaded environment) in java tha开发者_开发技巧t can hold up to a maximum of 'n' elements. If i add (n + 1)th element, then i should replace the oldest element with this new element. I know i can do it by checking for the size in each add() and doing the replace operation at full size. But, i would like to know if there is any data structure in java library for this. Please help


Try using a fixed size array, and add using the index modulo size. This is known as circular array, Wikipedia has decent article on the subject.

Basically, you keep track of an index where you should write the next entry, and let that index wrap around at the buffer size, then when you keep writing, you'll overwrite the entries which are oldest.

Something like this:

Object[] ring = new Object[32];
int writeIndex = 0;

public void add(Object o) {
  ring[writeIndex % ring.length] = o;
  writeIndex++;
}


this is a Circular Queue and there is no java native class for this. you can look at ArrayCircularQueue.


One way to do it, depending on your needs, is to wrap a subclass of LinkedHashMap.

import java.util.AbstractSet;
import java.util.Iterator;
import java.util.LinkedHashMap;

public class FixedSizeSet<E> extends AbstractSet<E> {
    private final LinkedHashMap<E, E> contents;

    FixedSizeSet(final int maxCapacity) {
        contents = new LinkedHashMap<E, E>(maxCapacity * 4 /3, 0.75f, false) {
            @Override
            protected boolean removeEldestEntry(java.util.Map.Entry<E, E> eldest) {
                return size() == maxCapacity;
            }
        };      
    }

    @Override
    public Iterator<E> iterator() {
        return contents.keySet().iterator();
    }

    @Override
    public int size() {
        return contents.size();
    }

    public boolean add(E e) {
        boolean hadNull = false;
        if (e == null) {
            hadNull = contents.containsKey(null);
        }
        E previous = contents.put(e, e);
        return e == null ? hadNull : previous != null;
    }

    @Override
    public boolean contains(Object o) {
        return contents.containsKey(o);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜