@@ -0,0 +1,2404 @@
+package com.miviclin.collections;%0A%0Aimport java.util.ArrayList;%0A%0A/**%0A * Object Pool.%0A * %0A * @author Miguel Vicente Linares%0A * %0A * @param %3CT%3E%0A */%0Apublic abstract class Pool%3CT%3E %7B%0A%0A%09private ArrayList%3CT%3E objects;%0A%0A%09/**%0A%09 * Creates a new empty Pool with ititial capacity for 10 elements.%0A%09 */%0A%09public Pool() %7B%0A%09%09this(10);%0A%09%7D%0A%0A%09/**%0A%09 * Creates a new empty Pool.%0A%09 * %0A%09 * @param initialCapacity Initial capacity.%0A%09 */%0A%09public Pool(int initialCapacity) %7B%0A%09%09this.objects = new ArrayList%3CT%3E(initialCapacity);%0A%09%7D%0A%0A%09/**%0A%09 * Retuns an object from this Pool or creates and returns a new object if the Pool is empty.%3Cbr%3E%0A%09 * The returned object is removed from this Pool.%0A%09 * %0A%09 * @return An object from this Pool or a new object if the Pool is empty%0A%09 * @see #createObject()%0A%09 */%0A%09public T obtain() %7B%0A%09%09if (objects.size() %3E 0) %7B%0A%09%09%09int index = objects.size() - 1;%0A%09%09%09return objects.remove(index);%0A%09%09%7D%0A%09%09return createObject();%0A%09%7D%0A%0A%09/**%0A%09 * Creates a new object.%3Cbr%3E%0A%09 * This method is called from %7B@link #obtain()%7D when this pool is empty.%0A%09 * %0A%09 * @return New object%0A%09 */%0A%09public abstract T createObject();%0A%0A%09/**%0A%09 * Adds the specified object to this Pool so it can be reused later.%3Cbr%3E%0A%09 * If the specified object is a %7B@link Poolable%7D object, its %7B@link Poolable#reset()%7D method will be called.%0A%09 * %0A%09 * @param object Object to be added.%0A%09 * @throws IllegalArgumentException if the specified object is null%0A%09 */%0A%09public void recycle(T object) %7B%0A%09%09if (object == null) %7B%0A%09%09%09throw new IllegalArgumentException(%22The specified object can not be null.%22);%0A%09%09%7D%0A%09%09if (object instanceof Poolable) %7B%0A%09%09%09((Poolable) object).reset();%0A%09%09%7D%0A%09%09objects.add(object);%0A%09%7D%0A%0A%09/**%0A%09 * Returns the number of objects in this Pool.%0A%09 * %0A%09 * @return Number of objects in this Pool%0A%09 */%0A%09public int size() %7B%0A%09%09return objects.size();%0A%09%7D%0A%0A%09/**%0A%09 * Returns true if this Pool is empty (size() == 0).%0A%09 * %0A%09 * @return true if this Pool is empty, false otherwise%0A%09 */%0A%09public boolean isEmpty() %7B%0A%09%09return size() == 0;%0A%09%7D%0A%0A%09/**%0A%09 * Removes all objects from this Pool, leaving it empty.%0A%09 */%0A%09public void clear() %7B%0A%09%09objects.clear();%0A%09%7D%0A%0A%09/**%0A%09 * Poolable interface.%0A%09 * %0A%09 * @author Miguel Vicente Linares%0A%09 */%0A%09public interface Poolable %7B%0A%0A%09%09/**%0A%09%09 * Resets the object to its default values. This method is called from %7B@link Pool#recycle(Object)%7D when the%0A%09%09 * object is stored in the %7B@link Pool%7D for later reuse.%0A%09%09 */%0A%09%09public void reset();%0A%0A%09%7D%0A%0A%7D%0A

Add Pool