Iterator vs Enumeration

Does anyone know how to produce the equivalent of an Enumeration with the new Collection classes like ArrayList and HashMap?
My situation is that I've got a collection (ArrayList) inside of my class, and I'd like clients to be able to see what's in this list without being able to change the list (ie Iterator.delete()) Is there any way to disable the Iterator.delete operation?
The solution I'm going with right now is just to use the old collections (ie Vector and Hashtable) which still have the .elements() method.
Ps. Is this a bug in Java?

1. Performance: The docs say that the unmodifiableXXX
methods put a 'view' on the collection so it cannot
be modified. My guess (well, if I had to do this,
this is what I'd do) is that they create a
lightweight dummy list object to sit between the
client and the list and to pass on all non-changing
operations. However this affects space and time.The affect performance and space is generally going to be negligible. I've never run into trouble doing things like this. Also note that creating an immutable Iterator wrapper it extremely quick and easy and could be an option if all you are doing is returning an Iterator.
2. Safety: If you're going to make a collection
immutable and disable some of its functionality by
throwing a RuntimeException, shouldn't there be a way
to ask "is this collection immutable or not?"
Otherwise, you have to either just know what it is or
be extremely paranoid or just allow things to fail
unexpectedly.Your API should specify this. If someone tries to modify the list, it will become apparent during development, which is what you want. If you need to sometimes return modifiable and sometimes not, then you will need to address this with a more complicated API.

Similar Messages

  • Enumeration vs Iterator

    Please,
    what is the difference between iterator and enumeration? Iterator should be more better designed, but I don't note that difference.

    Iterator vs. Enumeration
    Round 1: Typing
    "Iterator" has fewer letters than "Enumeration" (Point to Iterator)
    Iterator's methods have fewer letters than Enumeration's methods (Point to Iterator)
    Round 2: Power
    Iterator advertises the ability to remove from the iterated collection the last element that has been returned. Enumeration has no facility to do that. (Point to Iterator)
    Iterator has been extended within the Java platform (see ListIterator) to advertise the ability to move forward or backward through the iterated collection. (Point to Iterator)
    This extension can also add an element to the collection and change the value of the last element returned within the collection. (Point to Iterator)
    Iterator is integrated into the Collections framework. Enumeration is peripheral to the framework and has been awkwardly inserted to provide backwards compatability to Dinosaur-aged programs. (Point to Iterator)
    Lexographically speaking, Enumeration comes before Iterator. (Point to Enumeration).
    Tally up the score. You be the judge :-)

  • Why does for-each not work with Enumeration?

    I'm sure there's some reason for this but I don't know what it would be.
    I am calling an existing method [http://java.sun.com/javase/6/docs/api/java/util/zip/ZipFile.html#entries()] And it returns Enumeration<? extends ZipEntry>
    What I would like to do is
    Enumeration<? extends ZipEntry> entries = myzipfile.entries();
    for(ZipEntry ze : entries)but this won't compile because Enumeration is not an Iterator. Which kinda sucks.
    Obviously (I think) Enumeration can't be retrofit to be an Iterator without problems and the APIs that return Enumeration can't change without problems so it seems the only way that for-each would work with an Enumeration is if for-each was allowed to work with Iterator and Enumeration.
    So my question is, why isn't it? (To be clear I know how to enumerate an Enumeration, I'd just like to know if anybody has a clue why for-each was not designed to support Enumeration)

    Still it does'nt fully answer the why question. Why does the Collections class not implement a static iterable(Enumeration) method that does not impose the overhead of an addiditional ArrayList, as in the following class:
    import java.util.Collections;
    import java.util.Enumeration;
    import java.util.Iterator;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipFile;
    public class EnumerationToIterable {
        public static <T> Iterable<T> iterable(final Enumeration<T> enumeration) {
         return new Iterable<T>() {
             @Override
             public Iterator<T> iterator() {
              return new Iterator<T>() {
                  @Override
                  public boolean hasNext() {
                   return enumeration.hasMoreElements();
                  @Override
                  public T next() {
                   return enumeration.nextElement();
                  @Override
                  public void remove() {
                   throw new UnsupportedOperationException();
        public void iterateOne(ZipFile myzipfile) {
         Enumeration<? extends ZipEntry> entries = myzipfile.entries();
         for (ZipEntry ze : Collections.list(entries)) {
             // process ze
        public void iterateTwo(ZipFile myzipfile) {
         Enumeration<? extends ZipEntry> entries = myzipfile.entries();
         for (ZipEntry ze : iterable(entries)) {
             // process ze
    }Could it be more simple?
    (Thanks for the Dukes)
    Piet

  • Performance Impact with OR concatenation / Inlist Iterator

    Hello guys,
    is there any performance impact with using OR concatenations or some IN-Lists?
    The function of both is the "same":
    1) Concatenation (OR-processing)
    SELECT * FROM emp WHERE mgr# = 1 OR job = ‘YOURS’;- Similar to query rewrite into 2 seperate queries
    - Which are then ‘concatenated’
    2) Inlist Iterator
    SELECT * FROM dept WHERE d# in (10,20,30);- Iteration over enumerated value-list
    - Every value executed seperately
    - Same as concatenation of 3 “OR-red” values
    So i want to know if there is any performance impact if using IN-Lists instead of OR concatenations.
    Thanks and Regards
    Stefan

    The note is very misleading and far from complete; but there is one critical point of difference that you need to observe. It's talking about using a tablescan to deal with an IN-list (and that's NOT "in-list iteration"), my comments start by saying "if there is a suitable indexed access path."
    The note, by the way, describes a transformation to a UNION ALL - clearly that would be inefficient if there were no indexed access path. (Given the choice between one tablescan and several consecutive tablescans, which option would you choose ?).
    The note, in effect, is just about a slightly more subtle version of "why isn't oracle using my index". For "shorter" lists you might get an indexed iteration, for "longer" lists you might get a tablescan.
    Remember, Metalink is not perfect; most of it is just written by ordinary people who learned about Oracle in the normal fashion.
    Quick example to demonstrate the difference between concatenation and iteration:
    drop table t1;
    create table t1 as
    select
         rownum     id,
         rownum     n1,
         rpad('x',100)     padding
    from
         all_objects
    where
         rownum <= 10000
    create index t1_i1 on t1(id);
    execute dbms_stats.gather_table_stats(user,'t1')
    set autotrace traceonly explain
    select
         /*+ use_concat(t1) */
         n1
    from
         t1
    where
         id in (10,20,30,40,50,60,70,80,90,100)
    set autotrace offThe execution plan I got from 8.1.7.4 was as follows - showing the transformation to a UNION ALL - this is concatenation and required 10 query block optimisations (which were all done three times):
    Execution Plan
       0      SELECT STATEMENT Optimizer=ALL_ROWS (Cost=20 Card=10 Bytes=80)
       1    0   CONCATENATION
       2    1     TABLE ACCESS (BY INDEX ROWID) OF 'T1' (Cost=2 Card=1 Bytes=8)
       3    2       INDEX (RANGE SCAN) OF 'T1_I1' (NON-UNIQUE) (Cost=1 Card=1)
       4    1     TABLE ACCESS (BY INDEX ROWID) OF 'T1' (Cost=2 Card=1 Bytes=8)
       5    4       INDEX (RANGE SCAN) OF 'T1_I1' (NON-UNIQUE) (Cost=1 Card=1)
       6    1     TABLE ACCESS (BY INDEX ROWID) OF 'T1' (Cost=2 Card=1 Bytes=8)
       7    6       INDEX (RANGE SCAN) OF 'T1_I1' (NON-UNIQUE) (Cost=1 Card=1)
       8    1     TABLE ACCESS (BY INDEX ROWID) OF 'T1' (Cost=2 Card=1 Bytes=8)
       9    8       INDEX (RANGE SCAN) OF 'T1_I1' (NON-UNIQUE) (Cost=1 Card=1)
      10    1     TABLE ACCESS (BY INDEX ROWID) OF 'T1' (Cost=2 Card=1 Bytes=8)
      11   10       INDEX (RANGE SCAN) OF 'T1_I1' (NON-UNIQUE) (Cost=1 Card=1)
      12    1     TABLE ACCESS (BY INDEX ROWID) OF 'T1' (Cost=2 Card=1 Bytes=8)
      13   12       INDEX (RANGE SCAN) OF 'T1_I1' (NON-UNIQUE) (Cost=1 Card=1)
      14    1     TABLE ACCESS (BY INDEX ROWID) OF 'T1' (Cost=2 Card=1 Bytes=8)
      15   14       INDEX (RANGE SCAN) OF 'T1_I1' (NON-UNIQUE) (Cost=1 Card=1)
      16    1     TABLE ACCESS (BY INDEX ROWID) OF 'T1' (Cost=2 Card=1 Bytes=8)
      17   16       INDEX (RANGE SCAN) OF 'T1_I1' (NON-UNIQUE) (Cost=1 Card=1)
      18    1     TABLE ACCESS (BY INDEX ROWID) OF 'T1' (Cost=2 Card=1 Bytes=8)
      19   18       INDEX (RANGE SCAN) OF 'T1_I1' (NON-UNIQUE) (Cost=1 Card=1)
      20    1     TABLE ACCESS (BY INDEX ROWID) OF 'T1' (Cost=2 Card=1 Bytes=8)
      21   20       INDEX (RANGE SCAN) OF 'T1_I1' (NON-UNIQUE) (Cost=1 Card=1)This is the execution plan I got from 9.2.0.8, which doesn't transform to the UNION ALL, and only needs to optimise one query block.
    Execution Plan
       0      SELECT STATEMENT Optimizer=ALL_ROWS (Cost=3 Card=10 Bytes=80)
       1    0   INLIST ITERATOR
       2    1     TABLE ACCESS (BY INDEX ROWID) OF 'T1' (Cost=3 Card=10 Bytes=80)
       3    2       INDEX (RANGE SCAN) OF 'T1_I1' (NON-UNIQUE) (Cost=2 Card=10)Regards
    Jonathan Lewis
    http://jonathanlewis.wordpress.com
    http://www.jlcomp.demon.co.uk

  • GetAppProperty Method

    Hi!
    Where can I get a complete list of all the keys to pass in as input parameter to Midlet.getAppProperty() method?
    TIA!
    Regards
    swinging

    http://developers.sun.com/mobility/midp/ttips/getAppProperty/index.html
    characteristics of attributes:
    * Names are case-sensitive.
    * There is no iteration or enumeration of the attribute space.
    * Attribute names should appear only once in a single location; if an attribute appears more than once in either the manifest or the descriptor, the behavior is unspecified.
    * The attribute namespace is read-only; there is no MIDlet.setAppProperty() method.
    * The MIDlet suite cannot discover the source location of a value.

  • HELP me with the source code

    In this assignment you are asked to create a Java class that simulates the Java Vector class. You are also asked to create two Exception classes to allow the program to continue if errors occur. These are �MyVectNoDataException� and �MyVectIndexOutOfBoundsException�.
    1.     Write a Java class called �myVect� which will operate in the same way as the Java Vector class. In particular it should have
    a.     The following data members
    i.     An Object array
    ii.     An integer �size� that determines the size of the array
    iii.     An integer �increment� that defines the number of additional elements that will be added when the Array is to be resized.
    b.     The following methods
    i.     Constructor 1      myVect()that creates a new myVect object with an internal array size of 10 and an increment of 3.
    ii.     Constructor 2           myVect(int s)
    that creates a new myVect object with an internal array size of s and an increment of 3.
    iii.     Constructor 3           myVect(int s, int i)
    that creates a new myVect object with an internal array size of s and an increment of i.
    iv.     A method          void resize()
    that increases the size of the internal array by the number of elements in the �increment� variable.
    v.     A method      void addElement(Object o)
    that inserts an Object at the next available position in the internal array. If there are less than 3 vacant elements left in the array then the resize() method should be run automatically.
    vi.     A method      void deleteElement()
    that deletes the Object at the last occupied position in the internal array. If no element contains an Object then a MyVectNoDataException should be thrown and the program should continue.
    vii.     A method void insertElement(Object o,int p)
    that inserts an Object at position p in the internal array. The Objects at position p and below should each be moved down by one position before the insertion.
    If the index p is outside the bounds of the internal array then a MyVectIndexOutOfBoundsException should be thrown and the program should continue.
    viii.     A method void deleteElementAt(int p)
    that deletes the Object at position p in the internal array. The Objects below position p should each be moved up by one position after the deletion. If the index p is outside the bounds of the internal array then a MyVectIndexOutOfBoundsException should be thrown and the program should continue.
    If the position p is valid but does not contain an Object then a MyVectNoDataException should be thrown and the program should continue.
    ix.     A method      Object getElement()
    that returns the Object at the last occupied position in the internal array.
    x.     A method      Object getElementAt(int p)
    that returns the Object at position p in the internal array. If the index p is outside the bounds of the internal array then a MyVectIndexOutOfBoundsException should be thrown and the program should continue. If the position p is valid but does not contain an Object then a MyVectNoDataException should be thrown and the program should continue.
    xi.     A toString() method that produces a formatted String representing the myVect object and its data. It should also include the size and increment values.
    c.     Write a Java program called Assign3.java that creates a myVect object then
    i.     Store 6 objects of the following types
    1.     String
    2.     Date
    3.     Integer
    4.     String
    5.     StringTokenizer
    6.     Date
    ii.     Print the myVect object.
    iii.     Add 2 more objects
    1.     StringBuffer
    2.     Double
    iv.     Print the myVect object
    v.     Delete the Object at position 2
    vi.     Delete the Object at position 15
    vii.     Display the Object at position 10
    viii.     Display the length of the second String.
    ix.     Print the myVect object
    d.     Include Javadoc comments in the myVect class code then produce Java documentation using Javadoc.

    * @(#)MyOwnVectorReallyItIs.java     1.89 03/01/23
    * Copyright 2003 Sun Microsystems, Inc. All rights reserved.
    * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
    package java.util;
    * The <code>MyOwnVectorReallyItIs</code> class implements a growable array of
    * objects. Like an array, it contains components that can be
    * accessed using an integer index. However, the size of a
    * <code>MyOwnVectorReallyItIs</code> can grow or shrink as needed to accommodate
    * adding and removing items after the <code>MyOwnVectorReallyItIs</code> has been created.<p>
    * Each MyOwnVectorReallyItIs tries to optimize storage management by maintaining a
    * <code>capacity</code> and a <code>capacityIncrement</code>. The
    * <code>capacity</code> is always at least as large as the MyOwnVectorReallyItIs
    * size; it is usually larger because as components are added to the
    * MyOwnVectorReallyItIs, the MyOwnVectorReallyItIs's storage increases in chunks the size of
    * <code>capacityIncrement</code>. An application can increase the
    * capacity of a MyOwnVectorReallyItIs before inserting a large number of
    * components; this reduces the amount of incremental reallocation. <p>
    * As of the Java 2 platform v1.2, this class has been retrofitted to
    * implement List, so that it becomes a part of Java's collection framework.
    * Unlike the new collection implementations, MyOwnVectorReallyItIs is synchronized.<p>
    * The Iterators returned by MyOwnVectorReallyItIs's iterator and listIterator
    * methods are <em>fail-fast</em>: if the MyOwnVectorReallyItIs is structurally modified
    * at any time after the Iterator is created, in any way except through the
    * Iterator's own remove or add methods, the Iterator will throw a
    * ConcurrentModificationException.  Thus, in the face of concurrent
    * modification, the Iterator fails quickly and cleanly, rather than risking
    * arbitrary, non-deterministic behavior at an undetermined time in the future.
    * The Enumerations returned by MyOwnVectorReallyItIs's elements method are <em>not</em>
    * fail-fast.
    * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
    * as it is, generally speaking, impossible to make any hard guarantees in the
    * presence of unsynchronized concurrent modification.  Fail-fast iterators
    * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
    * Therefore, it would be wrong to write a program that depended on this
    * exception for its correctness:  <i>the fail-fast behavior of iterators
    * should be used only to detect bugs.</i><p>
    * This class is a member of the
    * <a href="{@docRoot}/../guide/collections/index.html">
    * Java Collections Framework</a>.
    * @author  Lee Boynton
    * @author  Jonathan Payne
    * @version 1.89, 01/23/03
    * @see Collection
    * @see List
    * @see ArrayList
    * @see LinkedList
    * @since   JDK1.0
    public class MyOwnVectorReallyItIs extends AbstractList
            implements List, RandomAccess, Cloneable, java.io.Serializable
         * The array buffer into which the components of the MyOwnVectorReallyItIs are
         * stored. The capacity of the MyOwnVectorReallyItIs is the length of this array buffer,
         * and is at least large enough to contain all the MyOwnVectorReallyItIs's elements.<p>
         * Any array elements following the last element in the MyOwnVectorReallyItIs are null.
         * @serial
        protected Object elementData[];
         * The number of valid components in this <tt>MyOwnVectorReallyItIs</tt> object.
         * Components <tt>elementData[0]</tt> through
         * <tt>elementData[elementCount-1]</tt> are the actual items.
         * @serial
        protected int elementCount;
         * The amount by which the capacity of the MyOwnVectorReallyItIs is automatically
         * incremented when its size becomes greater than its capacity.  If
         * the capacity increment is less than or equal to zero, the capacity
         * of the MyOwnVectorReallyItIs is doubled each time it needs to grow.
         * @serial
        protected int capacityIncrement;
        /** use serialVersionUID from JDK 1.0.2 for interoperability */
        private static final long serialVersionUID = -2767605614048989439L;
         * Constructs an empty MyOwnVectorReallyItIs with the specified initial capacity and
         * capacity increment.
         * @param   initialCapacity     the initial capacity of the MyOwnVectorReallyItIs.
         * @param   capacityIncrement   the amount by which the capacity is
         *                              increased when the MyOwnVectorReallyItIs overflows.
         * @exception IllegalArgumentException if the specified initial capacity
         *               is negative
        public MyOwnVectorReallyItIs(int initialCapacity, int capacityIncrement) {
         super();
            if (initialCapacity < 0)
                throw new IllegalArgumentException("Illegal Capacity: "+
                                                   initialCapacity);
         this.elementData = new Object[initialCapacity];
         this.capacityIncrement = capacityIncrement;
         * Constructs an empty MyOwnVectorReallyItIs with the specified initial capacity and
         * with its capacity increment equal to zero.
         * @param   initialCapacity   the initial capacity of the MyOwnVectorReallyItIs.
         * @exception IllegalArgumentException if the specified initial capacity
         *               is negative
        public MyOwnVectorReallyItIs(int initialCapacity) {
         this(initialCapacity, 0);
         * Constructs an empty MyOwnVectorReallyItIs so that its internal data array
         * has size <tt>10</tt> and its standard capacity increment is
         * zero.
        public MyOwnVectorReallyItIs() {
         this(10);
         * Constructs a MyOwnVectorReallyItIs containing the elements of the specified
         * collection, in the order they are returned by the collection's
         * iterator.
         * @param c the collection whose elements are to be placed into this
         *       MyOwnVectorReallyItIs.
         * @throws NullPointerException if the specified collection is null.
         * @since   1.2
        public MyOwnVectorReallyItIs(Collection c) {
            elementCount = c.size();
            // 10% for growth
            elementData = new Object[
                          (int)Math.min((elementCount*110L)/100,Integer.MAX_VALUE)];
            c.toArray(elementData);
         * Copies the components of this MyOwnVectorReallyItIs into the specified array. The
         * item at index <tt>k</tt> in this MyOwnVectorReallyItIs is copied into component
         * <tt>k</tt> of <tt>anArray</tt>. The array must be big enough to hold
         * all the objects in this MyOwnVectorReallyItIs, else an
         * <tt>IndexOutOfBoundsException</tt> is thrown.
         * @param   anArray   the array into which the components get copied.
         * @throws  NullPointerException if the given array is null.
        public synchronized void copyInto(Object anArray[]) {
         System.arraycopy(elementData, 0, anArray, 0, elementCount);
         * Trims the capacity of this MyOwnVectorReallyItIs to be the MyOwnVectorReallyItIs's current
         * size. If the capacity of this MyOwnVectorReallyItIs is larger than its current
         * size, then the capacity is changed to equal the size by replacing
         * its internal data array, kept in the field <tt>elementData</tt>,
         * with a smaller one. An application can use this operation to
         * minimize the storage of a MyOwnVectorReallyItIs.
        public synchronized void trimToSize() {
         modCount++;
         int oldCapacity = elementData.length;
         if (elementCount < oldCapacity) {
             Object oldData[] = elementData;
             elementData = new Object[elementCount];
             System.arraycopy(oldData, 0, elementData, 0, elementCount);
         * Increases the capacity of this MyOwnVectorReallyItIs, if necessary, to ensure
         * that it can hold at least the number of components specified by
         * the minimum capacity argument.
         * <p>If the current capacity of this MyOwnVectorReallyItIs is less than
         * <tt>minCapacity</tt>, then its capacity is increased by replacing its
         * internal data array, kept in the field <tt>elementData</tt>, with a
         * larger one.  The size of the new data array will be the old size plus
         * <tt>capacityIncrement</tt>, unless the value of
         * <tt>capacityIncrement</tt> is less than or equal to zero, in which case
         * the new capacity will be twice the old capacity; but if this new size
         * is still smaller than <tt>minCapacity</tt>, then the new capacity will
         * be <tt>minCapacity</tt>.
         * @param minCapacity the desired minimum capacity.
        public synchronized void ensureCapacity(int minCapacity) {
         modCount++;
         ensureCapacityHelper(minCapacity);
         * This implements the unsynchronized semantics of ensureCapacity.
         * Synchronized methods in this class can internally call this
         * method for ensuring capacity without incurring the cost of an
         * extra synchronization.
         * @see java.util.MyOwnVectorReallyItIs#ensureCapacity(int)
        private void ensureCapacityHelper(int minCapacity) {
         int oldCapacity = elementData.length;
         if (minCapacity > oldCapacity) {
             Object oldData[] = elementData;
             int newCapacity = (capacityIncrement > 0) ?
              (oldCapacity + capacityIncrement) : (oldCapacity * 2);
                 if (newCapacity < minCapacity) {
              newCapacity = minCapacity;
             elementData = new Object[newCapacity];
             System.arraycopy(oldData, 0, elementData, 0, elementCount);
         * Sets the size of this MyOwnVectorReallyItIs. If the new size is greater than the
         * current size, new <code>null</code> items are added to the end of
         * the MyOwnVectorReallyItIs. If the new size is less than the current size, all
         * components at index <code>newSize</code> and greater are discarded.
         * @param   newSize   the new size of this MyOwnVectorReallyItIs.
         * @throws  ArrayIndexOutOfBoundsException if new size is negative.
        public synchronized void setSize(int newSize) {
         modCount++;
         if (newSize > elementCount) {
             ensureCapacityHelper(newSize);
         } else {
             for (int i = newSize ; i < elementCount ; i++) {
              elementData[i] = null;
         elementCount = newSize;
         * Returns the current capacity of this MyOwnVectorReallyItIs.
         * @return  the current capacity (the length of its internal
         *          data array, kept in the field <tt>elementData</tt>
         *          of this MyOwnVectorReallyItIs).
        public synchronized int capacity() {
         return elementData.length;
         * Returns the number of components in this MyOwnVectorReallyItIs.
         * @return  the number of components in this MyOwnVectorReallyItIs.
        public synchronized int size() {
         return elementCount;
         * Tests if this MyOwnVectorReallyItIs has no components.
         * @return  <code>true</code> if and only if this MyOwnVectorReallyItIs has
         *          no components, that is, its size is zero;
         *          <code>false</code> otherwise.
        public synchronized boolean isEmpty() {
         return elementCount == 0;
         * Returns an enumeration of the components of this MyOwnVectorReallyItIs. The
         * returned <tt>Enumeration</tt> object will generate all items in
         * this MyOwnVectorReallyItIs. The first item generated is the item at index <tt>0</tt>,
         * then the item at index <tt>1</tt>, and so on.
         * @return  an enumeration of the components of this MyOwnVectorReallyItIs.
         * @see     Enumeration
         * @see     Iterator
        public Enumeration elements() {
         return new Enumeration() {
             int count = 0;
             public boolean hasMoreElements() {
              return count < elementCount;
             public Object nextElement() {
              synchronized (MyOwnVectorReallyItIs.this) {
                  if (count < elementCount) {
                   return elementData[count++];
              throw new NoSuchElementException("MyOwnVectorReallyItIs Enumeration");
         * Tests if the specified object is a component in this MyOwnVectorReallyItIs.
         * @param   elem   an object.
         * @return  <code>true</code> if and only if the specified object
         * is the same as a component in this MyOwnVectorReallyItIs, as determined by the
         * <tt>equals</tt> method; <code>false</code> otherwise.
        public boolean contains(Object elem) {
         return indexOf(elem, 0) >= 0;
         * Searches for the first occurence of the given argument, testing
         * for equality using the <code>equals</code> method.
         * @param   elem   an object.
         * @return  the index of the first occurrence of the argument in this
         *          MyOwnVectorReallyItIs, that is, the smallest value <tt>k</tt> such that
         *          <tt>elem.equals(elementData[k])</tt> is <tt>true</tt>;
         *          returns <code>-1</code> if the object is not found.
         * @see     Object#equals(Object)
        public int indexOf(Object elem) {
         return indexOf(elem, 0);
         * Searches for the first occurence of the given argument, beginning
         * the search at <code>index</code>, and testing for equality using
         * the <code>equals</code> method.
         * @param   elem    an object.
         * @param   index   the non-negative index to start searching from.
         * @return  the index of the first occurrence of the object argument in
         *          this MyOwnVectorReallyItIs at position <code>index</code> or later in the
         *          MyOwnVectorReallyItIs, that is, the smallest value <tt>k</tt> such that
         *          <tt>elem.equals(elementData[k]) && (k >= index)</tt> is
         *          <tt>true</tt>; returns <code>-1</code> if the object is not
         *          found. (Returns <code>-1</code> if <tt>index</tt> >= the
         *          current size of this <tt>MyOwnVectorReallyItIs</tt>.)
         * @exception  IndexOutOfBoundsException  if <tt>index</tt> is negative.
         * @see     Object#equals(Object)
        public synchronized int indexOf(Object elem, int index) {
         if (elem == null) {
             for (int i = index ; i < elementCount ; i++)
              if (elementData==null)
              return i;
         } else {
         for (int i = index ; i < elementCount ; i++)
              if (elem.equals(elementData[i]))
              return i;
         return -1;
    * Returns the index of the last occurrence of the specified object in
    * this MyOwnVectorReallyItIs.
    * @param elem the desired component.
    * @return the index of the last occurrence of the specified object in
    * this MyOwnVectorReallyItIs, that is, the largest value <tt>k</tt> such that
    * <tt>elem.equals(elementData[k])</tt> is <tt>true</tt>;
    * returns <code>-1</code> if the object is not found.
    public synchronized int lastIndexOf(Object elem) {
         return lastIndexOf(elem, elementCount-1);
    * Searches backwards for the specified object, starting from the
    * specified index, and returns an index to it.
    * @param elem the desired component.
    * @param index the index to start searching from.
    * @return the index of the last occurrence of the specified object in this
    * MyOwnVectorReallyItIs at position less than or equal to <code>index</code> in
    * the MyOwnVectorReallyItIs, that is, the largest value <tt>k</tt> such that
    * <tt>elem.equals(elementData[k]) && (k <= index)</tt> is
    * <tt>true</tt>; <code>-1</code> if the object is not found.
    * (Returns <code>-1</code> if <tt>index</tt> is negative.)
    * @exception IndexOutOfBoundsException if <tt>index</tt> is greater
    * than or equal to the current size of this MyOwnVectorReallyItIs.
    public synchronized int lastIndexOf(Object elem, int index) {
    if (index >= elementCount)
    throw new IndexOutOfBoundsException(index + " >= "+ elementCount);
         if (elem == null) {
         for (int i = index; i >= 0; i--)
              if (elementData[i]==null)
              return i;
         } else {
         for (int i = index; i >= 0; i--)
              if (elem.equals(elementData[i]))
              return i;
         return -1;
    * Returns the component at the specified index.<p>
    * This method is identical in functionality to the get method
    * (which is part of the List interface).
    * @param index an index into this MyOwnVectorReallyItIs.
    * @return the component at the specified index.
    * @exception ArrayIndexOutOfBoundsException if the <tt>index</tt>
    * is negative or not less than the current size of this
    * <tt>MyOwnVectorReallyItIs</tt> object.
    * given.
    * @see     #get(int)
    * @see     List
    public synchronized Object elementAt(int index) {
         if (index >= elementCount) {
         throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount);
    return elementData[index];
    * Returns the first component (the item at index <tt>0</tt>) of
    * this MyOwnVectorReallyItIs.
    * @return the first component of this MyOwnVectorReallyItIs.
    * @exception NoSuchElementException if this MyOwnVectorReallyItIs has no components.
    public synchronized Object firstElement() {
         if (elementCount == 0) {
         throw new NoSuchElementException();
         return elementData[0];
    * Returns the last component of the MyOwnVectorReallyItIs.
    * @return the last component of the MyOwnVectorReallyItIs, i.e., the component at index
    * <code>size() - 1</code>.
    * @exception NoSuchElementException if this MyOwnVectorReallyItIs is empty.
    public synchronized Object lastElement() {
         if (elementCount == 0) {
         throw new NoSuchElementException();
         return elementData[elementCount - 1];
    * Sets the component at the specified <code>index</code> of this
    * MyOwnVectorReallyItIs to be the specified object. The previous component at that
    * position is discarded.<p>
    * The index must be a value greater than or equal to <code>0</code>
    * and less than the current size of the MyOwnVectorReallyItIs. <p>
    * This method is identical in functionality to the set method
    * (which is part of the List interface). Note that the set method reverses
    * the order of the parameters, to more closely match array usage. Note
    * also that the set method returns the old value that was stored at the
    * specified position.
    * @param obj what the component is to be set to.
    * @param index the specified index.
    * @exception ArrayIndexOutOfBoundsException if the index was invalid.
    * @see #size()
    * @see List
    * @see     #set(int, java.lang.Object)
    public synchronized void setElementAt(Object obj, int index) {
         if (index >= elementCount) {
         throw new ArrayIndexOutOfBoundsException(index + " >= " +
                                  elementCount);
         elementData[index] = obj;
    * Deletes the component at the specified index. Each component in
    * this MyOwnVectorReallyItIs with an index greater or equal to the specified
    * <code>index</code> is shifted downward to have an index one
    * smaller than the value it had previously. The size of this MyOwnVectorReallyItIs
    * is decreased by <tt>1</tt>.<p>
    * The index must be a value greater than or equal to <code>0</code>
    * and less than the current size of the MyOwnVectorReallyItIs. <p>
    * This method is identical in functionality to the remove method
    * (which is part of the List interface). Note that the remove method
    * returns the old value that was stored at the specified position.
    * @param index the index of the object to remove.
    * @exception ArrayIndexOutOfBoundsException if the index was invalid.
    * @see #size()
    * @see     #remove(int)
    * @see     List
    public synchronized void removeElementAt(int index) {
         modCount++;
         if (index >= elementCount) {
         throw new ArrayIndexOutOfBoundsException(index + " >= " +
                                  elementCount);
         else if (index < 0) {
         throw new ArrayIndexOutOfBoundsException(index);
         int j = elementCount - index - 1;
         if (j > 0) {
         System.arraycopy(elementData, index + 1, elementData, index, j);
         elementCount--;
         elementData[elementCount] = null; /* to let gc do its work */
    * Inserts the specified object as a component in this MyOwnVectorReallyItIs at the
    * specified <code>index</code>. Each component in this MyOwnVectorReallyItIs with
    * an index greater or equal to the specified <code>index</code> is
    * shifted upward to have an index one greater than the value it had
    * previously. <p>
    * The index must be a value greater than or equal to <code>0</code>
    * and less than or equal to the current size of the MyOwnVectorReallyItIs. (If the
    * index is equal to the current size of the MyOwnVectorReallyItIs, the new element
    * is appended to the MyOwnVectorReallyItIs.)<p>
    * This method is identical in functionality to the add(Object, int) method
    * (which is part of the List interface). Note that the add method reverses
    * the order of the parameters, to more closely match array usage.
    * @param obj the component to insert.
    * @param index where to insert the new component.
    * @exception ArrayIndexOutOfBoundsException if the index was invalid.
    * @see #size()
    * @see     #add(int, Object)
    * @see     List
    public synchronized void insertElementAt(Object obj, int index) {
         modCount++;
         if (index > elementCount) {
         throw new ArrayIndexOutOfBoundsException(index
                                  + " > " + elementCount);
         ensureCapacityHelper(elementCount + 1);
         System.arraycopy(elementData, index, elementData, index + 1, elementCount - index);
         elementData[index] = obj;
         elementCount++;
    * Adds the specified component to the end of this MyOwnVectorReallyItIs,
    * increasing its size by one. The capacity of this MyOwnVectorReallyItIs is
    * increased if its size becomes greater than its capacity. <p>
    * This method is identical in functionality to the add(Object) method
    * (which is part of the List interface).
    * @param obj the component to be added.
    * @see     #add(Object)
    * @see     List
    public synchronized void addElement(Object obj) {
         modCount++;
         ensureCapacityHelper(elementCount + 1);
         elementData[elementCount++] = obj;
    * Removes the first (lowest-indexed) occurrence of the argument
    * from this MyOwnVectorReallyItIs. If the object is found in this MyOwnVectorReallyItIs, each
    * component in the MyOwnVectorReallyItIs with an index greater or equal to the
    * object's index is shifted downward to have an index one smaller
    * than the value it had previously.<p>
    * This method is identical in functionality to the remove(Object)
    * method (which is part of the List interface).
    * @param obj the component to be removed.
    * @return <code>true</code> if the argument was a component of this
    * MyOwnVectorReallyItIs; <code>false</code> otherwise.
    * @see     List#remove(Object)
    * @see     List
    public synchronized boolean removeElement(Object obj) {
         modCount++;
         int i = indexOf(obj);
         if (i >= 0) {
         removeElementAt(i);
         return true;
         return false;
    * Removes all components from this MyOwnVectorReallyItIs and sets its size to zero.<p>
    * This method is identical in functionality to the clear method
    * (which is part of the List interface).
    * @see     #clear
    * @see     List
    public synchronized void removeAllElements() {
    modCount++;
         // Let gc do its work
         for (int i = 0; i < elementCount; i++)
         elementData[i] = null;
         elementCount = 0;
    * Returns a clone of this MyOwnVectorReallyItIs. The copy will contain a
    * reference to a clone of the internal data array, not a reference
    * to the original internal data array of this <tt>MyOwnVectorReallyItIs</tt> object.
    * @return a clone of this MyOwnVectorReallyItIs.
    public synchronized Object clone() {
         try {
         MyOwnVectorReallyItIs v = (MyOwnVectorReallyItIs)super.clone();
         v.elementData = new Object[elementCount];
         System.arraycopy(elementData, 0, v.elementData, 0, elementCount);
         v.modCount = 0;
         return v;
         } catch (CloneNotSupportedException e) {
         // this shouldn't happen, since we are Cloneable
         throw new InternalError();
    * Returns an array containing all of the elements in this MyOwnVectorReallyItIs
    * in the correct order.
    * @since 1.2
    public synchronized Object[] toArray() {
         Object[] result = new Object[elementCount];
         System.arraycopy(elementData, 0, result, 0, elementCount);
         return result;
    * Returns an array containing all of the elements in this MyOwnVectorReallyItIs in the
    * correct order; the runtime type of the returned array is that of the
    * specified array. If the MyOwnVectorReallyItIs fits in the specified array, it is
    * returned therein. Otherwise, a new array is allocated with the runtime
    * type of the specified array and the size of this MyOwnVectorReallyItIs.<p>
    * If the MyOwnVectorReallyItIs fits in the specified array with room to spare
    * (i.e., the array has more elements than the MyOwnVectorReallyItIs),
    * the element in the array immediately following the end of the
    * MyOwnVectorReallyItIs is set to null. This is useful in determining the length
    * of the MyOwnVectorReallyItIs <em>only</em> if the caller knows that the MyOwnVectorReallyItIs
    * does not contain any null elements.
    * @param a the array into which the elements of the MyOwnVectorReallyItIs are to
    *          be stored, if it is big enough; otherwise, a new array of the
    *           same runtime type is allocated for this purpose.
    * @return an array containing the elements of the MyOwnVectorReallyItIs.
    * @exception ArrayStoreException the runtime type of a is not a supertype
    * of the runtime type of every element in this MyOwnVectorReallyItIs.
    * @throws NullPointerException if the given array is null.
    * @since 1.2
    public synchronized Object[] toArray(Object a[]) {
    if (a.length < elementCount)
    a = (Object[])java.lang.reflect.Array.newInstance(
    a.getClass().getComponentType(), elementCount);
         System.arraycopy(elementData, 0, a, 0, elementCount);
    if (a.length > elementCount)
    a[elementCount] = null;
    return a;
    // Positional Access Operations
    * Returns the element at the specified position in this MyOwnVectorReallyItIs.
    * @param index index of element to return.
    * @return object at the specified index
    * @exception ArrayIndexOutOfBoundsException index is out of range (index
    *           < 0 || index >= size()).
    * @since 1.2
    public synchronized Object get(int index) {
         if (index >= elementCount)
         throw new ArrayIndexOutOfBoundsException(index);
         return elementData[index];
    * Replaces the element at the specified position in this MyOwnVectorReallyItIs with the
    * specified element.
    * @param index index of element to replace.
    * @param element element to be stored at the specified position.
    * @return the element previously at the specified position.
    * @exception ArrayIndexOutOfBoundsException index out of range
    *          (index < 0 || index >= size()).
    * @since 1.2
    public synchronized Object set(int index, Object element) {
         if (index >= elementCount)
         throw new ArrayIndexOutOfBoundsException(index);
         Object oldValue = elementData[index];
         elementData[index] = element;
         return oldValue;
    * Appends the specified element to the end of this MyOwnVectorReallyItIs.
    * @param o element to be appended to this MyOwnVectorReallyItIs.
    * @return true (as per the general contract of Collection.add).
    * @since 1.2
    public synchronized boolean add(Object o) {
         modCount++;
         ensureCapacityHelper(elementCount + 1);
         elementData[elementCount++] = o;
    return true;
    * Removes the first occurrence of the specified element in this MyOwnVectorReallyItIs
    * If the MyOwnVectorReallyItIs does not contain the element, it is unchanged. More
    * formally, removes the element with the lowest index i such that
    * <code>(o==null ? get(i)==null : o.equals(get(i)))</code> (if such
    * an element exists).
    * @param o element to be removed from this MyOwnVectorReallyItIs, if present.
    * @return true if the MyOwnVectorReallyItIs contained the specified element.
    * @since 1.2
    public boolean remove(Object o) {
    return removeElement(o);
    * Inserts the specified element at the specified position in this MyOwnVectorReallyItIs.
    * Shifts the element currently at that position (if any) and any
    * subsequent elements to the right (adds one to their indices).
    * @param index index at which the specified element is to be inserted.
    * @param

  • Concurrent LRUCache?

    Hi,
    I'd like to know if you know of an LRU (least recently used) cache that would use java.util.concurrent.
    I'm currently using the following implementation that is based on java.util.LinkedHashMap.
    Do you know if there is an implementation based on java.util.concurrent.ConcurrentHashMap ?
    public class LRUCache<K, V> extends java.util.LinkedHashMap<K, V> {
        protected int maxsize;
        public LRUCache(int maxsize) {
            super(maxsize * 4 / 3 + 1, 0.75f, true);
            this.maxsize = maxsize;
        protected boolean removeEldestEntry(Map.Entry eldest) {
            return size() > maxsize;
    }

    I don't mind giving it out. Fill free to modify it or do anything you like with it. But, use this code at your own risk. I will not support it. The code is mostly undocumented. It uses a Timer that every 2 minutes checks the size and cleans out the old entries. You may need to add code to remove the TimerTask from the timer when the Map is no longer needed. I haven't since I've only used this class for static instances. It has two call back methods that can be overridden to find out what elements have been removed: removed() and expiredRemoved().
    import java.util.AbstractCollection;
    import java.util.AbstractSet;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Collection;
    import java.util.Comparator;
    import java.util.Enumeration;
    import java.util.Iterator;
    import java.util.Map;
    import java.util.Set;
    import java.util.Timer;
    import java.util.TimerTask;
    import java.util.concurrent.ConcurrentHashMap;
    import java.util.concurrent.ConcurrentMap;
    public class ConcurrentCacheMap<K,V> implements ConcurrentMap<K,V> {
         static final int DEFAULT_MAX_ENTRIES = 100;
         static final double PERCENT_CLEANUP = 0.05;     
         static final int DEFAULT_SEGMENTS = 16;
         static final int CHECK_DURATION = 120 * 1000;
         static final Timer timer = new Timer();
         protected int maxEntries;     
         protected ConcurrentHashMap<K,ValueWrapper<V>> map;
         /** Creates a new instance of CacheMap */
         public ConcurrentCacheMap() {
              this(DEFAULT_MAX_ENTRIES, DEFAULT_SEGMENTS);
         public ConcurrentCacheMap(int maxEntries, int concurrencyLevel) {
              map = new ConcurrentHashMap<K,ValueWrapper<V>>((maxEntries+1) * 4 / 3 + 1, 0.75f, concurrencyLevel);
              this.maxEntries = maxEntries;
              timer.schedule(new CacheCleaner(), CHECK_DURATION, CHECK_DURATION);
         public boolean replace(K key, V oldValue, V newValue) {
              return map.replace(key, new ValueWrapper<V>(oldValue), new ValueWrapper<V>(newValue));
         public V replace(K key, V value) {
              ValueWrapper<V> wrapper = map.replace(key, new ValueWrapper<V>(value));
              return checkRemove(key, wrapper);
         public V putIfAbsent(K key, V value) {
              ValueWrapper<V> wrapper = map.putIfAbsent(key, new ValueWrapper<V>(value));
              return checkRemove(key, wrapper);
         public V put(K key, V value) {
              ValueWrapper<V> wrapper = map.put(key, new ValueWrapper<V>(value));
              return checkRemove(key, wrapper);
         public void putAll(Map<? extends K,? extends V> t) {
              for (Entry<? extends K,? extends V> entry : t.entrySet()) {
                   put(entry.getKey(), entry.getValue());
         public V remove(Object key) {
              if (key == null) {
                   return null;
              ValueWrapper<V> wrapper = map.remove(key);
              return checkRemove(key, wrapper);
         public boolean remove(Object key, Object value) {
              ValueWrapper<Object> wrapper = new ValueWrapper<Object>(value);
              boolean rval = map.remove(key, wrapper);
              if (rval) {
                   removed(key, (V)value);               
              return rval;
         public V get(Object key) {
              ValueWrapper<V> wrapper = map.get(key);
              //don't increment age call .value
              return wrapper == null ? null : wrapper.getValue();
         public boolean contains(Object value) {
              return map.contains(new ValueWrapper<Object>(value));
         public boolean containsKey(Object key) {
              return map.containsKey(key);
         public boolean containsValue(Object value) {
              return map.containsValue(new ValueWrapper<Object>(value));
         public Collection<V> values() {
              return new CollectionValueWrapper();
         public Enumeration<V> elements() {
              return new ValueIter();
         public Enumeration<K> keys() {
              return new KeyIter();
         public boolean equals(Object obj) {
              if (obj instanceof ConcurrentCacheMap) {
                   return ((ConcurrentCacheMap)obj).map.equals(map);
              return false;
         public Set<K> keySet() {
              return map.keySet();
         public int size() {
              return map.size();
         public boolean isEmpty() {
              return map.isEmpty();
         public void clear() {
              map.clear();
         public String toString() {
              return map.toString();
         public int hashCode() {
              return map.hashCode();
         public Set<Entry<K, V>> entrySet() {
              return new EntrySetWrapper();
         final V checkRemove(Object key, ValueWrapper<V> wrapper) {
              if (wrapper == null){
                   return null;
              V value = wrapper.value;
              removed(key, value);
              return value;
         protected void removed(Object key, V value) {          
         protected void expiredRemoved(Object key, V value) {          
              //System.out.println(value + " " + value.getClass().getName());
         public int getMaxEntries() {
              return maxEntries;
         public void setMaxEntries(int maxEntries) {
              this.maxEntries = maxEntries;
         static boolean eq(Object o1, Object o2) {
              return (o1 == null ? o2 == null : o1.equals(o2));
         public final static class ValueWrapper<V> {
              // I just need approximate values for ageCounter so I don't care if
              // ageCounter is concurrently updated and therefore age is skipped or 
              // duplicated amoung ValueWrapper instances.  This should not be a
              // problem since I clean groups of old entries.
              // For small caches this may be a problem, but then so would be a 2 minute
              // cleanup. So if this is a concern then change ageCounter to use an AtomicLong or
              // a volatile and make schedule time variable.
              static long ageCounter;
              public V value;
              public long age;
              ValueWrapper(V value) {
                   this.value = value;
                   age = ageCounter++;
              public boolean equals(Object o) {
                   if (!(o instanceof ValueWrapper)) {
                        return false;
                   return eq(value,((ValueWrapper)o).value);
              public int hashCode() {
                   return value.hashCode();
              public V getValue() {
                   age = ageCounter++;
                   return value;
              public String toString() {
                   return value == null ? "null " : value.toString();
         abstract class Iter {
              Iterator<Entry<K,ValueWrapper<V>>> iter;
              Entry<K,ValueWrapper<V>> current;
              Iter() {
                   iter = map.entrySet().iterator();
              public void remove() {
                   ConcurrentCacheMap.this.remove(current.getKey());
              public boolean hasMoreElements() {
                   return iter.hasNext();
              public boolean hasNext() {
                   return iter.hasNext();
              final Entry<K,ValueWrapper<V>> advance() {
                   return (current = iter.next());
         final class KeyIter extends Iter implements Iterator<K>, Enumeration<K> {          
              public K nextElement() { return next(); }
              public K next() { return advance().getKey();     }
         final class ValueIter extends Iter implements Iterator<V>, Enumeration<V> {
              public V nextElement() { return next(); }                    
              public V next() {
                   ValueWrapper<V> valueWrapper = advance().getValue();
                   return valueWrapper == null ? null : valueWrapper.value;
         final class EntryIter extends Iter implements Iterator<Entry<K, V>>, Enumeration<Entry<K, V>> {               
              public Entry<K, V> nextElement() { return next(); }
              public Entry<K, V> next() { return new SimpleEntry<K,V>(advance());     }               
         final class CollectionValueWrapper extends AbstractCollection<V> {
              public Iterator<V> iterator() {
                   return new ValueIter();
              public int size() {
                   return ConcurrentCacheMap.this.size();
              public boolean contains(Object o) {
                   return ConcurrentCacheMap.this.containsValue(o);
              public void clear() {
                   ConcurrentCacheMap.this.clear();
              public Object[] toArray() {
                   Collection<V> c = new ArrayList<V>();
                   for (Iterator<V> i = iterator(); i.hasNext(); ) {
                        c.add(i.next());
                   return c.toArray();
              public <T> T[] toArray(T[] a) {
                   Collection<V> c = new ArrayList<V>();
                   for (Iterator<V> i = iterator(); i.hasNext(); ) {
                        c.add(i.next());
                   return c.toArray(a);
         final class EntrySetWrapper extends AbstractSet<Entry<K, V>> {
              public Iterator<Entry<K, V>> iterator() {
                   return new EntryIter();
              public boolean remove(Object o) {
                   if (!(o instanceof Map.Entry)) {                    
                        return false;
                   Map.Entry<K,V> entry = (Map.Entry<K,V>)o;
                   return ConcurrentCacheMap.this.remove(entry.getKey(), entry.getValue());
              public boolean contains(Object o) {
                   if (!(o instanceof Map.Entry)) {                    
                        return false;
                   Map.Entry<K,V> e = (Map.Entry<K,V>)o;
                   V v = ConcurrentCacheMap.this.get(e.getKey());
                   return v != null && v.equals(e.getValue());
              public int size() {
                   return ConcurrentCacheMap.this.size();
              public void clear() {
                   ConcurrentCacheMap.this.clear();
         final static class SimpleEntry<K,V> implements Entry<K,V> {
              Entry<K, ValueWrapper<V>> entry;
              SimpleEntry(Entry<K, ValueWrapper<V>> entry) {
                   this.entry = entry;                    
              public V setValue(V value) {
                   //don't increment age call .value
                   return entry.setValue(new ValueWrapper<V>(value)).value;
              public K getKey() {
                   return entry.getKey();
              public V getValue() {
                   ValueWrapper<V> valueWrapper = entry.getValue();                    
                   return valueWrapper == null ? null : valueWrapper.value;
              public boolean equals(Object o) {
                   if (!(o instanceof Map.Entry)) {
                        return false;
                   Entry e = (Entry)o;
                   return eq(getKey(), e.getKey()) && eq(getValue(), e.getValue());
              public int hashCode() {
                   K key = getKey();
                   V value = getValue();
                   return ((key == null)  ? 0 :   key.hashCode()) ^
                    ((value == null)   ? 0 : value.hashCode());
              public String toString() {
                   return getKey() + "=" + getValue();
         final class CacheCleaner extends TimerTask {
              public void run() {
                   try {
                        clean();
                   } catch (Throwable th) {
                        th.printStackTrace();
         public void clean() {
              int maxEntries = getMaxEntries();
              int size = size();
              if (size > maxEntries) {
                   int removeCount = (int)(maxEntries * PERCENT_CLEANUP) + (size - maxEntries);     
                   System.out.println("Starting to clean " + removeCount + " old items from cache(" + maxEntries +") with " + size + " items.");
                   long start = System.currentTimeMillis();
                   //Size can and will likely change during coping to an array inside of toArray
                   //and and new array will likely be need to be created. So to prevent three
                   //large arrays from being allocated. Just allocate an empty array for type purposes.
                   Entry[] allItem = new Entry[0]; 
                   allItem = map.entrySet().toArray(allItem);
                   Arrays.sort(allItem, new EntrySetComparator<K,V>());
                   int upper = allItem.length;
                   for (int i=0; i<removeCount; i++) {
                        Entry<K, ValueWrapper<V>> entry = (Entry<K, ValueWrapper<V>>)allItem;
                        ValueWrapper<V> valueWrapper = entry.getValue();
                        remove(entry.getKey());
                        if (valueWrapper != null) {
                             expiredRemoved(entry.getKey(), valueWrapper.value);
                   System.out.println("Cache(" + maxEntries +") took " + (System.currentTimeMillis() - start) + " ms to clean " + removeCount + " items");
         static final class EntrySetComparator<K,V> implements Comparator<Entry<K, ValueWrapper<V>>> {
              public int compare(Entry<K, ValueWrapper<V>> o1, Entry<K, ValueWrapper<V>> o2) {
                   ValueWrapper<V> valueWrapper1 = o1.getValue();
                   long age1 = valueWrapper1 != null ?
                        valueWrapper1.age :
                        -1;
                   ValueWrapper<V> valueWrapper2 = o2.getValue();
                   long age2 = valueWrapper2 != null ?
                        valueWrapper2.age :
                        -1;
                   int rval= age1 > age2 ?
                        1 :     
                        age1 == age2 ?
                             0 :
                             -1;
                   return rval;
    //perform a simple santity test.
         public static void main(String ...args) {
              final ConcurrentCacheMap<Integer,String> cache = new ConcurrentCacheMap<Integer,String>(300000,16);
              new Thread() {
                   public void run() {
                        int negCounter = -1;
                        for (;;) {
                             cache.put(negCounter, Integer.toString(negCounter));
                             negCounter--;
                             try {
                                  Thread.sleep(10);
                             } catch (InterruptedException ex){
                                  Thread.currentThread().interrupt();
                                  return;
              }.start();
              int counter = 0;
              for (int i=0; i<301000; i++) {
                   counter++;
                   cache.put(counter,Integer.toString(counter));
              for (int i=0; i<20; i++) {
                   cache.clean();
                   for (int j=0; j<16000; j++) {
                        counter++;
                        cache.put(counter,Integer.toString(counter));
              System.exit(0);

  • ArrayList vs LinkedList

    Can anyone explain with a real time example where these will be used , & whats the difference between them....
    1 ) ArrayList (vs) LinkedList (vs) Collection
    2 ) Abstract Class (vs) Interface

    Some more to add to that .,
    Abstract class vs Interfaces
    Extending threads vs Implementing runnable interface
    HashTable vs HashMap
    Iterator vs Enumeration
    string vs StringBuffer
    Reflections vs Introspection
    Array vs Vector
    ArrayList vs LinkedList
    Throw vs Throws
    can anyone help me in this regard?Most or all of these should be addressed in one of the following or in a google search of the exact terms. Do some research on your own, and then come back with more specific questions. These forums are not a particularly effective substitute for attending class or reading a textbook.
    Sun's basic Java tutorial
    Sun's New To Java Center. Includes an overview of what Java is, instructions for setting up Java, an intro to programming (that includes links to the above tutorial or to parts of it), quizzes, a list of resources, and info on certification and courses.
    http://javaalmanac.com. A couple dozen code examples that supplement The Java Developers Almanac.
    jGuru. A general Java resource site. Includes FAQs, forums, courses, more.
    JavaRanch. To quote the tagline on their homepage: "a friendly place for Java greenhorns." FAQs, forums (moderated, I believe), sample code, all kinds of goodies for newbies. From what I've heard, they live up to the "friendly" claim.
    Bruce Eckel's Thinking in Java (Available online.)
    Joshua Bloch's Effective Java
    Bert Bates and Kathy Sierra's Head First Java.

  • INNEER CLASS

    what is the use of inner class.
    pLEASE

    There are lots of reasons for using an inner class. The simplest is it's one less java file to clutter your editor with. If one class is only used inside the methods of another then making it an inner class is sensible.
    Inner classes are also useful as various kinds of delegate because, unless they are static, they have access to the fields of the outer class. So, for example, if you have a class that houses some kind of collection of data you may want methods that return an iterator or enumerator to allow other classes to walk through the collection. It makes sense to implement those iterators as inner (often anonymous) classes. Or you may want, say, to add different ActionListener s to different buttons. A small inner class which implements ActionListener can invoke the appropriate method in your main class.
    You often use them for structured data of which a class has multiple instances.

  • Enumeration/iteration definitions

    Could someone explain to me the difference between enumeration and iteration? Do either of them do anything special to the contents of a vector?
    I have a vector that contains something like [6, +, 9, *, 15, +, 10]. What I need to do is turn this into an equation and calculate it. i.e. x=6+9*15+10;
    Can this be accomplished by the use of an interator or enumerator? Or am I way off base? Another solution I thought of is to use toString() for the Vector, and then convert the numeric Strings into integers, but have no idea what to do with the operators as I do not believe Java considers them Strings.

    Thanks for letting me know the difference, it wasn't really clear in the book I have.
    The solution you suggested is what I feared. I was hoping Java had some way to recognize the String version of +-*/ as operators. It seems strange to me to have to write a parser to tell it what to do when it sees +-*/ and to tell it the order to evaluate them in. Silly to have to redefine what is already built into Java.
    Probably looks like I shouldn't waste my time putting these items into a Vector, they start out in a String format with some additional characters and I have used a StringTokenizer to eliminate the extra chars and put the tokens and delimiters into a Vector. Guess that is overkill, although I thought it would make it easier. Looks like I should call some sort of parsing method while tokenizing or something.

  • Enumeration and Iterator

    what is the different between Enumeration and Iterator ?

    http://forum.java.sun.com/thread.jspa?threadID=596382&tstart=255

  • Casting Enumeration to Iterator

    The element() method of a Hashtable returns an Enumeration Object.
    I got the following code working fine...
    Hashtable h = new HashTable);
    // Things with the hashtable
    Iterator i =(Iterator) h.elements();
    //Here I am CASTING Elnumeration to Iterator
    while (i.hasNext()) {
    // i.next() kind of things
    Is this correct ???

    Many iterators implement both java.util.Enumeration and java.util.Iterator, but you shouldn't count on it.
    - Marcus

  • Need example for code use with Simple Type Enumeration

    Hello,
    I've created a Simple Type Enumeration in my Web DynPro Project's Local Directory.
    I see that there is an option there to generate a class representation of this Enumeration. Can someone please show me an example code of how to use this Class. For example, to go over the Enumeration and get all the values?

    hi Roy,
    Try this.
    Iterator chk =
    wdContext.nodeB().getNodeInfo().getAttribute("val").getModifiableSimpleType().getSVServices().getModifiableSimpleValueSet().entrySet().iterator();
    I will check it and tel u in some time...
    Regards
    Bharathwaj
    Message was edited by: Bharathwaj R

  • Can you remove elements of hash while enumerating through its keys?

    I am running through each element of a hash table using the keys() method which returns an
    enumeration. Some values I will wish to remove from the hash after I view them while I am still enumerating through its keys. Can you do this without causing an error in the next call enumeration.nextElement()? I know its not a good idea to do this when using an iterator, but I didn't see any documentaion about it regarding enumerations. I could do a test run to check this but I'm not sure that that proves anything, I don't want it to fail ever.

    It's never a good idea to remove or add elements to a collection except by means of the enumerator or iterator that you've got for it. I don't know of any collections library in any language that allows this operation.
    You may be referring to the fact that Iterators are fail-fast, meaning that you get an error if you change the collection while you've got an iterator on it. But this is a good thing, because it alerts you to the fact that you're doing something horribly wrong. With an Enumerator, the code will simply silently fail. :-(

  • ForEach Loop Iteration Order

    Hi,
    I have a SSIS package that uses a Foreach Loop Container to iterate through a series of flat files. The order in which the files are iterated through is based on the name of the file. Is it possible to change the iteration order? More specifically, can the
    iteration order be changed to the date when the file was placed in the iteration folder? i.e files that have been sitting in a folder for a longer amount of time get processed first?

    you can change order but for that you need to use a control table based approach. Using file enumerator  will always take order based on filename.
    The approach would be like this. Have a for each loop based on file enumerator first. Take the filename and arrival date (this you can get inside a script task see
    http://jamelcato.com/111/how-to-check-last-modified-date-using-ssis/) and populate the table with the information.
    Have a object variable and set query as 
    SELECT fileName
    FROM table
    ORDER BY DateField
    Then have a for each loop to iterate through object variable use ADO enumerator
    http://www.select-sql.com/mssql/loop-through-ado-recordset-in-ssis.html
    This would make sure it iterates based on file date value. Then have a variable inside to retrieve filename each time and use it for whatever processing you want.
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

Maybe you are looking for