From a47caf48cbc87ae088c29972a6595ec258aeb050 Mon Sep 17 00:00:00 2001 From: mdb Date: Tue, 21 Jan 2003 21:46:31 +0000 Subject: [PATCH] A container for keeping a list of recent objects. git-svn-id: https://samskivert.googlecode.com/svn/trunk@1032 6335cc39-0255-0410-8fd6-9bcaacd3b74c --- .../java/com/samskivert/util/RecentList.java | 91 +++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 projects/samskivert/src/java/com/samskivert/util/RecentList.java diff --git a/projects/samskivert/src/java/com/samskivert/util/RecentList.java b/projects/samskivert/src/java/com/samskivert/util/RecentList.java new file mode 100644 index 00000000..90dfbdb5 --- /dev/null +++ b/projects/samskivert/src/java/com/samskivert/util/RecentList.java @@ -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. + * null is returned if the list does not contain at least + * index+1 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; +}