A container for keeping a list of recent objects.
git-svn-id: https://samskivert.googlecode.com/svn/trunk@1032 6335cc39-0255-0410-8fd6-9bcaacd3b74c
This commit is contained in:
@@ -0,0 +1,91 @@
|
||||
//
|
||||
// $Id: RecentList.java,v 1.1 2003/01/21 21:46:31 mdb Exp $
|
||||
|
||||
package com.samskivert.util;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* An array list that maintains a list of the N most recent entries added
|
||||
* to it.
|
||||
*/
|
||||
public class RecentList
|
||||
{
|
||||
/**
|
||||
* Constructs a recent list that keeps the specified number of most
|
||||
* recently added objects.
|
||||
*/
|
||||
public RecentList (int keepCount)
|
||||
{
|
||||
_list = new Object[keepCount];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of elements in this list.
|
||||
*/
|
||||
public int size ()
|
||||
{
|
||||
return Math.min(_lastPos, _list.length);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears the list.
|
||||
*/
|
||||
public void clear ()
|
||||
{
|
||||
Arrays.fill(_list, null);
|
||||
_lastPos = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the specified value to the list.
|
||||
*/
|
||||
public void add (Object value)
|
||||
{
|
||||
_list[_lastPos++ % _list.length] = value;
|
||||
// keep last pos cycling from keepCount to 2*keepCount-1
|
||||
if (_lastPos == 2*_list.length) {
|
||||
_lastPos = _list.length;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the supplied value is equal (using {@link
|
||||
* Object#equals}) to any value in the list.
|
||||
*/
|
||||
public boolean contains (Object value)
|
||||
{
|
||||
for (int ii = 0, ll = _list.length; ii < ll; ii++) {
|
||||
if (_list[ii] != null && _list[ii].equals(value)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the Nth most recently added value from the list.
|
||||
* <code>null</code> is returned if the list does not contain at least
|
||||
* <code>index+1</code> entries.
|
||||
*/
|
||||
public Object get (int index)
|
||||
{
|
||||
return _list[(_lastPos-index-1+_list.length)%_list.length];
|
||||
}
|
||||
|
||||
public static void main (String[] args)
|
||||
{
|
||||
RecentList list = new RecentList(5);
|
||||
for (int ii = 0; ii < 10; ii++) {
|
||||
list.add(new Integer(ii));
|
||||
}
|
||||
System.out.println("Contains 3 " + list.contains(new Integer(3)));
|
||||
System.out.println("Contains 7 " + list.contains(new Integer(7)));
|
||||
for (int ii = 0; ii < list.size(); ii++) {
|
||||
System.out.println(ii + " => " + list.get(ii));
|
||||
}
|
||||
}
|
||||
|
||||
protected Object[] _list;
|
||||
protected int _lastPos;
|
||||
}
|
||||
Reference in New Issue
Block a user