Merging from -r468106:814127 of collections_jdk5_branch - namely where this code was generified in commit r738956.

git-svn-id: https://svn.apache.org/repos/asf/commons/proper/collections/trunk@814997 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Henri Yandell 2009-09-15 05:29:56 +00:00
parent 1eaccf9ff1
commit d16bc8509f
252 changed files with 8868 additions and 8333 deletions

View File

@ -42,7 +42,7 @@ import java.util.EmptyStackException;
* @author Paul Jack * @author Paul Jack
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public class ArrayStack extends ArrayList implements Buffer { public class ArrayStack<E> extends ArrayList<E> implements Buffer<E> {
/** Ensure serialization compatibility */ /** Ensure serialization compatibility */
private static final long serialVersionUID = 2130079159931574599L; private static final long serialVersionUID = 2130079159931574599L;
@ -84,7 +84,7 @@ public class ArrayStack extends ArrayList implements Buffer {
* @return the top item on the stack * @return the top item on the stack
* @throws EmptyStackException if the stack is empty * @throws EmptyStackException if the stack is empty
*/ */
public Object peek() throws EmptyStackException { public E peek() throws EmptyStackException {
int n = size(); int n = size();
if (n <= 0) { if (n <= 0) {
throw new EmptyStackException(); throw new EmptyStackException();
@ -102,7 +102,7 @@ public class ArrayStack extends ArrayList implements Buffer {
* @throws EmptyStackException if there are not enough items on the * @throws EmptyStackException if there are not enough items on the
* stack to satisfy this request * stack to satisfy this request
*/ */
public Object peek(int n) throws EmptyStackException { public E peek(int n) throws EmptyStackException {
int m = (size() - n) - 1; int m = (size() - n) - 1;
if (m < 0) { if (m < 0) {
throw new EmptyStackException(); throw new EmptyStackException();
@ -117,7 +117,7 @@ public class ArrayStack extends ArrayList implements Buffer {
* @return the top item on the stack * @return the top item on the stack
* @throws EmptyStackException if the stack is empty * @throws EmptyStackException if the stack is empty
*/ */
public Object pop() throws EmptyStackException { public E pop() throws EmptyStackException {
int n = size(); int n = size();
if (n <= 0) { if (n <= 0) {
throw new EmptyStackException(); throw new EmptyStackException();
@ -133,7 +133,7 @@ public class ArrayStack extends ArrayList implements Buffer {
* @param item the item to be added * @param item the item to be added
* @return the item just pushed * @return the item just pushed
*/ */
public Object push(Object item) { public E push(E item) {
add(item); add(item);
return item; return item;
} }
@ -170,7 +170,7 @@ public class ArrayStack extends ArrayList implements Buffer {
* @return the element on the top of the stack * @return the element on the top of the stack
* @throws BufferUnderflowException if the stack is empty * @throws BufferUnderflowException if the stack is empty
*/ */
public Object get() { public E get() {
int size = size(); int size = size();
if (size == 0) { if (size == 0) {
throw new BufferUnderflowException(); throw new BufferUnderflowException();
@ -184,7 +184,7 @@ public class ArrayStack extends ArrayList implements Buffer {
* @return the removed element * @return the removed element
* @throws BufferUnderflowException if the stack is empty * @throws BufferUnderflowException if the stack is empty
*/ */
public Object remove() { public E remove() {
int size = size(); int size = size();
if (size == 0) { if (size == 0) {
throw new BufferUnderflowException(); throw new BufferUnderflowException();

View File

@ -34,7 +34,7 @@ import java.util.Collection;
* @author Herve Quiroz * @author Herve Quiroz
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public interface BoundedCollection extends Collection { public interface BoundedCollection<E> extends Collection<E> {
/** /**
* Returns true if this collection is full and no new elements can be added. * Returns true if this collection is full and no new elements can be added.

View File

@ -31,6 +31,9 @@ package org.apache.commons.collections;
*/ */
public class BufferOverflowException extends RuntimeException { public class BufferOverflowException extends RuntimeException {
/** Serialization version */
private static final long serialVersionUID = -3992254982265755876L;
/** The root cause throwable */ /** The root cause throwable */
private final Throwable throwable; private final Throwable throwable;

View File

@ -34,6 +34,9 @@ import java.util.NoSuchElementException;
*/ */
public class BufferUnderflowException extends NoSuchElementException { public class BufferUnderflowException extends NoSuchElementException {
/** Serialization version */
private static final long serialVersionUID = 4054570024234606028L;
/** The root cause throwable */ /** The root cause throwable */
private final Throwable throwable; private final Throwable throwable;

View File

@ -24,7 +24,8 @@ package org.apache.commons.collections;
* <p> * <p>
* Standard implementations of common closures are provided by * Standard implementations of common closures are provided by
* {@link ClosureUtils}. These include method invokation and for/while loops. * {@link ClosureUtils}. These include method invokation and for/while loops.
* *
* @param <T> the type that the closure acts on
* @since Commons Collections 1.0 * @since Commons Collections 1.0
* @version $Revision$ $Date$ * @version $Revision$ $Date$
* *
@ -32,7 +33,7 @@ package org.apache.commons.collections;
* @author Nicola Ken Barozzi * @author Nicola Ken Barozzi
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public interface Closure { public interface Closure<T> {
/** /**
* Performs an action on the specified input object. * Performs an action on the specified input object.
@ -42,6 +43,6 @@ public interface Closure {
* @throws IllegalArgumentException (runtime) if the input is invalid * @throws IllegalArgumentException (runtime) if the input is invalid
* @throws FunctorException (runtime) if any other error occurs * @throws FunctorException (runtime) if any other error occurs
*/ */
public void execute(Object input); public void execute(T input);
} }

View File

@ -54,14 +54,16 @@ public class ComparatorUtils {
* *
* @see ComparableComparator#getInstance * @see ComparableComparator#getInstance
*/ */
public static final Comparator NATURAL_COMPARATOR = ComparableComparator.getInstance(); @SuppressWarnings("unchecked")
public static final Comparator NATURAL_COMPARATOR = ComparableComparator.<Comparable>getInstance();
/** /**
* Gets a comparator that uses the natural order of the objects. * Gets a comparator that uses the natural order of the objects.
* *
* @return a comparator which uses natural order * @return a comparator which uses natural order
*/ */
public static Comparator naturalComparator() { @SuppressWarnings("unchecked")
public static <E extends Comparable<? super E>> Comparator<E> naturalComparator() {
return NATURAL_COMPARATOR; return NATURAL_COMPARATOR;
} }
@ -76,7 +78,8 @@ public class ComparatorUtils {
* @throws NullPointerException if either comparator is null * @throws NullPointerException if either comparator is null
* @see ComparatorChain * @see ComparatorChain
*/ */
public static Comparator chainedComparator(Comparator comparator1, Comparator comparator2) { @SuppressWarnings("unchecked")
public static <E extends Comparable<? super E>> Comparator<E> chainedComparator(Comparator<E> comparator1, Comparator<E> comparator2) {
return chainedComparator(new Comparator[] {comparator1, comparator2}); return chainedComparator(new Comparator[] {comparator1, comparator2});
} }
@ -89,8 +92,8 @@ public class ComparatorUtils {
* @throws NullPointerException if comparators array is null or contains a null * @throws NullPointerException if comparators array is null or contains a null
* @see ComparatorChain * @see ComparatorChain
*/ */
public static Comparator chainedComparator(Comparator[] comparators) { public static <E extends Comparable<? super E>> Comparator<E> chainedComparator(Comparator<E>[] comparators) {
ComparatorChain chain = new ComparatorChain(); ComparatorChain<E> chain = new ComparatorChain<E>();
for (int i = 0; i < comparators.length; i++) { for (int i = 0; i < comparators.length; i++) {
if (comparators[i] == null) { if (comparators[i] == null) {
throw new NullPointerException("Comparator cannot be null"); throw new NullPointerException("Comparator cannot be null");
@ -111,9 +114,10 @@ public class ComparatorUtils {
* @throws ClassCastException if the comparators collection contains the wrong object type * @throws ClassCastException if the comparators collection contains the wrong object type
* @see ComparatorChain * @see ComparatorChain
*/ */
public static Comparator chainedComparator(Collection comparators) { @SuppressWarnings("unchecked")
public static <E extends Comparable<? super E>> Comparator<E> chainedComparator(Collection<Comparator<E>> comparators) {
return chainedComparator( return chainedComparator(
(Comparator[]) comparators.toArray(new Comparator[comparators.size()]) (Comparator<E>[]) comparators.toArray(new Comparator[comparators.size()])
); );
} }
@ -124,11 +128,8 @@ public class ComparatorUtils {
* @return a comparator that reverses the order of the input comparator * @return a comparator that reverses the order of the input comparator
* @see ReverseComparator * @see ReverseComparator
*/ */
public static Comparator reversedComparator(Comparator comparator) { public static <E> Comparator<E> reversedComparator(Comparator<E> comparator) {
if (comparator == null) { return new ReverseComparator<E>(comparator);
comparator = NATURAL_COMPARATOR;
}
return new ReverseComparator(comparator);
} }
/** /**
@ -143,7 +144,7 @@ public class ComparatorUtils {
* <code>false</code> {@link Boolean}s. * <code>false</code> {@link Boolean}s.
* @return a comparator that sorts booleans * @return a comparator that sorts booleans
*/ */
public static Comparator booleanComparator(boolean trueFirst) { public static Comparator<Boolean> booleanComparator(boolean trueFirst) {
return BooleanComparator.getBooleanComparator(trueFirst); return BooleanComparator.getBooleanComparator(trueFirst);
} }
@ -158,11 +159,12 @@ public class ComparatorUtils {
* @return a version of that comparator that allows nulls * @return a version of that comparator that allows nulls
* @see NullComparator * @see NullComparator
*/ */
public static Comparator nullLowComparator(Comparator comparator) { @SuppressWarnings("unchecked")
public static <E> Comparator<E> nullLowComparator(Comparator<E> comparator) {
if (comparator == null) { if (comparator == null) {
comparator = NATURAL_COMPARATOR; comparator = NATURAL_COMPARATOR;
} }
return new NullComparator(comparator, false); return new NullComparator<E>(comparator, false);
} }
/** /**
@ -176,11 +178,12 @@ public class ComparatorUtils {
* @return a version of that comparator that allows nulls * @return a version of that comparator that allows nulls
* @see NullComparator * @see NullComparator
*/ */
public static Comparator nullHighComparator(Comparator comparator) { @SuppressWarnings("unchecked")
public static <E> Comparator<E> nullHighComparator(Comparator<E> comparator) {
if (comparator == null) { if (comparator == null) {
comparator = NATURAL_COMPARATOR; comparator = NATURAL_COMPARATOR;
} }
return new NullComparator(comparator, true); return new NullComparator<E>(comparator, true);
} }
/** /**
@ -195,11 +198,12 @@ public class ComparatorUtils {
* @return a comparator that transforms its input objects before comparing them * @return a comparator that transforms its input objects before comparing them
* @see TransformingComparator * @see TransformingComparator
*/ */
public static Comparator transformedComparator(Comparator comparator, Transformer transformer) { @SuppressWarnings("unchecked")
public static <E> Comparator<E> transformedComparator(Comparator<E> comparator, Transformer<? super E, ? extends E> transformer) {
if (comparator == null) { if (comparator == null) {
comparator = NATURAL_COMPARATOR; comparator = NATURAL_COMPARATOR;
} }
return new TransformingComparator(transformer, comparator); return new TransformingComparator<E>(transformer, comparator);
} }
/** /**
@ -212,7 +216,8 @@ public class ComparatorUtils {
* @param comparator the sort order to use * @param comparator the sort order to use
* @return the smaller of the two objects * @return the smaller of the two objects
*/ */
public static Object min(Object o1, Object o2, Comparator comparator) { @SuppressWarnings("unchecked")
public static <E> E min(E o1, E o2, Comparator<E> comparator) {
if (comparator == null) { if (comparator == null) {
comparator = NATURAL_COMPARATOR; comparator = NATURAL_COMPARATOR;
} }
@ -230,7 +235,8 @@ public class ComparatorUtils {
* @param comparator the sort order to use * @param comparator the sort order to use
* @return the larger of the two objects * @return the larger of the two objects
*/ */
public static Object max(Object o1, Object o2, Comparator comparator) { @SuppressWarnings("unchecked")
public static <E> E max(E o1, E o2, Comparator<E> comparator) {
if (comparator == null) { if (comparator == null) {
comparator = NATURAL_COMPARATOR; comparator = NATURAL_COMPARATOR;
} }

View File

@ -16,8 +16,10 @@
*/ */
package org.apache.commons.collections; package org.apache.commons.collections;
import java.util.ArrayList;
import java.util.Enumeration; import java.util.Enumeration;
import java.util.List; import java.util.List;
import java.util.StringTokenizer;
import org.apache.commons.collections.iterators.EnumerationIterator; import org.apache.commons.collections.iterators.EnumerationIterator;
@ -47,8 +49,21 @@ public class EnumerationUtils {
* @param enumeration the enumeration to traverse, which should not be <code>null</code>. * @param enumeration the enumeration to traverse, which should not be <code>null</code>.
* @throws NullPointerException if the enumeration parameter is <code>null</code>. * @throws NullPointerException if the enumeration parameter is <code>null</code>.
*/ */
public static List toList(Enumeration enumeration) { public static <E> List<E> toList(Enumeration<E> enumeration) {
return IteratorUtils.toList(new EnumerationIterator(enumeration)); return IteratorUtils.toList(new EnumerationIterator<E>(enumeration));
} }
/**
* Override toList(Enumeration) for StringTokenizer as it implements Enumeration<String>
* for the sake of backward compatibility.
* @param stringTokenizer
* @return List<String>
*/
public static List<String> toList(StringTokenizer stringTokenizer) {
List<String> result = new ArrayList<String>(stringTokenizer.countTokens());
while (stringTokenizer.hasMoreTokens()) {
result.add(stringTokenizer.nextToken());
}
return result;
}
} }

View File

@ -26,13 +26,15 @@ package org.apache.commons.collections;
* {@link FactoryUtils}. These include factories that return a constant, * {@link FactoryUtils}. These include factories that return a constant,
* a copy of a prototype or a new instance. * a copy of a prototype or a new instance.
* *
* @param <T> the type that the factory creates
*
* @since Commons Collections 2.1 * @since Commons Collections 2.1
* @version $Revision$ $Date$ * @version $Revision$ $Date$
* *
* @author Arron Bates * @author Arron Bates
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public interface Factory { public interface Factory<T> {
/** /**
* Create a new object. * Create a new object.
@ -40,6 +42,6 @@ public interface Factory {
* @return a new object * @return a new object
* @throws FunctorException (runtime) if the factory cannot create an object * @throws FunctorException (runtime) if the factory cannot create an object
*/ */
public Object create(); public T create();
} }

View File

@ -30,11 +30,14 @@ import java.io.PrintWriter;
*/ */
public class FunctorException extends RuntimeException { public class FunctorException extends RuntimeException {
/** Serialization version */
private static final long serialVersionUID = 9139387246344345475L;
/** /**
* Does JDK support nested exceptions * Does JDK support nested exceptions
*/ */
private static final boolean JDK_SUPPORTS_NESTED; private static final boolean JDK_SUPPORTS_NESTED;
static { static {
boolean flag = false; boolean flag = false;
try { try {
@ -45,7 +48,7 @@ public class FunctorException extends RuntimeException {
} }
JDK_SUPPORTS_NESTED = flag; JDK_SUPPORTS_NESTED = flag;
} }
/** /**
* Root cause of the exception * Root cause of the exception
*/ */

View File

@ -28,13 +28,15 @@ package org.apache.commons.collections;
* {@link PredicateUtils}. These include true, false, instanceof, equals, and, * {@link PredicateUtils}. These include true, false, instanceof, equals, and,
* or, not, method invokation and null testing. * or, not, method invokation and null testing.
* *
* @param <T> the type that the predicate queries
*
* @since Commons Collections 1.0 * @since Commons Collections 1.0
* @version $Revision$ $Date$ * @version $Revision$ $Date$
* *
* @author James Strachan * @author James Strachan
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public interface Predicate { public interface Predicate<T> {
/** /**
* Use the specified parameter to perform a test that returns true or false. * Use the specified parameter to perform a test that returns true or false.
@ -45,6 +47,6 @@ public interface Predicate {
* @throws IllegalArgumentException (runtime) if the input is invalid * @throws IllegalArgumentException (runtime) if the input is invalid
* @throws FunctorException (runtime) if the predicate encounters a problem * @throws FunctorException (runtime) if the predicate encounters a problem
*/ */
public boolean evaluate(Object object); public boolean evaluate(T object);
} }

View File

@ -29,13 +29,16 @@ package org.apache.commons.collections;
* {@link TransformerUtils}. These include method invokation, returning a constant, * {@link TransformerUtils}. These include method invokation, returning a constant,
* cloning and returning the string value. * cloning and returning the string value.
* *
* @param <I> the input type to the transformer
* @param <O> the output type from the transformer
*
* @since Commons Collections 1.0 * @since Commons Collections 1.0
* @version $Revision$ $Date$ * @version $Revision$ $Date$
* *
* @author James Strachan * @author James Strachan
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public interface Transformer { public interface Transformer<I, O> {
/** /**
* Transforms the input object (leaving it unchanged) into some output object. * Transforms the input object (leaving it unchanged) into some output object.
@ -46,6 +49,6 @@ public interface Transformer {
* @throws IllegalArgumentException (runtime) if the input is invalid * @throws IllegalArgumentException (runtime) if the input is invalid
* @throws FunctorException (runtime) if the transform cannot be completed * @throws FunctorException (runtime) if the transform cannot be completed
*/ */
public Object transform(Object input); public O transform(I input);
} }

View File

@ -33,9 +33,9 @@ import org.apache.commons.collections.set.UnmodifiableSet;
* Abstract implementation of the {@link Bag} interface to simplify the creation * Abstract implementation of the {@link Bag} interface to simplify the creation
* of subclass implementations. * of subclass implementations.
* <p> * <p>
* Subclasses specify a Map implementation to use as the internal storage. * Subclasses specify a Map implementation to use as the internal storage. The
* The map will be used to map bag elements to a number; the number represents * map will be used to map bag elements to a number; the number represents the
* the number of occurrences of that element in the bag. * number of occurrences of that element in the bag.
* *
* @since Commons Collections 3.0 (previously DefaultMapBag v2.0) * @since Commons Collections 3.0 (previously DefaultMapBag v2.0)
* @version $Revision$ $Date$ * @version $Revision$ $Date$
@ -46,16 +46,16 @@ import org.apache.commons.collections.set.UnmodifiableSet;
* @author Janek Bogucki * @author Janek Bogucki
* @author Steve Clark * @author Steve Clark
*/ */
public abstract class AbstractMapBag implements Bag { public abstract class AbstractMapBag<E> implements Bag<E> {
/** The map to use to store the data */ /** The map to use to store the data */
private transient Map map; private transient Map<E, MutableInteger> map;
/** The current total size of the bag */ /** The current total size of the bag */
private int size; private int size;
/** The modification count for fail fast iterators */ /** The modification count for fail fast iterators */
private transient int modCount; private transient int modCount;
/** The modification count for fail fast iterators */ /** The modification count for fail fast iterators */
private transient Set uniqueSet; private transient Set<E> uniqueSet;
/** /**
* Constructor needed for subclass serialisation. * Constructor needed for subclass serialisation.
@ -66,30 +66,30 @@ public abstract class AbstractMapBag implements Bag {
} }
/** /**
* Constructor that assigns the specified Map as the backing store. * Constructor that assigns the specified Map as the backing store. The map
* The map must be empty and non-null. * must be empty and non-null.
* *
* @param map the map to assign * @param map the map to assign
*/ */
protected AbstractMapBag(Map map) { protected AbstractMapBag(Map<E, MutableInteger> map) {
super(); super();
this.map = map; this.map = map;
} }
/** /**
* Utility method for implementations to access the map that backs * Utility method for implementations to access the map that backs this bag.
* this bag. Not intended for interactive use outside of subclasses. * Not intended for interactive use outside of subclasses.
* *
* @return the map being used by the Bag * @return the map being used by the Bag
*/ */
protected Map getMap() { protected Map<E, MutableInteger> getMap() {
return map; return map;
} }
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
/** /**
* Returns the number of elements in this bag. * Returns the number of elements in this bag.
* *
* @return current size of the bag * @return current size of the bag
*/ */
public int size() { public int size() {
@ -98,7 +98,7 @@ public abstract class AbstractMapBag implements Bag {
/** /**
* Returns true if the underlying map is empty. * Returns true if the underlying map is empty.
* *
* @return true if bag is empty * @return true if bag is empty
*/ */
public boolean isEmpty() { public boolean isEmpty() {
@ -106,14 +106,14 @@ public abstract class AbstractMapBag implements Bag {
} }
/** /**
* Returns the number of occurrence of the given element in this bag * Returns the number of occurrence of the given element in this bag by
* by looking up its count in the underlying map. * looking up its count in the underlying map.
* *
* @param object the object to search for * @param object the object to search for
* @return the number of occurrences of the object, zero if not found * @return the number of occurrences of the object, zero if not found
*/ */
public int getCount(Object object) { public int getCount(Object object) {
MutableInteger count = (MutableInteger) map.get(object); MutableInteger count = map.get(object);
if (count != null) { if (count != null) {
return count.value; return count.value;
} }
@ -124,8 +124,8 @@ public abstract class AbstractMapBag implements Bag {
/** /**
* Determines if the bag contains the given element by checking if the * Determines if the bag contains the given element by checking if the
* underlying map contains the element as a key. * underlying map contains the element as a key.
* *
* @param object the object to search for * @param object the object to search for
* @return true if the bag contains the given element * @return true if the bag contains the given element
*/ */
public boolean contains(Object object) { public boolean contains(Object object) {
@ -135,26 +135,27 @@ public abstract class AbstractMapBag implements Bag {
/** /**
* Determines if the bag contains the given elements. * Determines if the bag contains the given elements.
* *
* @param coll the collection to check against * @param coll the collection to check against
* @return <code>true</code> if the Bag contains all the collection * @return <code>true</code> if the Bag contains all the collection
*/ */
public boolean containsAll(Collection coll) { @SuppressWarnings("unchecked")
public boolean containsAll(Collection<?> coll) {
if (coll instanceof Bag) { if (coll instanceof Bag) {
return containsAll((Bag) coll); return containsAll((Bag<?>) coll);
} }
return containsAll(new HashBag(coll)); return containsAll(new HashBag<Object>((Collection<Object>) coll));
} }
/** /**
* Returns <code>true</code> if the bag contains all elements in * Returns <code>true</code> if the bag contains all elements in the given
* the given collection, respecting cardinality. * collection, respecting cardinality.
* *
* @param other the bag to check against * @param other the bag to check against
* @return <code>true</code> if the Bag contains all the collection * @return <code>true</code> if the Bag contains all the collection
*/ */
boolean containsAll(Bag other) { boolean containsAll(Bag<?> other) {
boolean result = true; boolean result = true;
Iterator it = other.uniqueSet().iterator(); Iterator<?> it = other.uniqueSet().iterator();
while (it.hasNext()) { while (it.hasNext()) {
Object current = it.next(); Object current = it.next();
boolean contains = getCount(current) >= other.getCount(current); boolean contains = getCount(current) >= other.getCount(current);
@ -165,22 +166,22 @@ public abstract class AbstractMapBag implements Bag {
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
/** /**
* Gets an iterator over the bag elements. * Gets an iterator over the bag elements. Elements present in the Bag more
* Elements present in the Bag more than once will be returned repeatedly. * than once will be returned repeatedly.
* *
* @return the iterator * @return the iterator
*/ */
public Iterator iterator() { public Iterator<E> iterator() {
return new BagIterator(this); return new BagIterator<E>(this);
} }
/** /**
* Inner class iterator for the Bag. * Inner class iterator for the Bag.
*/ */
static class BagIterator implements Iterator { static class BagIterator<E> implements Iterator<E> {
private AbstractMapBag parent; private AbstractMapBag<E> parent;
private Iterator entryIterator; private Iterator<Map.Entry<E, MutableInteger>> entryIterator;
private Map.Entry current; private Map.Entry<E, MutableInteger> current;
private int itemCount; private int itemCount;
private final int mods; private final int mods;
private boolean canRemove; private boolean canRemove;
@ -188,9 +189,9 @@ public abstract class AbstractMapBag implements Bag {
/** /**
* Constructor. * Constructor.
* *
* @param parent the parent bag * @param parent the parent bag
*/ */
public BagIterator(AbstractMapBag parent) { public BagIterator(AbstractMapBag<E> parent) {
this.parent = parent; this.parent = parent;
this.entryIterator = parent.map.entrySet().iterator(); this.entryIterator = parent.map.entrySet().iterator();
this.current = null; this.current = null;
@ -202,13 +203,13 @@ public abstract class AbstractMapBag implements Bag {
return (itemCount > 0 || entryIterator.hasNext()); return (itemCount > 0 || entryIterator.hasNext());
} }
public Object next() { public E next() {
if (parent.modCount != mods) { if (parent.modCount != mods) {
throw new ConcurrentModificationException(); throw new ConcurrentModificationException();
} }
if (itemCount == 0) { if (itemCount == 0) {
current = (Map.Entry) entryIterator.next(); current = (Map.Entry<E, MutableInteger>) entryIterator.next();
itemCount = ((MutableInteger) current.getValue()).value; itemCount = current.getValue().value;
} }
canRemove = true; canRemove = true;
itemCount--; itemCount--;
@ -222,7 +223,7 @@ public abstract class AbstractMapBag implements Bag {
if (canRemove == false) { if (canRemove == false) {
throw new IllegalStateException(); throw new IllegalStateException();
} }
MutableInteger mut = (MutableInteger) current.getValue(); MutableInteger mut = current.getValue();
if (mut.value > 1) { if (mut.value > 1) {
mut.value--; mut.value--;
} else { } else {
@ -235,48 +236,49 @@ public abstract class AbstractMapBag implements Bag {
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
/** /**
* Adds a new element to the bag, incrementing its count in the underlying map. * Adds a new element to the bag, incrementing its count in the underlying
* * map.
* @param object the object to add *
* @return <code>true</code> if the object was not already in the <code>uniqueSet</code> * @param object the object to add
* @return <code>true</code> if the object was not already in the
* <code>uniqueSet</code>
*/ */
public boolean add(Object object) { public boolean add(E object) {
return add(object, 1); return add(object, 1);
} }
/** /**
* Adds a new element to the bag, incrementing its count in the map. * Adds a new element to the bag, incrementing its count in the map.
* *
* @param object the object to search for * @param object the object to search for
* @param nCopies the number of copies to add * @param nCopies the number of copies to add
* @return <code>true</code> if the object was not already in the <code>uniqueSet</code> * @return <code>true</code> if the object was not already in the
* <code>uniqueSet</code>
*/ */
public boolean add(Object object, int nCopies) { public boolean add(E object, int nCopies) {
modCount++; modCount++;
if (nCopies > 0) { if (nCopies > 0) {
MutableInteger mut = (MutableInteger) map.get(object); MutableInteger mut = map.get(object);
size += nCopies; size += nCopies;
if (mut == null) { if (mut == null) {
map.put(object, new MutableInteger(nCopies)); map.put(object, new MutableInteger(nCopies));
return true; return true;
} else {
mut.value += nCopies;
return false;
} }
} else { mut.value += nCopies;
return false; return false;
} }
return false;
} }
/** /**
* Invokes {@link #add(Object)} for each element in the given collection. * Invokes {@link #add(Object)} for each element in the given collection.
* *
* @param coll the collection to add * @param coll the collection to add
* @return <code>true</code> if this call changed the bag * @return <code>true</code> if this call changed the bag
*/ */
public boolean addAll(Collection coll) { public boolean addAll(Collection<? extends E> coll) {
boolean changed = false; boolean changed = false;
Iterator i = coll.iterator(); Iterator<? extends E> i = coll.iterator();
while (i.hasNext()) { while (i.hasNext()) {
boolean added = add(i.next()); boolean added = add(i.next());
changed = changed || added; changed = changed || added;
@ -297,11 +299,11 @@ public abstract class AbstractMapBag implements Bag {
/** /**
* Removes all copies of the specified object from the bag. * Removes all copies of the specified object from the bag.
* *
* @param object the object to remove * @param object the object to remove
* @return true if the bag changed * @return true if the bag changed
*/ */
public boolean remove(Object object) { public boolean remove(Object object) {
MutableInteger mut = (MutableInteger) map.get(object); MutableInteger mut = map.get(object);
if (mut == null) { if (mut == null) {
return false; return false;
} }
@ -314,12 +316,12 @@ public abstract class AbstractMapBag implements Bag {
/** /**
* Removes a specified number of copies of an object from the bag. * Removes a specified number of copies of an object from the bag.
* *
* @param object the object to remove * @param object the object to remove
* @param nCopies the number of copies to remove * @param nCopies the number of copies to remove
* @return true if the bag changed * @return true if the bag changed
*/ */
public boolean remove(Object object, int nCopies) { public boolean remove(Object object, int nCopies) {
MutableInteger mut = (MutableInteger) map.get(object); MutableInteger mut = map.get(object);
if (mut == null) { if (mut == null) {
return false; return false;
} }
@ -338,15 +340,16 @@ public abstract class AbstractMapBag implements Bag {
} }
/** /**
* Removes objects from the bag according to their count in the specified collection. * Removes objects from the bag according to their count in the specified
* collection.
* *
* @param coll the collection to use * @param coll the collection to use
* @return true if the bag changed * @return true if the bag changed
*/ */
public boolean removeAll(Collection coll) { public boolean removeAll(Collection<?> coll) {
boolean result = false; boolean result = false;
if (coll != null) { if (coll != null) {
Iterator i = coll.iterator(); Iterator<?> i = coll.iterator();
while (i.hasNext()) { while (i.hasNext()) {
boolean changed = remove(i.next(), 1); boolean changed = remove(i.next(), 1);
result = result || changed; result = result || changed;
@ -356,33 +359,34 @@ public abstract class AbstractMapBag implements Bag {
} }
/** /**
* Remove any members of the bag that are not in the given * Remove any members of the bag that are not in the given bag, respecting
* bag, respecting cardinality. * cardinality.
* *
* @param coll the collection to retain * @param coll the collection to retain
* @return true if this call changed the collection * @return true if this call changed the collection
*/ */
public boolean retainAll(Collection coll) { @SuppressWarnings("unchecked")
public boolean retainAll(Collection<?> coll) {
if (coll instanceof Bag) { if (coll instanceof Bag) {
return retainAll((Bag) coll); return retainAll((Bag<?>) coll);
} }
return retainAll(new HashBag(coll)); return retainAll(new HashBag<Object>((Collection<Object>) coll));
} }
/** /**
* Remove any members of the bag that are not in the given * Remove any members of the bag that are not in the given bag, respecting
* bag, respecting cardinality. * cardinality.
* @see #retainAll(Collection) * @see #retainAll(Collection)
* *
* @param other the bag to retain * @param other the bag to retain
* @return <code>true</code> if this call changed the collection * @return <code>true</code> if this call changed the collection
*/ */
boolean retainAll(Bag other) { boolean retainAll(Bag<?> other) {
boolean result = false; boolean result = false;
Bag excess = new HashBag(); Bag<E> excess = new HashBag<E>();
Iterator i = uniqueSet().iterator(); Iterator<E> i = uniqueSet().iterator();
while (i.hasNext()) { while (i.hasNext()) {
Object current = i.next(); E current = i.next();
int myCount = getCount(current); int myCount = getCount(current);
int otherCount = other.getCount(current); int otherCount = other.getCount(current);
if (1 <= otherCount && otherCount <= myCount) { if (1 <= otherCount && otherCount <= myCount) {
@ -404,15 +408,15 @@ public abstract class AbstractMapBag implements Bag {
protected static class MutableInteger { protected static class MutableInteger {
/** The value of this mutable. */ /** The value of this mutable. */
protected int value; protected int value;
/** /**
* Constructor. * Constructor.
* @param value the initial value * @param value the initial value
*/ */
MutableInteger(int value) { MutableInteger(int value) {
this.value = value; this.value = value;
} }
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (obj instanceof MutableInteger == false) { if (obj instanceof MutableInteger == false) {
return false; return false;
@ -424,19 +428,19 @@ public abstract class AbstractMapBag implements Bag {
return value; return value;
} }
} }
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
/** /**
* Returns an array of all of this bag's elements. * Returns an array of all of this bag's elements.
* *
* @return an array of all of this bag's elements * @return an array of all of this bag's elements
*/ */
public Object[] toArray() { public Object[] toArray() {
Object[] result = new Object[size()]; Object[] result = new Object[size()];
int i = 0; int i = 0;
Iterator it = map.keySet().iterator(); Iterator<E> it = map.keySet().iterator();
while (it.hasNext()) { while (it.hasNext()) {
Object current = it.next(); E current = it.next();
for (int index = getCount(current); index > 0; index--) { for (int index = getCount(current); index > 0; index--) {
result[i++] = current; result[i++] = current;
} }
@ -446,38 +450,39 @@ public abstract class AbstractMapBag implements Bag {
/** /**
* Returns an array of all of this bag's elements. * Returns an array of all of this bag's elements.
* *
* @param array the array to populate * @param array the array to populate
* @return an array of all of this bag's elements * @return an array of all of this bag's elements
*/ */
public Object[] toArray(Object[] array) { @SuppressWarnings("unchecked")
public <T> T[] toArray(T[] array) {
int size = size(); int size = size();
if (array.length < size) { if (array.length < size) {
array = (Object[]) Array.newInstance(array.getClass().getComponentType(), size); array = (T[]) Array.newInstance(array.getClass().getComponentType(), size);
} }
int i = 0; int i = 0;
Iterator it = map.keySet().iterator(); Iterator<E> it = map.keySet().iterator();
while (it.hasNext()) { while (it.hasNext()) {
Object current = it.next(); E current = it.next();
for (int index = getCount(current); index > 0; index--) { for (int index = getCount(current); index > 0; index--) {
array[i++] = current; array[i++] = (T) current;
} }
} }
if (array.length > size) { while (i < array.length) {
array[size] = null; array[i++] = null;
} }
return array; return array;
} }
/** /**
* Returns an unmodifiable view of the underlying map's key set. * Returns an unmodifiable view of the underlying map's key set.
* *
* @return the set of unique elements in this bag * @return the set of unique elements in this bag
*/ */
public Set uniqueSet() { public Set<E> uniqueSet() {
if (uniqueSet == null) { if (uniqueSet == null) {
uniqueSet = UnmodifiableSet.decorate(map.keySet()); uniqueSet = UnmodifiableSet.<E> decorate(map.keySet());
} }
return uniqueSet; return uniqueSet;
} }
@ -485,26 +490,28 @@ public abstract class AbstractMapBag implements Bag {
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
/** /**
* Write the map out using a custom routine. * Write the map out using a custom routine.
* @param out the output stream * @param out the output stream
* @throws IOException * @throws IOException
*/ */
protected void doWriteObject(ObjectOutputStream out) throws IOException { protected void doWriteObject(ObjectOutputStream out) throws IOException {
out.writeInt(map.size()); out.writeInt(map.size());
for (Iterator it = map.entrySet().iterator(); it.hasNext();) { for (Iterator<Map.Entry<E, MutableInteger>> it = map.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next(); Map.Entry<E, MutableInteger> entry = it.next();
out.writeObject(entry.getKey()); out.writeObject(entry.getKey());
out.writeInt(((MutableInteger) entry.getValue()).value); out.writeInt(entry.getValue().value);
} }
} }
/** /**
* Read the map in using a custom routine. * Read the map in using a custom routine.
* @param map the map to use * @param map the map to use
* @param in the input stream * @param in the input stream
* @throws IOException * @throws IOException
* @throws ClassNotFoundException * @throws ClassNotFoundException
*/ */
protected void doReadObject(Map map, ObjectInputStream in) throws IOException, ClassNotFoundException { @SuppressWarnings("unchecked")
protected void doReadObject(Map map, ObjectInputStream in) throws IOException,
ClassNotFoundException {
this.map = map; this.map = map;
int entrySize = in.readInt(); int entrySize = in.readInt();
for (int i = 0; i < entrySize; i++) { for (int i = 0; i < entrySize; i++) {
@ -514,14 +521,13 @@ public abstract class AbstractMapBag implements Bag {
size += count; size += count;
} }
} }
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
/** /**
* Compares this Bag to another. * Compares this Bag to another. This Bag equals another Bag if it contains
* This Bag equals another Bag if it contains the same number of occurrences of * the same number of occurrences of the same elements.
* the same elements.
* *
* @param object the Bag to compare to * @param object the Bag to compare to
* @return true if equal * @return true if equal
*/ */
public boolean equals(Object object) { public boolean equals(Object object) {
@ -531,12 +537,12 @@ public abstract class AbstractMapBag implements Bag {
if (object instanceof Bag == false) { if (object instanceof Bag == false) {
return false; return false;
} }
Bag other = (Bag) object; Bag<?> other = (Bag<?>) object;
if (other.size() != size()) { if (other.size() != size()) {
return false; return false;
} }
for (Iterator it = map.keySet().iterator(); it.hasNext();) { for (Iterator<E> it = map.keySet().iterator(); it.hasNext();) {
Object element = it.next(); E element = it.next();
if (other.getCount(element) != getCount(element)) { if (other.getCount(element) != getCount(element)) {
return false; return false;
} }
@ -546,19 +552,19 @@ public abstract class AbstractMapBag implements Bag {
/** /**
* Gets a hash code for the Bag compatible with the definition of equals. * Gets a hash code for the Bag compatible with the definition of equals.
* The hash code is defined as the sum total of a hash code for each element. * The hash code is defined as the sum total of a hash code for each
* The per element hash code is defined as * element. The per element hash code is defined as
* <code>(e==null ? 0 : e.hashCode()) ^ noOccurances)</code>. * <code>(e==null ? 0 : e.hashCode()) ^ noOccurances)</code>. This hash code
* This hash code is compatible with the Set interface. * is compatible with the Set interface.
* *
* @return the hash code of the Bag * @return the hash code of the Bag
*/ */
public int hashCode() { public int hashCode() {
int total = 0; int total = 0;
for (Iterator it = map.entrySet().iterator(); it.hasNext();) { for (Iterator<Map.Entry<E, MutableInteger>> it = map.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next(); Map.Entry<E, MutableInteger> entry = it.next();
Object element = entry.getKey(); E element = entry.getKey();
MutableInteger count = (MutableInteger) entry.getValue(); MutableInteger count = entry.getValue();
total += (element == null ? 0 : element.hashCode()) ^ count.value; total += (element == null ? 0 : element.hashCode()) ^ count.value;
} }
return total; return total;
@ -575,7 +581,7 @@ public abstract class AbstractMapBag implements Bag {
} }
StringBuffer buf = new StringBuffer(); StringBuffer buf = new StringBuffer();
buf.append('['); buf.append('[');
Iterator it = uniqueSet().iterator(); Iterator<E> it = uniqueSet().iterator();
while (it.hasNext()) { while (it.hasNext()) {
Object current = it.next(); Object current = it.next();
int count = getCount(current); int count = getCount(current);
@ -589,5 +595,5 @@ public abstract class AbstractMapBag implements Bag {
buf.append(']'); buf.append(']');
return buf.toString(); return buf.toString();
} }
} }

View File

@ -41,8 +41,8 @@ import org.apache.commons.collections.Bag;
* @author Chuck Burdick * @author Chuck Burdick
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public class HashBag public class HashBag<E>
extends AbstractMapBag implements Bag, Serializable { extends AbstractMapBag<E> implements Bag<E>, Serializable {
/** Serial version lock */ /** Serial version lock */
private static final long serialVersionUID = -6561115435802554013L; private static final long serialVersionUID = -6561115435802554013L;
@ -51,7 +51,7 @@ public class HashBag
* Constructs an empty <code>HashBag</code>. * Constructs an empty <code>HashBag</code>.
*/ */
public HashBag() { public HashBag() {
super(new HashMap()); super(new HashMap<E, MutableInteger>());
} }
/** /**
@ -59,7 +59,7 @@ public class HashBag
* *
* @param coll a collection to copy into this bag * @param coll a collection to copy into this bag
*/ */
public HashBag(Collection coll) { public HashBag(Collection<? extends E> coll) {
this(); this();
addAll(coll); addAll(coll);
} }
@ -78,7 +78,7 @@ public class HashBag
*/ */
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject(); in.defaultReadObject();
super.doReadObject(new HashMap(), in); super.doReadObject(new HashMap<E, MutableInteger>(), in);
} }
} }

View File

@ -38,8 +38,8 @@ import org.apache.commons.collections.set.TransformedSet;
* *
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public class TransformedBag public class TransformedBag<E>
extends TransformedCollection implements Bag { extends TransformedCollection<E> implements Bag<E> {
/** Serialization version */ /** Serialization version */
private static final long serialVersionUID = 5421170911299074185L; private static final long serialVersionUID = 5421170911299074185L;
@ -56,8 +56,8 @@ public class TransformedBag
* @return a new transformed Bag * @return a new transformed Bag
* @throws IllegalArgumentException if bag or transformer is null * @throws IllegalArgumentException if bag or transformer is null
*/ */
public static Bag decorate(Bag bag, Transformer transformer) { public static <E> Bag<E> decorate(Bag<E> bag, Transformer<? super E, ? extends E> transformer) {
return new TransformedBag(bag, transformer); return new TransformedBag<E>(bag, transformer);
} }
/** /**
@ -74,13 +74,14 @@ public class TransformedBag
* @throws IllegalArgumentException if bag or transformer is null * @throws IllegalArgumentException if bag or transformer is null
* @since Commons Collections 3.3 * @since Commons Collections 3.3
*/ */
// TODO: Generics
public static Bag decorateTransform(Bag bag, Transformer transformer) { public static Bag decorateTransform(Bag bag, Transformer transformer) {
TransformedBag decorated = new TransformedBag(bag, transformer); TransformedBag decorated = new TransformedBag(bag, transformer);
if (transformer != null && bag != null && bag.size() > 0) { if (transformer != null && bag != null && bag.size() > 0) {
Object[] values = bag.toArray(); Object[] values = bag.toArray();
bag.clear(); bag.clear();
for(int i=0; i<values.length; i++) { for(int i=0; i<values.length; i++) {
decorated.getCollection().add(transformer.transform(values[i])); decorated.decorated().add(transformer.transform(values[i]));
} }
} }
return decorated; return decorated;
@ -97,7 +98,7 @@ public class TransformedBag
* @param transformer the transformer to use for conversion, must not be null * @param transformer the transformer to use for conversion, must not be null
* @throws IllegalArgumentException if bag or transformer is null * @throws IllegalArgumentException if bag or transformer is null
*/ */
protected TransformedBag(Bag bag, Transformer transformer) { protected TransformedBag(Bag<E> bag, Transformer<? super E, ? extends E> transformer) {
super(bag, transformer); super(bag, transformer);
} }
@ -106,8 +107,8 @@ public class TransformedBag
* *
* @return the decorated bag * @return the decorated bag
*/ */
protected Bag getBag() { protected Bag<E> getBag() {
return (Bag) collection; return (Bag<E>) collection;
} }
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
@ -120,14 +121,13 @@ public class TransformedBag
} }
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
public boolean add(Object object, int nCopies) { public boolean add(E object, int nCopies) {
object = transform(object); return getBag().add(transform(object), nCopies);
return getBag().add(object, nCopies);
} }
public Set uniqueSet() { public Set<E> uniqueSet() {
Set set = getBag().uniqueSet(); Set<E> set = getBag().uniqueSet();
return TransformedSet.decorate(set, transformer); return TransformedSet.<E>decorate(set, transformer);
} }
} }

View File

@ -36,8 +36,8 @@ import org.apache.commons.collections.Transformer;
* *
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public class TransformedSortedBag public class TransformedSortedBag<E>
extends TransformedBag implements SortedBag { extends TransformedBag<E> implements SortedBag<E> {
/** Serialization version */ /** Serialization version */
private static final long serialVersionUID = -251737742649401930L; private static final long serialVersionUID = -251737742649401930L;
@ -54,8 +54,8 @@ public class TransformedSortedBag
* @return a new transformed SortedBag * @return a new transformed SortedBag
* @throws IllegalArgumentException if bag or transformer is null * @throws IllegalArgumentException if bag or transformer is null
*/ */
public static SortedBag decorate(SortedBag bag, Transformer transformer) { public static <E> SortedBag<E> decorate(SortedBag<E> bag, Transformer<? super E, ? extends E> transformer) {
return new TransformedSortedBag(bag, transformer); return new TransformedSortedBag<E>(bag, transformer);
} }
/** /**
@ -72,13 +72,14 @@ public class TransformedSortedBag
* @throws IllegalArgumentException if bag or transformer is null * @throws IllegalArgumentException if bag or transformer is null
* @since Commons Collections 3.3 * @since Commons Collections 3.3
*/ */
// TODO: Generics
public static SortedBag decorateTransform(SortedBag bag, Transformer transformer) { public static SortedBag decorateTransform(SortedBag bag, Transformer transformer) {
TransformedSortedBag decorated = new TransformedSortedBag(bag, transformer); TransformedSortedBag decorated = new TransformedSortedBag(bag, transformer);
if (transformer != null && bag != null && bag.size() > 0) { if (transformer != null && bag != null && bag.size() > 0) {
Object[] values = bag.toArray(); Object[] values = bag.toArray();
bag.clear(); bag.clear();
for(int i=0; i<values.length; i++) { for(int i=0; i<values.length; i++) {
decorated.getCollection().add(transformer.transform(values[i])); decorated.decorated().add(transformer.transform(values[i]));
} }
} }
return decorated; return decorated;
@ -95,7 +96,7 @@ public class TransformedSortedBag
* @param transformer the transformer to use for conversion, must not be null * @param transformer the transformer to use for conversion, must not be null
* @throws IllegalArgumentException if bag or transformer is null * @throws IllegalArgumentException if bag or transformer is null
*/ */
protected TransformedSortedBag(SortedBag bag, Transformer transformer) { protected TransformedSortedBag(SortedBag<E> bag, Transformer<? super E, ? extends E> transformer) {
super(bag, transformer); super(bag, transformer);
} }
@ -104,20 +105,20 @@ public class TransformedSortedBag
* *
* @return the decorated bag * @return the decorated bag
*/ */
protected SortedBag getSortedBag() { protected SortedBag<E> getSortedBag() {
return (SortedBag) collection; return (SortedBag<E>) collection;
} }
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
public Object first() { public E first() {
return getSortedBag().first(); return getSortedBag().first();
} }
public Object last() { public E last() {
return getSortedBag().last(); return getSortedBag().last();
} }
public Comparator comparator() { public Comparator<? super E> comparator() {
return getSortedBag().comparator(); return getSortedBag().comparator();
} }

View File

@ -34,11 +34,11 @@ import org.apache.commons.collections.SortedBag;
* Order will be maintained among the bag members and can be viewed through the * Order will be maintained among the bag members and can be viewed through the
* iterator. * iterator.
* <p> * <p>
* A <code>Bag</code> stores each object in the collection together with a * A <code>Bag</code> stores each object in the collection together with a count
* count of occurrences. Extra methods on the interface allow multiple copies * of occurrences. Extra methods on the interface allow multiple copies of an
* of an object to be added or removed at once. It is important to read the * object to be added or removed at once. It is important to read the interface
* interface javadoc carefully as several methods violate the * javadoc carefully as several methods violate the <code>Collection</code>
* <code>Collection</code> interface specification. * interface specification.
* *
* @since Commons Collections 3.0 (previously in main package v2.0) * @since Commons Collections 3.0 (previously in main package v2.0)
* @version $Revision$ $Date$ * @version $Revision$ $Date$
@ -46,60 +46,69 @@ import org.apache.commons.collections.SortedBag;
* @author Chuck Burdick * @author Chuck Burdick
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public class TreeBag public class TreeBag<E> extends AbstractMapBag<E> implements SortedBag<E>, Serializable {
extends AbstractMapBag implements SortedBag, Serializable {
/** Serial version lock */ /** Serial version lock */
private static final long serialVersionUID = -7740146511091606676L; private static final long serialVersionUID = -7740146511091606676L;
/** /**
* Constructs an empty <code>TreeBag</code>. * Constructs an empty <code>TreeBag</code>.
*/ */
public TreeBag() { public TreeBag() {
super(new TreeMap()); super(new TreeMap<E, MutableInteger>());
} }
/** /**
* Constructs an empty bag that maintains order on its unique * Constructs an empty bag that maintains order on its unique representative
* representative members according to the given {@link Comparator}. * members according to the given {@link Comparator}.
* *
* @param comparator the comparator to use * @param comparator the comparator to use
*/ */
public TreeBag(Comparator comparator) { public TreeBag(Comparator<? super E> comparator) {
super(new TreeMap(comparator)); super(new TreeMap<E, MutableInteger>(comparator));
} }
/** /**
* Constructs a <code>TreeBag</code> containing all the members of the * Constructs a <code>TreeBag</code> containing all the members of the
* specified collection. * specified collection.
* *
* @param coll the collection to copy into the bag * @param coll the collection to copy into the bag
*/ */
public TreeBag(Collection coll) { public TreeBag(Collection<? extends E> coll) {
this(); this();
addAll(coll); addAll(coll);
} }
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
public boolean add(Object o) { // TODO: Generics - should this be E<? extends Comparable> or some such?
if(comparator() == null && !(o instanceof Comparable)) { public boolean add(E object) {
throw new IllegalArgumentException("Objects of type " + o.getClass() + " cannot be added to " + if(comparator() == null && !(object instanceof Comparable)) {
throw new IllegalArgumentException("Objects of type " + object.getClass() + " cannot be added to " +
"a naturally ordered TreeBag as it does not implement Comparable"); "a naturally ordered TreeBag as it does not implement Comparable");
} }
return super.add(o); return super.add(object);
} }
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
public Object first() { public E first() {
return ((SortedMap) getMap()).firstKey(); return getMap().firstKey();
} }
public Object last() { public E last() {
return ((SortedMap) getMap()).lastKey(); return getMap().lastKey();
} }
public Comparator comparator() { public Comparator<? super E> comparator() {
return ((SortedMap) getMap()).comparator(); return getMap().comparator();
}
/**
* {@inheritDoc}
*/
@Override
protected SortedMap<E, org.apache.commons.collections.bag.AbstractMapBag.MutableInteger> getMap() {
return (SortedMap<E, org.apache.commons.collections.bag.AbstractMapBag.MutableInteger>) super
.getMap();
} }
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
@ -115,10 +124,11 @@ public class TreeBag
/** /**
* Read the bag in using a custom routine. * Read the bag in using a custom routine.
*/ */
@SuppressWarnings("unchecked")
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject(); in.defaultReadObject();
Comparator comp = (Comparator) in.readObject(); Comparator comp = (Comparator) in.readObject();
super.doReadObject(new TreeMap(comp), in); super.doReadObject(new TreeMap(comp), in);
} }
} }

View File

@ -42,8 +42,7 @@ import org.apache.commons.collections.BidiMap;
* @author Matthew Hawthorne * @author Matthew Hawthorne
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public class DualHashBidiMap public class DualHashBidiMap<K, V> extends AbstractDualBidiMap<K, V> implements Serializable {
extends AbstractDualBidiMap implements Serializable {
/** Ensure serialization compatibility */ /** Ensure serialization compatibility */
private static final long serialVersionUID = 721969328361808L; private static final long serialVersionUID = 721969328361808L;
@ -52,7 +51,7 @@ public class DualHashBidiMap
* Creates an empty <code>HashBidiMap</code>. * Creates an empty <code>HashBidiMap</code>.
*/ */
public DualHashBidiMap() { public DualHashBidiMap() {
super(new HashMap(), new HashMap()); super(new HashMap<K, V>(), new HashMap<V, K>());
} }
/** /**
@ -61,8 +60,8 @@ public class DualHashBidiMap
* *
* @param map the map whose mappings are to be placed in this map * @param map the map whose mappings are to be placed in this map
*/ */
public DualHashBidiMap(Map map) { public DualHashBidiMap(Map<K, V> map) {
super(new HashMap(), new HashMap()); super(new HashMap<K, V>(), new HashMap<V, K>());
putAll(map); putAll(map);
} }
@ -73,7 +72,7 @@ public class DualHashBidiMap
* @param reverseMap the reverse direction map * @param reverseMap the reverse direction map
* @param inverseBidiMap the inverse BidiMap * @param inverseBidiMap the inverse BidiMap
*/ */
protected DualHashBidiMap(Map normalMap, Map reverseMap, BidiMap inverseBidiMap) { protected DualHashBidiMap(Map<K, V> normalMap, Map<V, K> reverseMap, BidiMap<V, K> inverseBidiMap) {
super(normalMap, reverseMap, inverseBidiMap); super(normalMap, reverseMap, inverseBidiMap);
} }
@ -85,21 +84,22 @@ public class DualHashBidiMap
* @param inverseBidiMap the inverse BidiMap * @param inverseBidiMap the inverse BidiMap
* @return new bidi map * @return new bidi map
*/ */
protected BidiMap createBidiMap(Map normalMap, Map reverseMap, BidiMap inverseBidiMap) { protected BidiMap<V, K> createBidiMap(Map<V, K> normalMap, Map<K, V> reverseMap, BidiMap<K, V> inverseBidiMap) {
return new DualHashBidiMap(normalMap, reverseMap, inverseBidiMap); return new DualHashBidiMap<V, K>(normalMap, reverseMap, inverseBidiMap);
} }
// Serialization // Serialization
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
private void writeObject(ObjectOutputStream out) throws IOException { private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject(); out.defaultWriteObject();
out.writeObject(maps[0]); out.writeObject(normalMap);
} }
@SuppressWarnings("unchecked")
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject(); in.defaultReadObject();
maps[0] = new HashMap(); normalMap = new HashMap();
maps[1] = new HashMap(); reverseMap = new HashMap();
Map map = (Map) in.readObject(); Map map = (Map) in.readObject();
putAll(map); putAll(map);
} }

View File

@ -38,36 +38,36 @@ import org.apache.commons.collections.set.UnmodifiableSet;
* *
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public final class UnmodifiableBidiMap public final class UnmodifiableBidiMap<K, V>
extends AbstractBidiMapDecorator implements Unmodifiable { extends AbstractBidiMapDecorator<K, V> implements Unmodifiable {
/** The inverse unmodifiable map */ /** The inverse unmodifiable map */
private UnmodifiableBidiMap inverse; private UnmodifiableBidiMap<V, K> inverse;
/** /**
* Factory method to create an unmodifiable map. * Factory method to create an unmodifiable map.
* <p> * <p>
* If the map passed in is already unmodifiable, it is returned. * If the map passed in is already unmodifiable, it is returned.
* *
* @param map the map to decorate, must not be null * @param map the map to decorate, must not be null
* @return an unmodifiable BidiMap * @return an unmodifiable BidiMap
* @throws IllegalArgumentException if map is null * @throws IllegalArgumentException if map is null
*/ */
public static BidiMap decorate(BidiMap map) { public static <K, V> BidiMap<K, V> decorate(BidiMap<K, V> map) {
if (map instanceof Unmodifiable) { if (map instanceof Unmodifiable) {
return map; return map;
} }
return new UnmodifiableBidiMap(map); return new UnmodifiableBidiMap<K, V>(map);
} }
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
/** /**
* Constructor that wraps (not copies). * Constructor that wraps (not copies).
* *
* @param map the map to decorate, must not be null * @param map the map to decorate, must not be null
* @throws IllegalArgumentException if map is null * @throws IllegalArgumentException if map is null
*/ */
private UnmodifiableBidiMap(BidiMap map) { private UnmodifiableBidiMap(BidiMap<K, V> map) {
super(map); super(map);
} }
@ -76,49 +76,49 @@ public final class UnmodifiableBidiMap
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public Object put(Object key, Object value) { public V put(K key, V value) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public void putAll(Map mapToCopy) { public void putAll(Map<? extends K, ? extends V> mapToCopy) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public Object remove(Object key) { public V remove(Object key) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public Set entrySet() { public Set<Map.Entry<K, V>> entrySet() {
Set set = super.entrySet(); Set<Map.Entry<K, V>> set = super.entrySet();
return UnmodifiableEntrySet.decorate(set); return UnmodifiableEntrySet.decorate(set);
} }
public Set keySet() { public Set<K> keySet() {
Set set = super.keySet(); Set<K> set = super.keySet();
return UnmodifiableSet.decorate(set); return UnmodifiableSet.decorate(set);
} }
public Collection values() { public Collection<V> values() {
Collection coll = super.values(); Collection<V> coll = super.values();
return UnmodifiableCollection.decorate(coll); return UnmodifiableCollection.decorate(coll);
} }
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
public Object removeValue(Object value) { public K removeValue(Object value) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public MapIterator mapIterator() { public MapIterator<K, V> mapIterator() {
MapIterator it = getBidiMap().mapIterator(); MapIterator<K, V> it = decorated().mapIterator();
return UnmodifiableMapIterator.decorate(it); return UnmodifiableMapIterator.decorate(it);
} }
public BidiMap inverseBidiMap() { public synchronized BidiMap<V, K> inverseBidiMap() {
if (inverse == null) { if (inverse == null) {
inverse = new UnmodifiableBidiMap(getBidiMap().inverseBidiMap()); inverse = new UnmodifiableBidiMap<V, K>(decorated().inverseBidiMap());
inverse.inverse = this; inverse.inverse = this;
} }
return inverse; return inverse;
} }
} }

View File

@ -20,8 +20,6 @@ import java.util.Collection;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import org.apache.commons.collections.BidiMap;
import org.apache.commons.collections.MapIterator;
import org.apache.commons.collections.OrderedBidiMap; import org.apache.commons.collections.OrderedBidiMap;
import org.apache.commons.collections.OrderedMapIterator; import org.apache.commons.collections.OrderedMapIterator;
import org.apache.commons.collections.Unmodifiable; import org.apache.commons.collections.Unmodifiable;
@ -40,36 +38,36 @@ import org.apache.commons.collections.set.UnmodifiableSet;
* *
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public final class UnmodifiableOrderedBidiMap public final class UnmodifiableOrderedBidiMap<K, V>
extends AbstractOrderedBidiMapDecorator implements Unmodifiable { extends AbstractOrderedBidiMapDecorator<K, V> implements Unmodifiable {
/** The inverse unmodifiable map */ /** The inverse unmodifiable map */
private UnmodifiableOrderedBidiMap inverse; private UnmodifiableOrderedBidiMap<V, K> inverse;
/** /**
* Factory method to create an unmodifiable map. * Factory method to create an unmodifiable map.
* <p> * <p>
* If the map passed in is already unmodifiable, it is returned. * If the map passed in is already unmodifiable, it is returned.
* *
* @param map the map to decorate, must not be null * @param map the map to decorate, must not be null
* @return an unmodifiable OrderedBidiMap * @return an unmodifiable OrderedBidiMap
* @throws IllegalArgumentException if map is null * @throws IllegalArgumentException if map is null
*/ */
public static OrderedBidiMap decorate(OrderedBidiMap map) { public static <K, V> OrderedBidiMap<K, V> decorate(OrderedBidiMap<K, V> map) {
if (map instanceof Unmodifiable) { if (map instanceof Unmodifiable) {
return map; return map;
} }
return new UnmodifiableOrderedBidiMap(map); return new UnmodifiableOrderedBidiMap<K, V>(map);
} }
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
/** /**
* Constructor that wraps (not copies). * Constructor that wraps (not copies).
* *
* @param map the map to decorate, must not be null * @param map the map to decorate, must not be null
* @throws IllegalArgumentException if map is null * @throws IllegalArgumentException if map is null
*/ */
private UnmodifiableOrderedBidiMap(OrderedBidiMap map) { private UnmodifiableOrderedBidiMap(OrderedBidiMap<K, V> map) {
super(map); super(map);
} }
@ -78,55 +76,51 @@ public final class UnmodifiableOrderedBidiMap
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public Object put(Object key, Object value) { public V put(K key, V value) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public void putAll(Map mapToCopy) { public void putAll(Map<? extends K, ? extends V> mapToCopy) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public Object remove(Object key) { public V remove(Object key) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public Set entrySet() { public Set<Map.Entry<K, V>> entrySet() {
Set set = super.entrySet(); Set<Map.Entry<K, V>> set = super.entrySet();
return UnmodifiableEntrySet.decorate(set); return UnmodifiableEntrySet.decorate(set);
} }
public Set keySet() { public Set<K> keySet() {
Set set = super.keySet(); Set<K> set = super.keySet();
return UnmodifiableSet.decorate(set); return UnmodifiableSet.decorate(set);
} }
public Collection values() { public Collection<V> values() {
Collection coll = super.values(); Collection<V> coll = super.values();
return UnmodifiableCollection.decorate(coll); return UnmodifiableCollection.decorate(coll);
} }
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
public Object removeValue(Object value) { public K removeValue(Object value) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public MapIterator mapIterator() { public OrderedBidiMap<V, K> inverseBidiMap() {
return orderedMapIterator();
}
public BidiMap inverseBidiMap() {
return inverseOrderedBidiMap(); return inverseOrderedBidiMap();
} }
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
public OrderedMapIterator orderedMapIterator() { public OrderedMapIterator<K, V> mapIterator() {
OrderedMapIterator it = getOrderedBidiMap().orderedMapIterator(); OrderedMapIterator<K, V> it = decorated().mapIterator();
return UnmodifiableOrderedMapIterator.decorate(it); return UnmodifiableOrderedMapIterator.decorate(it);
} }
public OrderedBidiMap inverseOrderedBidiMap() { public OrderedBidiMap<V, K> inverseOrderedBidiMap() {
if (inverse == null) { if (inverse == null) {
inverse = new UnmodifiableOrderedBidiMap(getOrderedBidiMap().inverseOrderedBidiMap()); inverse = new UnmodifiableOrderedBidiMap<V, K>(decorated().inverseBidiMap());
inverse.inverse = this; inverse.inverse = this;
} }
return inverse; return inverse;

View File

@ -21,9 +21,6 @@ import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.SortedMap; import java.util.SortedMap;
import org.apache.commons.collections.BidiMap;
import org.apache.commons.collections.MapIterator;
import org.apache.commons.collections.OrderedBidiMap;
import org.apache.commons.collections.OrderedMapIterator; import org.apache.commons.collections.OrderedMapIterator;
import org.apache.commons.collections.SortedBidiMap; import org.apache.commons.collections.SortedBidiMap;
import org.apache.commons.collections.Unmodifiable; import org.apache.commons.collections.Unmodifiable;
@ -43,36 +40,36 @@ import org.apache.commons.collections.set.UnmodifiableSet;
* *
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public final class UnmodifiableSortedBidiMap public final class UnmodifiableSortedBidiMap<K, V>
extends AbstractSortedBidiMapDecorator implements Unmodifiable { extends AbstractSortedBidiMapDecorator<K, V> implements Unmodifiable {
/** The inverse unmodifiable map */ /** The inverse unmodifiable map */
private UnmodifiableSortedBidiMap inverse; private UnmodifiableSortedBidiMap<V, K> inverse;
/** /**
* Factory method to create an unmodifiable map. * Factory method to create an unmodifiable map.
* <p> * <p>
* If the map passed in is already unmodifiable, it is returned. * If the map passed in is already unmodifiable, it is returned.
* *
* @param map the map to decorate, must not be null * @param map the map to decorate, must not be null
* @return an unmodifiable SortedBidiMap * @return an unmodifiable SortedBidiMap
* @throws IllegalArgumentException if map is null * @throws IllegalArgumentException if map is null
*/ */
public static SortedBidiMap decorate(SortedBidiMap map) { public static <K, V> SortedBidiMap<K, V> decorate(SortedBidiMap<K, V> map) {
if (map instanceof Unmodifiable) { if (map instanceof Unmodifiable) {
return map; return map;
} }
return new UnmodifiableSortedBidiMap(map); return new UnmodifiableSortedBidiMap<K, V>(map);
} }
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
/** /**
* Constructor that wraps (not copies). * Constructor that wraps (not copies).
* *
* @param map the map to decorate, must not be null * @param map the map to decorate, must not be null
* @throws IllegalArgumentException if map is null * @throws IllegalArgumentException if map is null
*/ */
private UnmodifiableSortedBidiMap(SortedBidiMap map) { private UnmodifiableSortedBidiMap(SortedBidiMap<K, V> map) {
super(map); super(map);
} }
@ -81,77 +78,65 @@ public final class UnmodifiableSortedBidiMap
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public Object put(Object key, Object value) { public V put(K key, V value) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public void putAll(Map mapToCopy) { public void putAll(Map<? extends K, ? extends V> mapToCopy) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public Object remove(Object key) { public V remove(Object key) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public Set entrySet() { public Set<Map.Entry<K, V>> entrySet() {
Set set = super.entrySet(); Set<Map.Entry<K, V>> set = super.entrySet();
return UnmodifiableEntrySet.decorate(set); return UnmodifiableEntrySet.decorate(set);
} }
public Set keySet() { public Set<K> keySet() {
Set set = super.keySet(); Set<K> set = super.keySet();
return UnmodifiableSet.decorate(set); return UnmodifiableSet.decorate(set);
} }
public Collection values() { public Collection<V> values() {
Collection coll = super.values(); Collection<V> coll = super.values();
return UnmodifiableCollection.decorate(coll); return UnmodifiableCollection.decorate(coll);
} }
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
public Object removeValue(Object value) { public K removeValue(Object value) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public MapIterator mapIterator() {
return orderedMapIterator();
}
public BidiMap inverseBidiMap() {
return inverseSortedBidiMap();
}
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
public OrderedMapIterator orderedMapIterator() { public OrderedMapIterator<K, V> mapIterator() {
OrderedMapIterator it = getSortedBidiMap().orderedMapIterator(); OrderedMapIterator<K, V> it = decorated().mapIterator();
return UnmodifiableOrderedMapIterator.decorate(it); return UnmodifiableOrderedMapIterator.decorate(it);
} }
public OrderedBidiMap inverseOrderedBidiMap() {
return inverseSortedBidiMap();
}
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
public SortedBidiMap inverseSortedBidiMap() { public SortedBidiMap<V, K> inverseBidiMap() {
if (inverse == null) { if (inverse == null) {
inverse = new UnmodifiableSortedBidiMap(getSortedBidiMap().inverseSortedBidiMap()); inverse = new UnmodifiableSortedBidiMap<V, K>(decorated().inverseBidiMap());
inverse.inverse = this; inverse.inverse = this;
} }
return inverse; return inverse;
} }
public SortedMap subMap(Object fromKey, Object toKey) { public SortedMap<K, V> subMap(K fromKey, K toKey) {
SortedMap sm = getSortedBidiMap().subMap(fromKey, toKey); SortedMap<K, V> sm = decorated().subMap(fromKey, toKey);
return UnmodifiableSortedMap.decorate(sm); return UnmodifiableSortedMap.decorate(sm);
} }
public SortedMap headMap(Object toKey) { public SortedMap<K, V> headMap(K toKey) {
SortedMap sm = getSortedBidiMap().headMap(toKey); SortedMap<K, V> sm = decorated().headMap(toKey);
return UnmodifiableSortedMap.decorate(sm); return UnmodifiableSortedMap.decorate(sm);
} }
public SortedMap tailMap(Object fromKey) { public SortedMap<K, V> tailMap(K fromKey) {
SortedMap sm = getSortedBidiMap().tailMap(fromKey); SortedMap<K, V> sm = decorated().tailMap(fromKey);
return UnmodifiableSortedMap.decorate(sm); return UnmodifiableSortedMap.decorate(sm);
} }

View File

@ -35,7 +35,7 @@ import org.apache.commons.collections.BufferUnderflowException;
* The BoundedFifoBuffer is a very efficient implementation of * The BoundedFifoBuffer is a very efficient implementation of
* <code>Buffer</code> that is of a fixed size. * <code>Buffer</code> that is of a fixed size.
* <p> * <p>
* The removal order of a <code>BoundedFifoBuffer</code> is based on the * The removal order of a <code>BoundedFifoBuffer</code> is based on the
* insertion order; elements are removed in the same order in which they * insertion order; elements are removed in the same order in which they
* were added. The iteration order is the same as the removal order. * were added. The iteration order is the same as the removal order.
* <p> * <p>
@ -62,30 +62,30 @@ import org.apache.commons.collections.BufferUnderflowException;
* @author Stephen Colebourne * @author Stephen Colebourne
* @author Herve Quiroz * @author Herve Quiroz
*/ */
public class BoundedFifoBuffer extends AbstractCollection public class BoundedFifoBuffer<E> extends AbstractCollection<E>
implements Buffer, BoundedCollection, Serializable { implements Buffer<E>, BoundedCollection<E>, Serializable {
/** Serialization version */ /** Serialization version */
private static final long serialVersionUID = 5603722811189451017L; private static final long serialVersionUID = 5603722811189451017L;
/** Underlying storage array */ /** Underlying storage array */
private transient Object[] elements; private transient E[] elements;
/** Array index of first (oldest) buffer element */ /** Array index of first (oldest) buffer element */
private transient int start = 0; private transient int start = 0;
/** /**
* Index mod maxElements of the array position following the last buffer * Index mod maxElements of the array position following the last buffer
* element. Buffer elements start at elements[start] and "wrap around" * element. Buffer elements start at elements[start] and "wrap around"
* elements[maxElements-1], ending at elements[decrement(end)]. * elements[maxElements-1], ending at elements[decrement(end)].
* For example, elements = {c,a,b}, start=1, end=1 corresponds to * For example, elements = {c,a,b}, start=1, end=1 corresponds to
* the buffer [a,b,c]. * the buffer [a,b,c].
*/ */
private transient int end = 0; private transient int end = 0;
/** Flag to indicate if the buffer is currently full. */ /** Flag to indicate if the buffer is currently full. */
private transient boolean full = false; private transient boolean full = false;
/** Capacity of the buffer */ /** Capacity of the buffer */
private final int maxElements; private final int maxElements;
@ -104,11 +104,12 @@ public class BoundedFifoBuffer extends AbstractCollection
* @param size the maximum number of elements for this fifo * @param size the maximum number of elements for this fifo
* @throws IllegalArgumentException if the size is less than 1 * @throws IllegalArgumentException if the size is less than 1
*/ */
@SuppressWarnings("unchecked")
public BoundedFifoBuffer(int size) { public BoundedFifoBuffer(int size) {
if (size <= 0) { if (size <= 0) {
throw new IllegalArgumentException("The size must be greater than 0"); throw new IllegalArgumentException("The size must be greater than 0");
} }
elements = new Object[size]; elements = (E[]) new Object[size];
maxElements = elements.length; maxElements = elements.length;
} }
@ -120,7 +121,7 @@ public class BoundedFifoBuffer extends AbstractCollection
* @param coll the collection whose elements to add, may not be null * @param coll the collection whose elements to add, may not be null
* @throws NullPointerException if the collection is null * @throws NullPointerException if the collection is null
*/ */
public BoundedFifoBuffer(Collection coll) { public BoundedFifoBuffer(Collection<? extends E> coll) {
this(coll.size()); this(coll.size());
addAll(coll); addAll(coll);
} }
@ -128,31 +129,32 @@ public class BoundedFifoBuffer extends AbstractCollection
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
/** /**
* Write the buffer out using a custom routine. * Write the buffer out using a custom routine.
* *
* @param out the output stream * @param out the output stream
* @throws IOException * @throws IOException
*/ */
private void writeObject(ObjectOutputStream out) throws IOException { private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject(); out.defaultWriteObject();
out.writeInt(size()); out.writeInt(size());
for (Iterator it = iterator(); it.hasNext();) { for (Iterator<E> it = iterator(); it.hasNext();) {
out.writeObject(it.next()); out.writeObject(it.next());
} }
} }
/** /**
* Read the buffer in using a custom routine. * Read the buffer in using a custom routine.
* *
* @param in the input stream * @param in the input stream
* @throws IOException * @throws IOException
* @throws ClassNotFoundException * @throws ClassNotFoundException
*/ */
@SuppressWarnings("unchecked")
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject(); in.defaultReadObject();
elements = new Object[maxElements]; elements = (E[]) new Object[maxElements];
int size = in.readInt(); int size = in.readInt();
for (int i = 0; i < size; i++) { for (int i = 0; i < size; i++) {
elements[i] = in.readObject(); elements[i] = (E) in.readObject();
} }
start = 0; start = 0;
full = (size == maxElements); full = (size == maxElements);
@ -200,7 +202,7 @@ public class BoundedFifoBuffer extends AbstractCollection
public boolean isFull() { public boolean isFull() {
return size() == maxElements; return size() == maxElements;
} }
/** /**
* Gets the maximum size of the collection (the bound). * Gets the maximum size of the collection (the bound).
* *
@ -209,7 +211,7 @@ public class BoundedFifoBuffer extends AbstractCollection
public int maxSize() { public int maxSize() {
return maxElements; return maxElements;
} }
/** /**
* Clears this buffer. * Clears this buffer.
*/ */
@ -228,7 +230,7 @@ public class BoundedFifoBuffer extends AbstractCollection
* @throws NullPointerException if the given element is null * @throws NullPointerException if the given element is null
* @throws BufferOverflowException if this buffer is full * @throws BufferOverflowException if this buffer is full
*/ */
public boolean add(Object element) { public boolean add(E element) {
if (null == element) { if (null == element) {
throw new NullPointerException("Attempted to add null object to buffer"); throw new NullPointerException("Attempted to add null object to buffer");
} }
@ -256,11 +258,10 @@ public class BoundedFifoBuffer extends AbstractCollection
* @return the least recently inserted element * @return the least recently inserted element
* @throws BufferUnderflowException if the buffer is empty * @throws BufferUnderflowException if the buffer is empty
*/ */
public Object get() { public E get() {
if (isEmpty()) { if (isEmpty()) {
throw new BufferUnderflowException("The buffer is already empty"); throw new BufferUnderflowException("The buffer is already empty");
} }
return elements[start]; return elements[start];
} }
@ -270,12 +271,12 @@ public class BoundedFifoBuffer extends AbstractCollection
* @return the least recently inserted element * @return the least recently inserted element
* @throws BufferUnderflowException if the buffer is empty * @throws BufferUnderflowException if the buffer is empty
*/ */
public Object remove() { public E remove() {
if (isEmpty()) { if (isEmpty()) {
throw new BufferUnderflowException("The buffer is already empty"); throw new BufferUnderflowException("The buffer is already empty");
} }
Object element = elements[start]; E element = elements[start];
if (null != element) { if (null != element) {
elements[start++] = null; elements[start++] = null;
@ -283,21 +284,19 @@ public class BoundedFifoBuffer extends AbstractCollection
if (start >= maxElements) { if (start >= maxElements) {
start = 0; start = 0;
} }
full = false; full = false;
} }
return element; return element;
} }
/** /**
* Increments the internal index. * Increments the internal index.
* *
* @param index the index to increment * @param index the index to increment
* @return the updated index * @return the updated index
*/ */
private int increment(int index) { private int increment(int index) {
index++; index++;
if (index >= maxElements) { if (index >= maxElements) {
index = 0; index = 0;
} }
@ -306,7 +305,7 @@ public class BoundedFifoBuffer extends AbstractCollection
/** /**
* Decrements the internal index. * Decrements the internal index.
* *
* @param index the index to decrement * @param index the index to decrement
* @return the updated index * @return the updated index
*/ */
@ -323,8 +322,8 @@ public class BoundedFifoBuffer extends AbstractCollection
* *
* @return an iterator over this buffer's elements * @return an iterator over this buffer's elements
*/ */
public Iterator iterator() { public Iterator<E> iterator() {
return new Iterator() { return new Iterator<E>() {
private int index = start; private int index = start;
private int lastReturnedIndex = -1; private int lastReturnedIndex = -1;
@ -332,10 +331,9 @@ public class BoundedFifoBuffer extends AbstractCollection
public boolean hasNext() { public boolean hasNext() {
return isFirst || (index != end); return isFirst || (index != end);
} }
public Object next() { public E next() {
if (!hasNext()) { if (!hasNext()) {
throw new NoSuchElementException(); throw new NoSuchElementException();
} }

View File

@ -18,11 +18,11 @@ package org.apache.commons.collections.buffer;
import java.util.Collection; import java.util.Collection;
/** /**
* CircularFifoBuffer is a first in first out buffer with a fixed size that * CircularFifoBuffer is a first in first out buffer with a fixed size that
* replaces its oldest element if full. * replaces its oldest element if full.
* <p> * <p>
* The removal order of a <code>CircularFifoBuffer</code> is based on the * The removal order of a <code>CircularFifoBuffer</code> is based on the
* insertion order; elements are removed in the same order in which they * insertion order; elements are removed in the same order in which they
* were added. The iteration order is the same as the removal order. * were added. The iteration order is the same as the removal order.
* <p> * <p>
@ -46,7 +46,7 @@ import java.util.Collection;
* @author Stefano Fornari * @author Stefano Fornari
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public class CircularFifoBuffer extends BoundedFifoBuffer { public class CircularFifoBuffer<E> extends BoundedFifoBuffer<E> {
/** Serialization version */ /** Serialization version */
private static final long serialVersionUID = -8423413834657610406L; private static final long serialVersionUID = -8423413834657610406L;
@ -60,7 +60,7 @@ public class CircularFifoBuffer extends BoundedFifoBuffer {
/** /**
* Constructor that creates a buffer with the specified size. * Constructor that creates a buffer with the specified size.
* *
* @param size the size of the buffer (cannot be changed) * @param size the size of the buffer (cannot be changed)
* @throws IllegalArgumentException if the size is less than 1 * @throws IllegalArgumentException if the size is less than 1
*/ */
@ -71,11 +71,11 @@ public class CircularFifoBuffer extends BoundedFifoBuffer {
/** /**
* Constructor that creates a buffer from the specified collection. * Constructor that creates a buffer from the specified collection.
* The collection size also sets the buffer size * The collection size also sets the buffer size
* *
* @param coll the collection to copy into the buffer, may not be null * @param coll the collection to copy into the buffer, may not be null
* @throws NullPointerException if the collection is null * @throws NullPointerException if the collection is null
*/ */
public CircularFifoBuffer(Collection coll) { public CircularFifoBuffer(Collection<E> coll) {
super(coll); super(coll);
} }
@ -86,11 +86,11 @@ public class CircularFifoBuffer extends BoundedFifoBuffer {
* @param element the element to add * @param element the element to add
* @return true, always * @return true, always
*/ */
public boolean add(Object element) { public boolean add(E element) {
if (isFull()) { if (isFull()) {
remove(); remove();
} }
return super.add(element); return super.add(element);
} }
} }

View File

@ -24,6 +24,7 @@ import java.util.NoSuchElementException;
import org.apache.commons.collections.Buffer; import org.apache.commons.collections.Buffer;
import org.apache.commons.collections.BufferUnderflowException; import org.apache.commons.collections.BufferUnderflowException;
import org.apache.commons.collections.comparators.ComparableComparator;
/** /**
* Binary heap implementation of <code>Buffer</code> that provides for * Binary heap implementation of <code>Buffer</code> that provides for
@ -62,8 +63,7 @@ import org.apache.commons.collections.BufferUnderflowException;
* @author Stephen Colebourne * @author Stephen Colebourne
* @author Steve Phelps * @author Steve Phelps
*/ */
public class PriorityBuffer extends AbstractCollection public class PriorityBuffer<E> extends AbstractCollection<E> implements Buffer<E>, Serializable {
implements Buffer, Serializable {
/** Serialization lock. */ /** Serialization lock. */
private static final long serialVersionUID = 6891186490470027896L; private static final long serialVersionUID = 6891186490470027896L;
@ -76,21 +76,24 @@ public class PriorityBuffer extends AbstractCollection
/** /**
* The elements in this buffer. * The elements in this buffer.
*/ */
protected Object[] elements; protected E[] elements;
/** /**
* The number of elements currently in this buffer. * The number of elements currently in this buffer.
*/ */
protected int size; protected int size;
/** /**
* If true, the first element as determined by the sort order will * If true, the first element as determined by the sort order will
* be returned. If false, the last element as determined by the * be returned. If false, the last element as determined by the
* sort order will be returned. * sort order will be returned.
*/ */
protected boolean ascendingOrder; protected boolean ascendingOrder;
/** /**
* The comparator used to order the elements * The comparator used to order the elements
*/ */
protected Comparator comparator; protected Comparator<? super E> comparator;
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
/** /**
@ -108,7 +111,7 @@ public class PriorityBuffer extends AbstractCollection
* @param comparator the comparator used to order the elements, * @param comparator the comparator used to order the elements,
* null means use natural order * null means use natural order
*/ */
public PriorityBuffer(Comparator comparator) { public PriorityBuffer(Comparator<? super E> comparator) {
this(DEFAULT_CAPACITY, true, comparator); this(DEFAULT_CAPACITY, true, comparator);
} }
@ -131,7 +134,7 @@ public class PriorityBuffer extends AbstractCollection
* @param comparator the comparator used to order the elements, * @param comparator the comparator used to order the elements,
* null means use natural order * null means use natural order
*/ */
public PriorityBuffer(boolean ascendingOrder, Comparator comparator) { public PriorityBuffer(boolean ascendingOrder, Comparator<? super E> comparator) {
this(DEFAULT_CAPACITY, ascendingOrder, comparator); this(DEFAULT_CAPACITY, ascendingOrder, comparator);
} }
@ -155,7 +158,7 @@ public class PriorityBuffer extends AbstractCollection
* null means use natural order * null means use natural order
* @throws IllegalArgumentException if <code>capacity</code> is &lt;= <code>0</code> * @throws IllegalArgumentException if <code>capacity</code> is &lt;= <code>0</code>
*/ */
public PriorityBuffer(int capacity, Comparator comparator) { public PriorityBuffer(int capacity, Comparator<? super E> comparator) {
this(capacity, true, comparator); this(capacity, true, comparator);
} }
@ -183,7 +186,8 @@ public class PriorityBuffer extends AbstractCollection
* null means use natural order * null means use natural order
* @throws IllegalArgumentException if <code>capacity</code> is <code>&lt;= 0</code> * @throws IllegalArgumentException if <code>capacity</code> is <code>&lt;= 0</code>
*/ */
public PriorityBuffer(int capacity, boolean ascendingOrder, Comparator comparator) { @SuppressWarnings("unchecked")
public PriorityBuffer(int capacity, boolean ascendingOrder, Comparator<? super E> comparator) {
super(); super();
if (capacity <= 0) { if (capacity <= 0) {
throw new IllegalArgumentException("invalid capacity"); throw new IllegalArgumentException("invalid capacity");
@ -191,8 +195,8 @@ public class PriorityBuffer extends AbstractCollection
this.ascendingOrder = ascendingOrder; this.ascendingOrder = ascendingOrder;
//+1 as 0 is noop //+1 as 0 is noop
this.elements = new Object[capacity + 1]; this.elements = (E[]) new Object[capacity + 1];
this.comparator = comparator; this.comparator = (Comparator<? super E>) (comparator == null ? ComparableComparator.INSTANCE : comparator);
} }
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
@ -210,7 +214,7 @@ public class PriorityBuffer extends AbstractCollection
* *
* @return the comparator in use, null is natural order * @return the comparator in use, null is natural order
*/ */
public Comparator comparator() { public Comparator<? super E> comparator() {
return comparator; return comparator;
} }
@ -227,8 +231,9 @@ public class PriorityBuffer extends AbstractCollection
/** /**
* Clears all elements from the buffer. * Clears all elements from the buffer.
*/ */
@SuppressWarnings("unchecked")
public void clear() { public void clear() {
elements = new Object[elements.length]; // for gc elements = (E[]) new Object[elements.length]; // for gc
size = 0; size = 0;
} }
@ -240,11 +245,11 @@ public class PriorityBuffer extends AbstractCollection
* @param element the element to be added * @param element the element to be added
* @return true always * @return true always
*/ */
public boolean add(Object element) { public boolean add(E element) {
if (isAtCapacity()) { if (isAtCapacity()) {
grow(); grow();
} }
// percolate element to it's place in tree // percolate element to its place in tree
if (ascendingOrder) { if (ascendingOrder) {
percolateUpMinHeap(element); percolateUpMinHeap(element);
} else { } else {
@ -259,12 +264,11 @@ public class PriorityBuffer extends AbstractCollection
* @return the next element * @return the next element
* @throws BufferUnderflowException if the buffer is empty * @throws BufferUnderflowException if the buffer is empty
*/ */
public Object get() { public E get() {
if (isEmpty()) { if (isEmpty()) {
throw new BufferUnderflowException(); throw new BufferUnderflowException();
} else {
return elements[1];
} }
return elements[1];
} }
/** /**
@ -273,8 +277,8 @@ public class PriorityBuffer extends AbstractCollection
* @return the next element * @return the next element
* @throws BufferUnderflowException if the buffer is empty * @throws BufferUnderflowException if the buffer is empty
*/ */
public Object remove() { public E remove() {
final Object result = get(); final E result = get();
elements[1] = elements[size--]; elements[1] = elements[size--];
// set the unused element to 'null' so that the garbage collector // set the unused element to 'null' so that the garbage collector
@ -313,7 +317,7 @@ public class PriorityBuffer extends AbstractCollection
* @param index the index for the element * @param index the index for the element
*/ */
protected void percolateDownMinHeap(final int index) { protected void percolateDownMinHeap(final int index) {
final Object element = elements[index]; final E element = elements[index];
int hole = index; int hole = index;
while ((hole * 2) <= size) { while ((hole * 2) <= size) {
@ -345,7 +349,7 @@ public class PriorityBuffer extends AbstractCollection
* @param index the index of the element * @param index the index of the element
*/ */
protected void percolateDownMaxHeap(final int index) { protected void percolateDownMaxHeap(final int index) {
final Object element = elements[index]; final E element = elements[index];
int hole = index; int hole = index;
while ((hole * 2) <= size) { while ((hole * 2) <= size) {
@ -378,7 +382,7 @@ public class PriorityBuffer extends AbstractCollection
*/ */
protected void percolateUpMinHeap(final int index) { protected void percolateUpMinHeap(final int index) {
int hole = index; int hole = index;
Object element = elements[hole]; E element = elements[hole];
while (hole > 1 && compare(element, elements[hole / 2]) < 0) { while (hole > 1 && compare(element, elements[hole / 2]) < 0) {
// save element that is being pushed down // save element that is being pushed down
// as the element "bubble" is percolated up // as the element "bubble" is percolated up
@ -396,7 +400,7 @@ public class PriorityBuffer extends AbstractCollection
* *
* @param element the element * @param element the element
*/ */
protected void percolateUpMinHeap(final Object element) { protected void percolateUpMinHeap(final E element) {
elements[++size] = element; elements[++size] = element;
percolateUpMinHeap(size); percolateUpMinHeap(size);
} }
@ -410,7 +414,7 @@ public class PriorityBuffer extends AbstractCollection
*/ */
protected void percolateUpMaxHeap(final int index) { protected void percolateUpMaxHeap(final int index) {
int hole = index; int hole = index;
Object element = elements[hole]; E element = elements[hole];
while (hole > 1 && compare(element, elements[hole / 2]) > 0) { while (hole > 1 && compare(element, elements[hole / 2]) > 0) {
// save element that is being pushed down // save element that is being pushed down
@ -430,7 +434,7 @@ public class PriorityBuffer extends AbstractCollection
* *
* @param element the element * @param element the element
*/ */
protected void percolateUpMaxHeap(final Object element) { protected void percolateUpMaxHeap(final E element) {
elements[++size] = element; elements[++size] = element;
percolateUpMaxHeap(size); percolateUpMaxHeap(size);
} }
@ -443,19 +447,16 @@ public class PriorityBuffer extends AbstractCollection
* @param b the second object * @param b the second object
* @return -ve if a less than b, 0 if they are equal, +ve if a greater than b * @return -ve if a less than b, 0 if they are equal, +ve if a greater than b
*/ */
protected int compare(Object a, Object b) { protected int compare(E a, E b) {
if (comparator != null) { return comparator.compare(a, b);
return comparator.compare(a, b);
} else {
return ((Comparable) a).compareTo(b);
}
} }
/** /**
* Increases the size of the heap to support additional elements * Increases the size of the heap to support additional elements
*/ */
@SuppressWarnings("unchecked")
protected void grow() { protected void grow() {
final Object[] array = new Object[elements.length * 2]; final E[] array = (E[]) new Object[elements.length * 2];
System.arraycopy(elements, 0, array, 0, elements.length); System.arraycopy(elements, 0, array, 0, elements.length);
elements = array; elements = array;
} }
@ -466,8 +467,8 @@ public class PriorityBuffer extends AbstractCollection
* *
* @return an iterator over this heap's elements * @return an iterator over this heap's elements
*/ */
public Iterator iterator() { public Iterator<E> iterator() {
return new Iterator() { return new Iterator<E>() {
private int index = 1; private int index = 1;
private int lastReturnedIndex = -1; private int lastReturnedIndex = -1;
@ -476,7 +477,7 @@ public class PriorityBuffer extends AbstractCollection
return index <= size; return index <= size;
} }
public Object next() { public E next() {
if (!hasNext()) { if (!hasNext()) {
throw new NoSuchElementException(); throw new NoSuchElementException();
} }

View File

@ -35,7 +35,7 @@ import org.apache.commons.collections.collection.TransformedCollection;
* *
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public class TransformedBuffer extends TransformedCollection implements Buffer { public class TransformedBuffer<E> extends TransformedCollection<E> implements Buffer<E> {
/** Serialization version */ /** Serialization version */
private static final long serialVersionUID = -7901091318986132033L; private static final long serialVersionUID = -7901091318986132033L;
@ -52,8 +52,8 @@ public class TransformedBuffer extends TransformedCollection implements Buffer {
* @return a new transformed Buffer * @return a new transformed Buffer
* @throws IllegalArgumentException if buffer or transformer is null * @throws IllegalArgumentException if buffer or transformer is null
*/ */
public static Buffer decorate(Buffer buffer, Transformer transformer) { public static <E> Buffer<E> decorate(Buffer<E> buffer, Transformer<? super E, ? extends E> transformer) {
return new TransformedBuffer(buffer, transformer); return new TransformedBuffer<E>(buffer, transformer);
} }
/** /**
@ -70,13 +70,14 @@ public class TransformedBuffer extends TransformedCollection implements Buffer {
* @throws IllegalArgumentException if buffer or transformer is null * @throws IllegalArgumentException if buffer or transformer is null
* @since Commons Collections 3.3 * @since Commons Collections 3.3
*/ */
// TODO: Generics
public static Buffer decorateTransform(Buffer buffer, Transformer transformer) { public static Buffer decorateTransform(Buffer buffer, Transformer transformer) {
TransformedBuffer decorated = new TransformedBuffer(buffer, transformer); TransformedBuffer decorated = new TransformedBuffer(buffer, transformer);
if (transformer != null && buffer != null && buffer.size() > 0) { if (transformer != null && buffer != null && buffer.size() > 0) {
Object[] values = buffer.toArray(); Object[] values = buffer.toArray();
buffer.clear(); buffer.clear();
for(int i=0; i<values.length; i++) { for(int i=0; i<values.length; i++) {
decorated.getCollection().add(transformer.transform(values[i])); decorated.decorated().add(transformer.transform(values[i]));
} }
} }
return decorated; return decorated;
@ -93,7 +94,7 @@ public class TransformedBuffer extends TransformedCollection implements Buffer {
* @param transformer the transformer to use for conversion, must not be null * @param transformer the transformer to use for conversion, must not be null
* @throws IllegalArgumentException if buffer or transformer is null * @throws IllegalArgumentException if buffer or transformer is null
*/ */
protected TransformedBuffer(Buffer buffer, Transformer transformer) { protected TransformedBuffer(Buffer<E> buffer, Transformer<? super E, ? extends E> transformer) {
super(buffer, transformer); super(buffer, transformer);
} }
@ -102,16 +103,16 @@ public class TransformedBuffer extends TransformedCollection implements Buffer {
* *
* @return the decorated buffer * @return the decorated buffer
*/ */
protected Buffer getBuffer() { protected Buffer<E> getBuffer() {
return (Buffer) collection; return (Buffer<E>) collection;
} }
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
public Object get() { public E get() {
return getBuffer().get(); return getBuffer().get();
} }
public Object remove() { public E remove() {
return getBuffer().remove(); return getBuffer().remove();
} }

View File

@ -63,7 +63,7 @@ import org.apache.commons.collections.BufferUnderflowException;
* @author Thomas Knych * @author Thomas Knych
* @author Jordan Krey * @author Jordan Krey
*/ */
public class UnboundedFifoBuffer extends AbstractCollection implements Buffer, Serializable { public class UnboundedFifoBuffer<E> extends AbstractCollection<E> implements Buffer<E>, Serializable {
// invariant: buffer.length > size() // invariant: buffer.length > size()
// ie.buffer always has at least one empty entry // ie.buffer always has at least one empty entry
@ -71,9 +71,11 @@ public class UnboundedFifoBuffer extends AbstractCollection implements Buffer, S
private static final long serialVersionUID = -3482960336579541419L; private static final long serialVersionUID = -3482960336579541419L;
/** The array of objects in the buffer. */ /** The array of objects in the buffer. */
protected transient Object[] buffer; protected transient E[] buffer;
/** The current head index. */ /** The current head index. */
protected transient int head; protected transient int head;
/** The current tail index. */ /** The current tail index. */
protected transient int tail; protected transient int tail;
@ -92,15 +94,16 @@ public class UnboundedFifoBuffer extends AbstractCollection implements Buffer, S
/** /**
* Constructs an UnboundedFifoBuffer with the specified number of elements. * Constructs an UnboundedFifoBuffer with the specified number of elements.
* The integer must be a positive integer. * The integer must be a positive integer.
* *
* @param initialSize the initial size of the buffer * @param initialSize the initial size of the buffer
* @throws IllegalArgumentException if the size is less than 1 * @throws IllegalArgumentException if the size is less than 1
*/ */
@SuppressWarnings("unchecked")
public UnboundedFifoBuffer(int initialSize) { public UnboundedFifoBuffer(int initialSize) {
if (initialSize <= 0) { if (initialSize <= 0) {
throw new IllegalArgumentException("The size must be greater than 0"); throw new IllegalArgumentException("The size must be greater than 0");
} }
buffer = new Object[initialSize + 1]; buffer = (E[]) new Object[initialSize + 1];
head = 0; head = 0;
tail = 0; tail = 0;
} }
@ -108,7 +111,7 @@ public class UnboundedFifoBuffer extends AbstractCollection implements Buffer, S
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
/** /**
* Write the buffer out using a custom routine. * Write the buffer out using a custom routine.
* *
* @param out the output stream * @param out the output stream
* @throws IOException * @throws IOException
*/ */
@ -116,25 +119,26 @@ public class UnboundedFifoBuffer extends AbstractCollection implements Buffer, S
out.defaultWriteObject(); out.defaultWriteObject();
out.writeInt(size()); out.writeInt(size());
out.writeInt(buffer.length); out.writeInt(buffer.length);
for (Iterator it = iterator(); it.hasNext();) { for (Iterator<E> it = iterator(); it.hasNext();) {
out.writeObject(it.next()); out.writeObject(it.next());
} }
} }
/** /**
* Read the buffer in using a custom routine. * Read the buffer in using a custom routine.
* *
* @param in the input stream * @param in the input stream
* @throws IOException * @throws IOException
* @throws ClassNotFoundException * @throws ClassNotFoundException
*/ */
@SuppressWarnings("unchecked")
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject(); in.defaultReadObject();
int size = in.readInt(); int size = in.readInt();
int length = in.readInt(); int length = in.readInt();
buffer = new Object[length]; buffer = (E[]) new Object[length];
for (int i = 0; i < size; i++) { for (int i = 0; i < size; i++) {
buffer[i] = in.readObject(); buffer[i] = (E) in.readObject();
} }
head = 0; head = 0;
tail = size; tail = size;
@ -174,14 +178,15 @@ public class UnboundedFifoBuffer extends AbstractCollection implements Buffer, S
* @return true, always * @return true, always
* @throws NullPointerException if the given element is null * @throws NullPointerException if the given element is null
*/ */
public boolean add(final Object obj) { @SuppressWarnings("unchecked")
public boolean add(final E obj) {
if (obj == null) { if (obj == null) {
throw new NullPointerException("Attempted to add null object to buffer"); throw new NullPointerException("Attempted to add null object to buffer");
} }
if (size() + 1 >= buffer.length) { if (size() + 1 >= buffer.length) {
// copy contents to a new buffer array // copy contents to a new buffer array
Object[] tmp = new Object[((buffer.length - 1) * 2) + 1]; E[] tmp = (E[]) new Object[((buffer.length - 1) * 2) + 1];
int j = 0; int j = 0;
// move head to element zero in the new array // move head to element zero in the new array
for (int i = head; i != tail;) { for (int i = head; i != tail;) {
@ -207,7 +212,7 @@ public class UnboundedFifoBuffer extends AbstractCollection implements Buffer, S
* @return the next object in the buffer * @return the next object in the buffer
* @throws BufferUnderflowException if this buffer is empty * @throws BufferUnderflowException if this buffer is empty
*/ */
public Object get() { public E get() {
if (isEmpty()) { if (isEmpty()) {
throw new BufferUnderflowException("The buffer is already empty"); throw new BufferUnderflowException("The buffer is already empty");
} }
@ -221,12 +226,12 @@ public class UnboundedFifoBuffer extends AbstractCollection implements Buffer, S
* @return the removed object * @return the removed object
* @throws BufferUnderflowException if this buffer is empty * @throws BufferUnderflowException if this buffer is empty
*/ */
public Object remove() { public E remove() {
if (isEmpty()) { if (isEmpty()) {
throw new BufferUnderflowException("The buffer is already empty"); throw new BufferUnderflowException("The buffer is already empty");
} }
Object element = buffer[head]; E element = buffer[head];
if (element != null) { if (element != null) {
buffer[head] = null; buffer[head] = null;
head = increment(head); head = increment(head);
@ -236,7 +241,7 @@ public class UnboundedFifoBuffer extends AbstractCollection implements Buffer, S
/** /**
* Increments the internal index. * Increments the internal index.
* *
* @param index the index to increment * @param index the index to increment
* @return the updated index * @return the updated index
*/ */
@ -250,7 +255,7 @@ public class UnboundedFifoBuffer extends AbstractCollection implements Buffer, S
/** /**
* Decrements the internal index. * Decrements the internal index.
* *
* @param index the index to decrement * @param index the index to decrement
* @return the updated index * @return the updated index
*/ */
@ -267,8 +272,8 @@ public class UnboundedFifoBuffer extends AbstractCollection implements Buffer, S
* *
* @return an iterator over this buffer's elements * @return an iterator over this buffer's elements
*/ */
public Iterator iterator() { public Iterator<E> iterator() {
return new Iterator() { return new Iterator<E>() {
private int index = head; private int index = head;
private int lastReturnedIndex = -1; private int lastReturnedIndex = -1;
@ -278,7 +283,7 @@ public class UnboundedFifoBuffer extends AbstractCollection implements Buffer, S
} }
public Object next() { public E next() {
if (!hasNext()) { if (!hasNext()) {
throw new NoSuchElementException(); throw new NoSuchElementException();
} }

View File

@ -0,0 +1,125 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.collections.collection;
import java.io.Serializable;
import java.util.Collection;
/**
* Decorates another <code>Collection</code> to provide additional behaviour
* without guaranteeing that the provided <code>Collection</code> type is the
* same as that of the decorated <code>Collection</code>.
* <p>
* Each untyped method call made on this <code>Collection</code> is forwarded to the
* decorated <code>Collection</code>. This class is used as a framework on which
* to build to extensions such as synchronized and unmodifiable behaviour. The
* main advantage of decoration is that one decorator can wrap any
* implementation of <code>Collection</code>, whereas sub-classing requires a
* new class to be written for each implementation.
* <p>
* This implementation does not perform any special processing with
* {@link #iterator()}. Instead it simply returns the value from the wrapped
* collection. This may be undesirable, for example if you are trying to write
* an unmodifiable implementation it might provide a loophole.
*
* @param <D> the type of the elements in the decorated collection
* @param <E> the element type of the Collection implementation
* @since Commons Collections 5
* @version $Revision$ $Date$
*
* @author Stephen Colebourne
* @author Paul Jack
* @author Matt Benson
*/
public abstract class AbstractUntypedCollectionDecorator<E, D> implements Collection<E>, Serializable {
/** Serialization version */
private static final long serialVersionUID = -8016691444524268856L;
/** The collection being decorated */
protected Collection<D> collection;
/**
* Create a new AbstractUntypedCollectionDecorator.
*/
public AbstractUntypedCollectionDecorator() {
super();
}
/**
* Gets the collection being decorated. All access to the decorated
* collection goes via this method.
*
* @return the decorated collection
*/
protected Collection<D> decorated() {
return collection;
}
public void clear() {
decorated().clear();
}
public boolean contains(Object object) {
return decorated().contains(object);
}
public boolean isEmpty() {
return decorated().isEmpty();
}
public boolean remove(Object object) {
return decorated().remove(object);
}
public int size() {
return decorated().size();
}
public Object[] toArray() {
return decorated().toArray();
}
public <T> T[] toArray(T[] object) {
return decorated().toArray(object);
}
public boolean containsAll(Collection<?> coll) {
return decorated().containsAll(coll);
}
public boolean removeAll(Collection<?> coll) {
return decorated().removeAll(coll);
}
public boolean retainAll(Collection<?> coll) {
return decorated().retainAll(coll);
}
public boolean equals(Object object) {
return object == this || decorated().equals(object);
}
public int hashCode() {
return decorated().hashCode();
}
public String toString() {
return decorated().toString();
}
}

View File

@ -32,7 +32,7 @@ import java.util.Comparator;
* *
* @author Rodney Waldhoff * @author Rodney Waldhoff
*/ */
public final class BooleanComparator implements Comparator, Serializable { public final class BooleanComparator implements Comparator<Boolean>, Serializable {
/** Serialization version. */ /** Serialization version. */
private static final long serialVersionUID = 1830042991606340609L; private static final long serialVersionUID = 1830042991606340609L;
@ -126,22 +126,6 @@ public final class BooleanComparator implements Comparator, Serializable {
} }
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
/**
* Compares two arbitrary Objects.
* When both arguments are <code>Boolean</code>, this method is equivalent to
* {@link #compare(Boolean,Boolean) compare((Boolean)<i>obj1</i>,(Boolean)<i>obj2</i>)}.
* When either argument is not a <code>Boolean</code>, this methods throws
* a {@link ClassCastException}.
*
* @param obj1 the first object to compare
* @param obj2 the second object to compare
* @return negative if obj1 is less, positive if greater, zero if equal
* @throws ClassCastException when either argument is not <code>Boolean</code>
*/
public int compare(Object obj1, Object obj2) {
return compare((Boolean)obj1, (Boolean)obj2);
}
/** /**
* Compares two non-<code>null</code> <code>Boolean</code> objects * Compares two non-<code>null</code> <code>Boolean</code> objects
* according to the value of {@link #sortsTrueFirst()}. * according to the value of {@link #sortsTrueFirst()}.

View File

@ -40,13 +40,14 @@ import java.util.Comparator;
* *
* @see java.util.Collections#reverseOrder() * @see java.util.Collections#reverseOrder()
*/ */
public class ComparableComparator implements Comparator, Serializable { public class ComparableComparator<E extends Comparable<? super E>> implements Comparator<E>, Serializable {
/** Serialization version. */ /** Serialization version. */
private static final long serialVersionUID=-291439688585137865L; private static final long serialVersionUID=-291439688585137865L;
/** The singleton instance. */ /** The singleton instance. */
private static final ComparableComparator instance = new ComparableComparator(); @SuppressWarnings("unchecked")
public static final ComparableComparator<?> INSTANCE = new ComparableComparator();
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
/** /**
@ -58,8 +59,9 @@ public class ComparableComparator implements Comparator, Serializable {
* *
* @return the singleton ComparableComparator * @return the singleton ComparableComparator
*/ */
public static ComparableComparator getInstance() { @SuppressWarnings("unchecked")
return instance; public static <E extends Comparable<? super E>> ComparableComparator<E> getInstance() {
return (ComparableComparator<E>) INSTANCE;
} }
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
@ -86,8 +88,8 @@ public class ComparableComparator implements Comparator, Serializable {
* @throws ClassCastException when <i>obj1</i> is not a <code>Comparable</code>, * @throws ClassCastException when <i>obj1</i> is not a <code>Comparable</code>,
* or when <code>((Comparable)obj1).compareTo(obj2)</code> does * or when <code>((Comparable)obj1).compareTo(obj2)</code> does
*/ */
public int compare(Object obj1, Object obj2) { public int compare(E obj1, E obj2) {
return ((Comparable)obj1).compareTo(obj2); return obj1.compareTo(obj2);
} }
//----------------------------------------------------------------------- //-----------------------------------------------------------------------

View File

@ -54,13 +54,13 @@ import java.util.List;
* @author Morgan Delagrange * @author Morgan Delagrange
* @version $Revision$ $Date$ * @version $Revision$ $Date$
*/ */
public class ComparatorChain implements Comparator, Serializable { public class ComparatorChain<E> implements Comparator<E>, Serializable {
/** Serialization version from Collections 2.0. */ /** Serialization version from Collections 2.0. */
private static final long serialVersionUID = -721644942746081630L; private static final long serialVersionUID = -721644942746081630L;
/** The list of comparators in the chain. */ /** The list of comparators in the chain. */
protected List comparatorChain = null; protected List<Comparator<E>> comparatorChain = null;
/** Order - false (clear) = ascend; true (set) = descend. */ /** Order - false (clear) = ascend; true (set) = descend. */
protected BitSet orderingBits = null; protected BitSet orderingBits = null;
/** Whether the chain has been "locked". */ /** Whether the chain has been "locked". */
@ -70,32 +70,32 @@ public class ComparatorChain implements Comparator, Serializable {
/** /**
* Construct a ComparatorChain with no Comparators. * Construct a ComparatorChain with no Comparators.
* You must add at least one Comparator before calling * You must add at least one Comparator before calling
* the compare(Object,Object) method, or an * the compare(Object,Object) method, or an
* UnsupportedOperationException is thrown * UnsupportedOperationException is thrown
*/ */
public ComparatorChain() { public ComparatorChain() {
this(new ArrayList(),new BitSet()); this(new ArrayList<Comparator<E>>(), new BitSet());
} }
/** /**
* Construct a ComparatorChain with a single Comparator, * Construct a ComparatorChain with a single Comparator,
* sorting in the forward order * sorting in the forward order
* *
* @param comparator First comparator in the Comparator chain * @param comparator First comparator in the Comparator chain
*/ */
public ComparatorChain(Comparator comparator) { public ComparatorChain(Comparator<E> comparator) {
this(comparator,false); this(comparator, false);
} }
/** /**
* Construct a Comparator chain with a single Comparator, * Construct a Comparator chain with a single Comparator,
* sorting in the given order * sorting in the given order
* *
* @param comparator First Comparator in the ComparatorChain * @param comparator First Comparator in the ComparatorChain
* @param reverse false = forward sort; true = reverse sort * @param reverse false = forward sort; true = reverse sort
*/ */
public ComparatorChain(Comparator comparator, boolean reverse) { public ComparatorChain(Comparator<E> comparator, boolean reverse) {
comparatorChain = new ArrayList(); comparatorChain = new ArrayList<Comparator<E>>();
comparatorChain.add(comparator); comparatorChain.add(comparator);
orderingBits = new BitSet(1); orderingBits = new BitSet(1);
if (reverse == true) { if (reverse == true) {
@ -105,14 +105,14 @@ public class ComparatorChain implements Comparator, Serializable {
/** /**
* Construct a ComparatorChain from the Comparators in the * Construct a ComparatorChain from the Comparators in the
* List. All Comparators will default to the forward * List. All Comparators will default to the forward
* sort order. * sort order.
* *
* @param list List of Comparators * @param list List of Comparators
* @see #ComparatorChain(List,BitSet) * @see #ComparatorChain(List,BitSet)
*/ */
public ComparatorChain(List list) { public ComparatorChain(List<Comparator<E>> list) {
this(list,new BitSet(list.size())); this(list, new BitSet(list.size()));
} }
/** /**
@ -124,13 +124,13 @@ public class ComparatorChain implements Comparator, Serializable {
* If that method returns <i>false</i>, the forward * If that method returns <i>false</i>, the forward
* sort order is used; a return value of <i>true</i> * sort order is used; a return value of <i>true</i>
* indicates reverse sort order. * indicates reverse sort order.
* *
* @param list List of Comparators. NOTE: This constructor does not perform a * @param list List of Comparators. NOTE: This constructor does not perform a
* defensive copy of the list * defensive copy of the list
* @param bits Sort order for each Comparator. Extra bits are ignored, * @param bits Sort order for each Comparator. Extra bits are ignored,
* unless extra Comparators are added by another method. * unless extra Comparators are added by another method.
*/ */
public ComparatorChain(List list, BitSet bits) { public ComparatorChain(List<Comparator<E>> list, BitSet bits) {
comparatorChain = list; comparatorChain = list;
orderingBits = bits; orderingBits = bits;
} }
@ -139,23 +139,23 @@ public class ComparatorChain implements Comparator, Serializable {
/** /**
* Add a Comparator to the end of the chain using the * Add a Comparator to the end of the chain using the
* forward sort order * forward sort order
* *
* @param comparator Comparator with the forward sort order * @param comparator Comparator with the forward sort order
*/ */
public void addComparator(Comparator comparator) { public void addComparator(Comparator<E> comparator) {
addComparator(comparator,false); addComparator(comparator, false);
} }
/** /**
* Add a Comparator to the end of the chain using the * Add a Comparator to the end of the chain using the
* given sort order * given sort order
* *
* @param comparator Comparator to add to the end of the chain * @param comparator Comparator to add to the end of the chain
* @param reverse false = forward sort order; true = reverse sort order * @param reverse false = forward sort order; true = reverse sort order
*/ */
public void addComparator(Comparator comparator, boolean reverse) { public void addComparator(Comparator<E> comparator, boolean reverse) {
checkLocked(); checkLocked();
comparatorChain.add(comparator); comparatorChain.add(comparator);
if (reverse == true) { if (reverse == true) {
orderingBits.set(comparatorChain.size() - 1); orderingBits.set(comparatorChain.size() - 1);
@ -165,26 +165,25 @@ public class ComparatorChain implements Comparator, Serializable {
/** /**
* Replace the Comparator at the given index, maintaining * Replace the Comparator at the given index, maintaining
* the existing sort order. * the existing sort order.
* *
* @param index index of the Comparator to replace * @param index index of the Comparator to replace
* @param comparator Comparator to place at the given index * @param comparator Comparator to place at the given index
* @exception IndexOutOfBoundsException * @exception IndexOutOfBoundsException
* if index &lt; 0 or index &gt;= size() * if index &lt; 0 or index &gt;= size()
*/ */
public void setComparator(int index, Comparator comparator) public void setComparator(int index, Comparator<E> comparator) throws IndexOutOfBoundsException {
throws IndexOutOfBoundsException { setComparator(index, comparator, false);
setComparator(index,comparator,false);
} }
/** /**
* Replace the Comparator at the given index in the * Replace the Comparator at the given index in the
* ComparatorChain, using the given sort order * ComparatorChain, using the given sort order
* *
* @param index index of the Comparator to replace * @param index index of the Comparator to replace
* @param comparator Comparator to set * @param comparator Comparator to set
* @param reverse false = forward sort order; true = reverse sort order * @param reverse false = forward sort order; true = reverse sort order
*/ */
public void setComparator(int index, Comparator comparator, boolean reverse) { public void setComparator(int index, Comparator<E> comparator, boolean reverse) {
checkLocked(); checkLocked();
comparatorChain.set(index,comparator); comparatorChain.set(index,comparator);
@ -195,11 +194,10 @@ public class ComparatorChain implements Comparator, Serializable {
} }
} }
/** /**
* Change the sort order at the given index in the * Change the sort order at the given index in the
* ComparatorChain to a forward sort. * ComparatorChain to a forward sort.
* *
* @param index Index of the ComparatorChain * @param index Index of the ComparatorChain
*/ */
public void setForwardSort(int index) { public void setForwardSort(int index) {
@ -210,7 +208,7 @@ public class ComparatorChain implements Comparator, Serializable {
/** /**
* Change the sort order at the given index in the * Change the sort order at the given index in the
* ComparatorChain to a reverse sort. * ComparatorChain to a reverse sort.
* *
* @param index Index of the ComparatorChain * @param index Index of the ComparatorChain
*/ */
public void setReverseSort(int index) { public void setReverseSort(int index) {
@ -220,7 +218,7 @@ public class ComparatorChain implements Comparator, Serializable {
/** /**
* Number of Comparators in the current ComparatorChain. * Number of Comparators in the current ComparatorChain.
* *
* @return Comparator count * @return Comparator count
*/ */
public int size() { public int size() {
@ -231,8 +229,8 @@ public class ComparatorChain implements Comparator, Serializable {
* Determine if modifications can still be made to the * Determine if modifications can still be made to the
* ComparatorChain. ComparatorChains cannot be modified * ComparatorChain. ComparatorChains cannot be modified
* once they have performed a comparison. * once they have performed a comparison.
* *
* @return true = ComparatorChain cannot be modified; false = * @return true = ComparatorChain cannot be modified; false =
* ComparatorChain can still be modified. * ComparatorChain can still be modified.
*/ */
public boolean isLocked() { public boolean isLocked() {
@ -256,7 +254,7 @@ public class ComparatorChain implements Comparator, Serializable {
/** /**
* Perform comparisons on the Objects as per * Perform comparisons on the Objects as per
* Comparator.compare(o1,o2). * Comparator.compare(o1,o2).
* *
* @param o1 the first object to compare * @param o1 the first object to compare
* @param o2 the second object to compare * @param o2 the second object to compare
* @return -1, 0, or 1 * @return -1, 0, or 1
@ -264,31 +262,29 @@ public class ComparatorChain implements Comparator, Serializable {
* if the ComparatorChain does not contain at least one * if the ComparatorChain does not contain at least one
* Comparator * Comparator
*/ */
public int compare(Object o1, Object o2) throws UnsupportedOperationException { public int compare(E o1, E o2) throws UnsupportedOperationException {
if (isLocked == false) { if (isLocked == false) {
checkChainIntegrity(); checkChainIntegrity();
isLocked = true; isLocked = true;
} }
// iterate over all comparators in the chain // iterate over all comparators in the chain
Iterator comparators = comparatorChain.iterator(); Iterator<Comparator<E>> comparators = comparatorChain.iterator();
for (int comparatorIndex = 0; comparators.hasNext(); ++comparatorIndex) { for (int comparatorIndex = 0; comparators.hasNext(); ++comparatorIndex) {
Comparator comparator = (Comparator) comparators.next(); Comparator<E> comparator = comparators.next();
int retval = comparator.compare(o1,o2); int retval = comparator.compare(o1,o2);
if (retval != 0) { if (retval != 0) {
// invert the order if it is a reverse sort // invert the order if it is a reverse sort
if (orderingBits.get(comparatorIndex) == true) { if (orderingBits.get(comparatorIndex) == true) {
if(Integer.MIN_VALUE == retval) { if(Integer.MIN_VALUE == retval) {
retval = Integer.MAX_VALUE; retval = Integer.MAX_VALUE;
} else { } else {
retval *= -1; retval *= -1;
} }
} }
return retval; return retval;
} }
} }
// if comparators are exhausted, return 0 // if comparators are exhausted, return 0
@ -299,49 +295,51 @@ public class ComparatorChain implements Comparator, Serializable {
/** /**
* Implement a hash code for this comparator that is consistent with * Implement a hash code for this comparator that is consistent with
* {@link #equals(Object) equals}. * {@link #equals(Object) equals}.
* *
* @return a suitable hash code * @return a suitable hash code
* @since Commons Collections 3.0 * @since Commons Collections 3.0
*/ */
public int hashCode() { public int hashCode() {
int hash = 0; int hash = 0;
if(null != comparatorChain) { if (null != comparatorChain) {
hash ^= comparatorChain.hashCode(); hash ^= comparatorChain.hashCode();
} }
if(null != orderingBits) { if (null != orderingBits) {
hash ^= orderingBits.hashCode(); hash ^= orderingBits.hashCode();
} }
return hash; return hash;
} }
/** /**
* Returns <code>true</code> iff <i>that</i> Object is * Returns <code>true</code> iff <i>that</i> Object is
* is a {@link Comparator} whose ordering is known to be * is a {@link Comparator} whose ordering is known to be
* equivalent to mine. * equivalent to mine.
* <p> * <p>
* This implementation returns <code>true</code> * This implementation returns <code>true</code>
* iff <code><i>object</i>.{@link Object#getClass() getClass()}</code> * iff <code><i>object</i>.{@link Object#getClass() getClass()}</code>
* equals <code>this.getClass()</code>, and the underlying * equals <code>this.getClass()</code>, and the underlying
* comparators and order bits are equal. * comparators and order bits are equal.
* Subclasses may want to override this behavior to remain consistent * Subclasses may want to override this behavior to remain consistent
* with the {@link Comparator#equals(Object)} contract. * with the {@link Comparator#equals(Object)} contract.
* *
* @param object the object to compare with * @param object the object to compare with
* @return true if equal * @return true if equal
* @since Commons Collections 3.0 * @since Commons Collections 3.0
*/ */
public boolean equals(Object object) { public boolean equals(Object object) {
if(this == object) { if (this == object) {
return true; return true;
} else if(null == object) { }
return false; if (null == object) {
} else if(object.getClass().equals(this.getClass())) {
ComparatorChain chain = (ComparatorChain)object;
return ( (null == orderingBits ? null == chain.orderingBits : orderingBits.equals(chain.orderingBits))
&& (null == comparatorChain ? null == chain.comparatorChain : comparatorChain.equals(chain.comparatorChain)) );
} else {
return false; return false;
} }
if (object.getClass().equals(this.getClass())) {
ComparatorChain<?> chain = (ComparatorChain<?>) object;
return ((null == orderingBits ? null == chain.orderingBits : orderingBits
.equals(chain.orderingBits)) && (null == comparatorChain ? null == chain.comparatorChain
: comparatorChain.equals(chain.comparatorChain)));
}
return false;
} }
} }

View File

@ -18,11 +18,10 @@ package org.apache.commons.collections.comparators;
import java.util.Comparator; import java.util.Comparator;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
/** /**
* A Comparator which imposes a specific order on a specific set of Objects. * A Comparator which imposes a specific order on a specific set of Objects.
* Objects are presented to the FixedOrderComparator in a specified order and * Objects are presented to the FixedOrderComparator in a specified order and
* subsequent calls to {@link #compare(Object, Object) compare} yield that order. * subsequent calls to {@link #compare(Object, Object) compare} yield that order.
@ -48,55 +47,47 @@ import java.util.Map;
* @author Stephen Colebourne * @author Stephen Colebourne
* @author Janek Bogucki * @author Janek Bogucki
*/ */
public class FixedOrderComparator implements Comparator { public class FixedOrderComparator<T> implements Comparator<T> {
/** /**
* Behavior when comparing unknown Objects: * Unknown object behavior enum.
* unknown objects compare as before known Objects. * @since Commons Collections 5
*/ */
public static final int UNKNOWN_BEFORE = 0; public static enum UnknownObjectBehavior {
BEFORE, AFTER, EXCEPTION;
/** }
* Behavior when comparing unknown Objects:
* unknown objects compare as after known Objects.
*/
public static final int UNKNOWN_AFTER = 1;
/**
* Behavior when comparing unknown Objects:
* unknown objects cause a IllegalArgumentException to be thrown.
* This is the default behavior.
*/
public static final int UNKNOWN_THROW_EXCEPTION = 2;
/** Internal map of object to position */ /** Internal map of object to position */
private final Map map = new HashMap(); private final Map<T, Integer> map = new HashMap<T, Integer>();
/** Counter used in determining the position in the map */ /** Counter used in determining the position in the map */
private int counter = 0; private int counter = 0;
/** Is the comparator locked against further change */ /** Is the comparator locked against further change */
private boolean isLocked = false; private boolean isLocked = false;
/** The behaviour in the case of an unknown object */ /** The behaviour in the case of an unknown object */
private int unknownObjectBehavior = UNKNOWN_THROW_EXCEPTION; private UnknownObjectBehavior unknownObjectBehavior = UnknownObjectBehavior.EXCEPTION;
// Constructors // Constructors
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
/** /**
* Constructs an empty FixedOrderComparator. * Constructs an empty FixedOrderComparator.
*/ */
public FixedOrderComparator() { public FixedOrderComparator() {
super(); super();
} }
/** /**
* Constructs a FixedOrderComparator which uses the order of the given array * Constructs a FixedOrderComparator which uses the order of the given array
* to compare the objects. * to compare the objects.
* <p> * <p>
* The array is copied, so later changes will not affect the comparator. * The array is copied, so later changes will not affect the comparator.
* *
* @param items the items that the comparator can compare in order * @param items the items that the comparator can compare in order
* @throws IllegalArgumentException if the array is null * @throws IllegalArgumentException if the array is null
*/ */
public FixedOrderComparator(Object[] items) { public FixedOrderComparator(T[] items) {
super(); super();
if (items == null) { if (items == null) {
throw new IllegalArgumentException("The list of items must not be null"); throw new IllegalArgumentException("The list of items must not be null");
@ -106,22 +97,22 @@ public class FixedOrderComparator implements Comparator {
} }
} }
/** /**
* Constructs a FixedOrderComparator which uses the order of the given list * Constructs a FixedOrderComparator which uses the order of the given list
* to compare the objects. * to compare the objects.
* <p> * <p>
* The list is copied, so later changes will not affect the comparator. * The list is copied, so later changes will not affect the comparator.
* *
* @param items the items that the comparator can compare in order * @param items the items that the comparator can compare in order
* @throws IllegalArgumentException if the list is null * @throws IllegalArgumentException if the list is null
*/ */
public FixedOrderComparator(List items) { public FixedOrderComparator(List<T> items) {
super(); super();
if (items == null) { if (items == null) {
throw new IllegalArgumentException("The list of items must not be null"); throw new IllegalArgumentException("The list of items must not be null");
} }
for (Iterator it = items.iterator(); it.hasNext();) { for (T t : items) {
add(it.next()); add(t);
} }
} }
@ -130,7 +121,7 @@ public class FixedOrderComparator implements Comparator {
/** /**
* Returns true if modifications cannot be made to the FixedOrderComparator. * Returns true if modifications cannot be made to the FixedOrderComparator.
* FixedOrderComparators cannot be modified once they have performed a comparison. * FixedOrderComparators cannot be modified once they have performed a comparison.
* *
* @return true if attempts to change the FixedOrderComparator yield an * @return true if attempts to change the FixedOrderComparator yield an
* UnsupportedOperationException, false if it can be changed. * UnsupportedOperationException, false if it can be changed.
*/ */
@ -140,7 +131,7 @@ public class FixedOrderComparator implements Comparator {
/** /**
* Checks to see whether the comparator is now locked against further changes. * Checks to see whether the comparator is now locked against further changes.
* *
* @throws UnsupportedOperationException if the comparator is locked * @throws UnsupportedOperationException if the comparator is locked
*/ */
protected void checkLocked() { protected void checkLocked() {
@ -149,118 +140,108 @@ public class FixedOrderComparator implements Comparator {
} }
} }
/** /**
* Gets the behavior for comparing unknown objects. * Gets the behavior for comparing unknown objects.
* *
* @return the flag for unknown behaviour - UNKNOWN_AFTER, * @return {@link UnknownObjectBehavior}
* UNKNOWN_BEFORE or UNKNOWN_THROW_EXCEPTION
*/ */
public int getUnknownObjectBehavior() { public UnknownObjectBehavior getUnknownObjectBehavior() {
return unknownObjectBehavior; return unknownObjectBehavior;
} }
/** /**
* Sets the behavior for comparing unknown objects. * Sets the behavior for comparing unknown objects.
* *
* @param unknownObjectBehavior the flag for unknown behaviour - * @param unknownObjectBehavior the flag for unknown behaviour -
* UNKNOWN_AFTER, UNKNOWN_BEFORE or UNKNOWN_THROW_EXCEPTION * UNKNOWN_AFTER, UNKNOWN_BEFORE or UNKNOWN_THROW_EXCEPTION
* @throws UnsupportedOperationException if a comparison has been performed * @throws UnsupportedOperationException if a comparison has been performed
* @throws IllegalArgumentException if the unknown flag is not valid * @throws IllegalArgumentException if the unknown flag is not valid
*/ */
public void setUnknownObjectBehavior(int unknownObjectBehavior) { public void setUnknownObjectBehavior(UnknownObjectBehavior unknownObjectBehavior) {
checkLocked(); checkLocked();
if (unknownObjectBehavior != UNKNOWN_AFTER if (unknownObjectBehavior == null) {
&& unknownObjectBehavior != UNKNOWN_BEFORE throw new IllegalArgumentException("Unknown object behavior must not be null");
&& unknownObjectBehavior != UNKNOWN_THROW_EXCEPTION) {
throw new IllegalArgumentException("Unrecognised value for unknown behaviour flag");
} }
this.unknownObjectBehavior = unknownObjectBehavior; this.unknownObjectBehavior = unknownObjectBehavior;
} }
// Methods for adding items // Methods for adding items
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
/** /**
* Adds an item, which compares as after all items known to the Comparator. * Adds an item, which compares as after all items known to the Comparator.
* If the item is already known to the Comparator, its old position is * If the item is already known to the Comparator, its old position is
* replaced with the new position. * replaced with the new position.
* *
* @param obj the item to be added to the Comparator. * @param obj the item to be added to the Comparator.
* @return true if obj has been added for the first time, false if * @return true if obj has been added for the first time, false if
* it was already known to the Comparator. * it was already known to the Comparator.
* @throws UnsupportedOperationException if a comparison has already been made * @throws UnsupportedOperationException if a comparison has already been made
*/ */
public boolean add(Object obj) { public boolean add(T obj) {
checkLocked(); checkLocked();
Object position = map.put(obj, new Integer(counter++)); Integer position = map.put(obj, new Integer(counter++));
return (position == null); return (position == null);
} }
/** /**
* Adds a new item, which compares as equal to the given existing item. * Adds a new item, which compares as equal to the given existing item.
* *
* @param existingObj an item already in the Comparator's set of * @param existingObj an item already in the Comparator's set of
* known objects * known objects
* @param newObj an item to be added to the Comparator's set of * @param newObj an item to be added to the Comparator's set of
* known objects * known objects
* @return true if newObj has been added for the first time, false if * @return true if newObj has been added for the first time, false if
* it was already known to the Comparator. * it was already known to the Comparator.
* @throws IllegalArgumentException if existingObject is not in the * @throws IllegalArgumentException if existingObject is not in the
* Comparator's set of known objects. * Comparator's set of known objects.
* @throws UnsupportedOperationException if a comparison has already been made * @throws UnsupportedOperationException if a comparison has already been made
*/ */
public boolean addAsEqual(Object existingObj, Object newObj) { public boolean addAsEqual(T existingObj, T newObj) {
checkLocked(); checkLocked();
Integer position = (Integer) map.get(existingObj); Integer position = map.get(existingObj);
if (position == null) { if (position == null) {
throw new IllegalArgumentException(existingObj + " not known to " + this); throw new IllegalArgumentException(existingObj + " not known to " + this);
} }
Object result = map.put(newObj, position); Integer result = map.put(newObj, position);
return (result == null); return (result == null);
} }
// Comparator methods // Comparator methods
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
/** /**
* Compares two objects according to the order of this Comparator. * Compares two objects according to the order of this Comparator.
* <p> * <p>
* It is important to note that this class will throw an IllegalArgumentException * It is important to note that this class will throw an IllegalArgumentException
* in the case of an unrecognised object. This is not specified in the * in the case of an unrecognised object. This is not specified in the
* Comparator interface, but is the most appropriate exception. * Comparator interface, but is the most appropriate exception.
* *
* @param obj1 the first object to compare * @param obj1 the first object to compare
* @param obj2 the second object to compare * @param obj2 the second object to compare
* @return negative if obj1 is less, positive if greater, zero if equal * @return negative if obj1 is less, positive if greater, zero if equal
* @throws IllegalArgumentException if obj1 or obj2 are not known * @throws IllegalArgumentException if obj1 or obj2 are not known
* to this Comparator and an alternative behavior has not been set * to this Comparator and an alternative behavior has not been set
* via {@link #setUnknownObjectBehavior(int)}. * via {@link #setUnknownObjectBehavior(int)}.
*/ */
public int compare(Object obj1, Object obj2) { public int compare(T obj1, T obj2) {
isLocked = true; isLocked = true;
Integer position1 = (Integer) map.get(obj1); Integer position1 = map.get(obj1);
Integer position2 = (Integer) map.get(obj2); Integer position2 = map.get(obj2);
if (position1 == null || position2 == null) { if (position1 == null || position2 == null) {
switch (unknownObjectBehavior) { switch (unknownObjectBehavior) {
case UNKNOWN_BEFORE : case BEFORE:
if (position1 == null) { return position1 == null ? position2 == null ? 0 : -1 : 1;
return (position2 == null) ? 0 : -1; case AFTER:
} else { return position1 == null ? position2 == null ? 0 : 1 : -1;
return 1; case EXCEPTION:
} Object unknownObj = (position1 == null) ? obj1 : obj2;
case UNKNOWN_AFTER : throw new IllegalArgumentException("Attempting to compare unknown object "
if (position1 == null) { + unknownObj);
return (position2 == null) ? 0 : 1; default: //could be null
} else { throw new UnsupportedOperationException("Unknown unknownObjectBehavior: "
return -1; + unknownObjectBehavior);
}
case UNKNOWN_THROW_EXCEPTION :
Object unknownObj = (position1 == null) ? obj1 : obj2;
throw new IllegalArgumentException("Attempting to compare unknown object " + unknownObj);
default :
throw new UnsupportedOperationException("Unknown unknownObjectBehavior: " + unknownObjectBehavior);
} }
} else {
return position1.compareTo(position2);
} }
return position1.compareTo(position2);
} }
} }

View File

@ -19,6 +19,8 @@ package org.apache.commons.collections.comparators;
import java.io.Serializable; import java.io.Serializable;
import java.util.Comparator; import java.util.Comparator;
import org.apache.commons.collections.ComparatorUtils;
/** /**
* Reverses the order of another comparator by reversing the arguments * Reverses the order of another comparator by reversing the arguments
* to its {@link #compare(Object, Object) compare} method. * to its {@link #compare(Object, Object) compare} method.
@ -30,13 +32,13 @@ import java.util.Comparator;
* *
* @see java.util.Collections#reverseOrder() * @see java.util.Collections#reverseOrder()
*/ */
public class ReverseComparator implements Comparator, Serializable { public class ReverseComparator<E> implements Comparator<E>, Serializable {
/** Serialization version from Collections 2.0. */ /** Serialization version from Collections 2.0. */
private static final long serialVersionUID = 2858887242028539265L; private static final long serialVersionUID = 2858887242028539265L;
/** The comparator being decorated. */ /** The comparator being decorated. */
private Comparator comparator; private Comparator<E> comparator;
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
/** /**
@ -60,12 +62,9 @@ public class ReverseComparator implements Comparator, Serializable {
* *
* @param comparator Comparator to reverse * @param comparator Comparator to reverse
*/ */
public ReverseComparator(Comparator comparator) { @SuppressWarnings("unchecked")
if(comparator != null) { public ReverseComparator(Comparator<E> comparator) {
this.comparator = comparator; this.comparator = comparator == null ? ComparatorUtils.NATURAL_COMPARATOR : comparator;
} else {
this.comparator = ComparableComparator.getInstance();
}
} }
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
@ -76,7 +75,7 @@ public class ReverseComparator implements Comparator, Serializable {
* @param obj2 the second object to compare * @param obj2 the second object to compare
* @return negative if obj1 is less, positive if greater, zero if equal * @return negative if obj1 is less, positive if greater, zero if equal
*/ */
public int compare(Object obj1, Object obj2) { public int compare(E obj1, E obj2) {
return comparator.compare(obj2, obj1); return comparator.compare(obj2, obj1);
} }
@ -109,16 +108,17 @@ public class ReverseComparator implements Comparator, Serializable {
* @since Commons Collections 3.0 * @since Commons Collections 3.0
*/ */
public boolean equals(Object object) { public boolean equals(Object object) {
if(this == object) { if (this == object) {
return true; return true;
} else if(null == object) { }
return false; if (null == object) {
} else if(object.getClass().equals(this.getClass())) {
ReverseComparator thatrc = (ReverseComparator)object;
return comparator.equals(thatrc.comparator);
} else {
return false; return false;
} }
if (object.getClass().equals(this.getClass())) {
ReverseComparator<?> thatrc = (ReverseComparator<?>) object;
return comparator.equals(thatrc.comparator);
}
return false;
} }
} }

View File

@ -18,6 +18,7 @@ package org.apache.commons.collections.comparators;
import java.util.Comparator; import java.util.Comparator;
import org.apache.commons.collections.ComparatorUtils;
import org.apache.commons.collections.Transformer; import org.apache.commons.collections.Transformer;
/** /**
@ -31,12 +32,12 @@ import org.apache.commons.collections.Transformer;
* @see org.apache.commons.collections.Transformer * @see org.apache.commons.collections.Transformer
* @see org.apache.commons.collections.comparators.ComparableComparator * @see org.apache.commons.collections.comparators.ComparableComparator
*/ */
public class TransformingComparator implements Comparator { public class TransformingComparator<E> implements Comparator<E> {
/** The decorated comparator. */ /** The decorated comparator. */
protected Comparator decorated; protected Comparator<E> decorated;
/** The transformer being used. */ /** The transformer being used. */
protected Transformer transformer; protected Transformer<? super E, ? extends E> transformer;
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
/** /**
@ -45,8 +46,9 @@ public class TransformingComparator implements Comparator {
* *
* @param transformer what will transform the arguments to <code>compare</code> * @param transformer what will transform the arguments to <code>compare</code>
*/ */
public TransformingComparator(Transformer transformer) { @SuppressWarnings("unchecked")
this(transformer, new ComparableComparator()); public TransformingComparator(Transformer<? super E, ? extends E> transformer) {
this(transformer, ComparatorUtils.NATURAL_COMPARATOR);
} }
/** /**
@ -55,7 +57,7 @@ public class TransformingComparator implements Comparator {
* @param transformer what will transform the arguments to <code>compare</code> * @param transformer what will transform the arguments to <code>compare</code>
* @param decorated the decorated Comparator * @param decorated the decorated Comparator
*/ */
public TransformingComparator(Transformer transformer, Comparator decorated) { public TransformingComparator(Transformer<? super E, ? extends E> transformer, Comparator<E> decorated) {
this.decorated = decorated; this.decorated = decorated;
this.transformer = transformer; this.transformer = transformer;
} }
@ -68,9 +70,9 @@ public class TransformingComparator implements Comparator {
* @param obj2 the second object to transform then compare * @param obj2 the second object to transform then compare
* @return negative if obj1 is less, positive if greater, zero if equal * @return negative if obj1 is less, positive if greater, zero if equal
*/ */
public int compare(Object obj1, Object obj2) { public int compare(E obj1, E obj2) {
Object value1 = this.transformer.transform(obj1); E value1 = this.transformer.transform(obj1);
Object value2 = this.transformer.transform(obj2); E value2 = this.transformer.transform(obj2);
return this.decorated.compare(value1, value2); return this.decorated.compare(value1, value2);
} }

View File

@ -28,39 +28,39 @@ import org.apache.commons.collections.Predicate;
* *
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public final class AndPredicate implements Predicate, PredicateDecorator, Serializable { public final class AndPredicate<T> implements Predicate<T>, PredicateDecorator<T>, Serializable {
/** Serial version UID */ /** Serial version UID */
private static final long serialVersionUID = 4189014213763186912L; private static final long serialVersionUID = 4189014213763186912L;
/** The array of predicates to call */ /** The array of predicates to call */
private final Predicate iPredicate1; private final Predicate<? super T> iPredicate1;
/** The array of predicates to call */ /** The array of predicates to call */
private final Predicate iPredicate2; private final Predicate<? super T> iPredicate2;
/** /**
* Factory to create the predicate. * Factory to create the predicate.
* *
* @param predicate1 the first predicate to check, not null * @param predicate1 the first predicate to check, not null
* @param predicate2 the second predicate to check, not null * @param predicate2 the second predicate to check, not null
* @return the <code>and</code> predicate * @return the <code>and</code> predicate
* @throws IllegalArgumentException if either predicate is null * @throws IllegalArgumentException if either predicate is null
*/ */
public static Predicate getInstance(Predicate predicate1, Predicate predicate2) { public static <T> Predicate<T> getInstance(Predicate<? super T> predicate1, Predicate<? super T> predicate2) {
if (predicate1 == null || predicate2 == null) { if (predicate1 == null || predicate2 == null) {
throw new IllegalArgumentException("Predicate must not be null"); throw new IllegalArgumentException("Predicate must not be null");
} }
return new AndPredicate(predicate1, predicate2); return new AndPredicate<T>(predicate1, predicate2);
} }
/** /**
* Constructor that performs no validation. * Constructor that performs no validation.
* Use <code>getInstance</code> if you want that. * Use <code>getInstance</code> if you want that.
* *
* @param predicate1 the first predicate to check, not null * @param predicate1 the first predicate to check, not null
* @param predicate2 the second predicate to check, not null * @param predicate2 the second predicate to check, not null
*/ */
public AndPredicate(Predicate predicate1, Predicate predicate2) { public AndPredicate(Predicate<? super T> predicate1, Predicate<? super T> predicate2) {
super(); super();
iPredicate1 = predicate1; iPredicate1 = predicate1;
iPredicate2 = predicate2; iPredicate2 = predicate2;
@ -68,21 +68,22 @@ public final class AndPredicate implements Predicate, PredicateDecorator, Serial
/** /**
* Evaluates the predicate returning true if both predicates return true. * Evaluates the predicate returning true if both predicates return true.
* *
* @param object the input object * @param object the input object
* @return true if both decorated predicates return true * @return true if both decorated predicates return true
*/ */
public boolean evaluate(Object object) { public boolean evaluate(T object) {
return (iPredicate1.evaluate(object) && iPredicate2.evaluate(object)); return (iPredicate1.evaluate(object) && iPredicate2.evaluate(object));
} }
/** /**
* Gets the two predicates being decorated as an array. * Gets the two predicates being decorated as an array.
* *
* @return the predicates * @return the predicates
* @since Commons Collections 3.1 * @since Commons Collections 3.1
*/ */
public Predicate[] getPredicates() { @SuppressWarnings("unchecked")
public Predicate<? super T>[] getPredicates() {
return new Predicate[] {iPredicate1, iPredicate2}; return new Predicate[] {iPredicate1, iPredicate2};
} }

View File

@ -35,14 +35,14 @@ import org.apache.commons.collections.Predicate;
* @author Stephen Colebourne * @author Stephen Colebourne
* @author Matt Benson * @author Matt Benson
*/ */
public final class AnyPredicate implements Predicate, PredicateDecorator, Serializable { public final class AnyPredicate<T> implements Predicate<T>, PredicateDecorator<T>, Serializable {
/** Serial version UID */ /** Serial version UID */
private static final long serialVersionUID = 7429999530934647542L; private static final long serialVersionUID = 7429999530934647542L;
/** The array of predicates to call */ /** The array of predicates to call */
private final Predicate[] iPredicates; private final Predicate<? super T>[] iPredicates;
/** /**
* Factory to create the predicate. * Factory to create the predicate.
* <p> * <p>
@ -54,15 +54,16 @@ public final class AnyPredicate implements Predicate, PredicateDecorator, Serial
* @throws IllegalArgumentException if the predicates array is null * @throws IllegalArgumentException if the predicates array is null
* @throws IllegalArgumentException if any predicate in the array is null * @throws IllegalArgumentException if any predicate in the array is null
*/ */
public static Predicate getInstance(Predicate[] predicates) { @SuppressWarnings("unchecked")
public static <T> Predicate<T> getInstance(Predicate<? super T>[] predicates) {
FunctorUtils.validate(predicates); FunctorUtils.validate(predicates);
if (predicates.length == 0) { if (predicates.length == 0) {
return FalsePredicate.INSTANCE; return FalsePredicate.<T>falsePredicate();
} }
if (predicates.length == 1) { if (predicates.length == 1) {
return predicates[0]; return (Predicate<T>) predicates[0];
} }
return new AnyPredicate(FunctorUtils.copy(predicates)); return new AnyPredicate<T>(FunctorUtils.copy(predicates));
} }
/** /**
@ -76,35 +77,36 @@ public final class AnyPredicate implements Predicate, PredicateDecorator, Serial
* @throws IllegalArgumentException if the predicates array is null * @throws IllegalArgumentException if the predicates array is null
* @throws IllegalArgumentException if any predicate in the array is null * @throws IllegalArgumentException if any predicate in the array is null
*/ */
public static Predicate getInstance(Collection predicates) { @SuppressWarnings("unchecked")
Predicate[] preds = FunctorUtils.validate(predicates); public static <T> Predicate<T> getInstance(Collection<? extends Predicate<T>> predicates) {
Predicate<? super T>[] preds = FunctorUtils.validate(predicates);
if (preds.length == 0) { if (preds.length == 0) {
return FalsePredicate.INSTANCE; return FalsePredicate.<T>falsePredicate();
} }
if (preds.length == 1) { if (preds.length == 1) {
return preds[0]; return (Predicate<T>) preds[0];
} }
return new AnyPredicate(preds); return new AnyPredicate<T>(preds);
} }
/** /**
* Constructor that performs no validation. * Constructor that performs no validation.
* Use <code>getInstance</code> if you want that. * Use <code>getInstance</code> if you want that.
* *
* @param predicates the predicates to check, not cloned, not null * @param predicates the predicates to check, not cloned, not null
*/ */
public AnyPredicate(Predicate[] predicates) { public AnyPredicate(Predicate<? super T>[] predicates) {
super(); super();
iPredicates = predicates; iPredicates = predicates;
} }
/** /**
* Evaluates the predicate returning true if any predicate returns true. * Evaluates the predicate returning true if any predicate returns true.
* *
* @param object the input object * @param object the input object
* @return true if any decorated predicate return true * @return true if any decorated predicate return true
*/ */
public boolean evaluate(Object object) { public boolean evaluate(T object) {
for (int i = 0; i < iPredicates.length; i++) { for (int i = 0; i < iPredicates.length; i++) {
if (iPredicates[i].evaluate(object)) { if (iPredicates[i].evaluate(object)) {
return true; return true;
@ -115,11 +117,11 @@ public final class AnyPredicate implements Predicate, PredicateDecorator, Serial
/** /**
* Gets the predicates, do not modify the array. * Gets the predicates, do not modify the array.
* *
* @return the predicates * @return the predicates
* @since Commons Collections 3.1 * @since Commons Collections 3.1
*/ */
public Predicate[] getPredicates() { public Predicate<? super T>[] getPredicates() {
return iPredicates; return iPredicates;
} }

View File

@ -18,7 +18,6 @@ package org.apache.commons.collections.functors;
import java.io.Serializable; import java.io.Serializable;
import java.util.Collection; import java.util.Collection;
import java.util.Iterator;
import org.apache.commons.collections.Closure; import org.apache.commons.collections.Closure;
@ -30,13 +29,13 @@ import org.apache.commons.collections.Closure;
* *
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public class ChainedClosure implements Closure, Serializable { public class ChainedClosure<E> implements Closure<E>, Serializable {
/** Serial version UID */ /** Serial version UID */
private static final long serialVersionUID = -3520677225766901240L; private static final long serialVersionUID = -3520677225766901240L;
/** The closures to call in turn */ /** The closures to call in turn */
private final Closure[] iClosures; private final Closure<? super E>[] iClosures;
/** /**
* Factory method that performs validation and copies the parameter array. * Factory method that performs validation and copies the parameter array.
@ -46,15 +45,15 @@ public class ChainedClosure implements Closure, Serializable {
* @throws IllegalArgumentException if the closures array is null * @throws IllegalArgumentException if the closures array is null
* @throws IllegalArgumentException if any closure in the array is null * @throws IllegalArgumentException if any closure in the array is null
*/ */
public static Closure getInstance(Closure[] closures) { public static <E> Closure<E> getInstance(Closure<? super E>[] closures) {
FunctorUtils.validate(closures); FunctorUtils.validate(closures);
if (closures.length == 0) { if (closures.length == 0) {
return NOPClosure.INSTANCE; return NOPClosure.<E>getInstance();
} }
closures = FunctorUtils.copy(closures); closures = FunctorUtils.copy(closures);
return new ChainedClosure(closures); return new ChainedClosure<E>(closures);
} }
/** /**
* Create a new Closure that calls each closure in turn, passing the * Create a new Closure that calls each closure in turn, passing the
* result into the next closure. The ordering is that of the iterator() * result into the next closure. The ordering is that of the iterator()
@ -65,21 +64,22 @@ public class ChainedClosure implements Closure, Serializable {
* @throws IllegalArgumentException if the closures collection is null * @throws IllegalArgumentException if the closures collection is null
* @throws IllegalArgumentException if any closure in the collection is null * @throws IllegalArgumentException if any closure in the collection is null
*/ */
public static Closure getInstance(Collection closures) { @SuppressWarnings("unchecked")
public static <E> Closure<E> getInstance(Collection<Closure<E>> closures) {
if (closures == null) { if (closures == null) {
throw new IllegalArgumentException("Closure collection must not be null"); throw new IllegalArgumentException("Closure collection must not be null");
} }
if (closures.size() == 0) { if (closures.size() == 0) {
return NOPClosure.INSTANCE; return NOPClosure.<E>getInstance();
} }
// convert to array like this to guarantee iterator() ordering // convert to array like this to guarantee iterator() ordering
Closure[] cmds = new Closure[closures.size()]; Closure<? super E>[] cmds = new Closure[closures.size()];
int i = 0; int i = 0;
for (Iterator it = closures.iterator(); it.hasNext();) { for (Closure<? super E> closure : closures) {
cmds[i++] = (Closure) it.next(); cmds[i++] = (Closure<E>) closure;
} }
FunctorUtils.validate(cmds); FunctorUtils.validate(cmds);
return new ChainedClosure(cmds); return new ChainedClosure<E>(cmds);
} }
/** /**
@ -90,12 +90,13 @@ public class ChainedClosure implements Closure, Serializable {
* @return the <code>chained</code> closure * @return the <code>chained</code> closure
* @throws IllegalArgumentException if either closure is null * @throws IllegalArgumentException if either closure is null
*/ */
public static Closure getInstance(Closure closure1, Closure closure2) { @SuppressWarnings("unchecked")
public static <E> Closure<E> getInstance(Closure<? super E> closure1, Closure<? super E> closure2) {
if (closure1 == null || closure2 == null) { if (closure1 == null || closure2 == null) {
throw new IllegalArgumentException("Closures must not be null"); throw new IllegalArgumentException("Closures must not be null");
} }
Closure[] closures = new Closure[] { closure1, closure2 }; Closure<E>[] closures = new Closure[] { closure1, closure2 };
return new ChainedClosure(closures); return new ChainedClosure<E>(closures);
} }
/** /**
@ -104,7 +105,7 @@ public class ChainedClosure implements Closure, Serializable {
* *
* @param closures the closures to chain, not copied, no nulls * @param closures the closures to chain, not copied, no nulls
*/ */
public ChainedClosure(Closure[] closures) { public ChainedClosure(Closure<? super E>[] closures) {
super(); super();
iClosures = closures; iClosures = closures;
} }
@ -114,7 +115,7 @@ public class ChainedClosure implements Closure, Serializable {
* *
* @param input the input object passed to each closure * @param input the input object passed to each closure
*/ */
public void execute(Object input) { public void execute(E input) {
for (int i = 0; i < iClosures.length; i++) { for (int i = 0; i < iClosures.length; i++) {
iClosures[i].execute(input); iClosures[i].execute(input);
} }
@ -125,7 +126,7 @@ public class ChainedClosure implements Closure, Serializable {
* @return the closures * @return the closures
* @since Commons Collections 3.1 * @since Commons Collections 3.1
*/ */
public Closure[] getClosures() { public Closure<? super E>[] getClosures() {
return iClosures; return iClosures;
} }

View File

@ -18,7 +18,6 @@ package org.apache.commons.collections.functors;
import java.io.Serializable; import java.io.Serializable;
import java.util.Collection; import java.util.Collection;
import java.util.Iterator;
import org.apache.commons.collections.Transformer; import org.apache.commons.collections.Transformer;
@ -33,13 +32,13 @@ import org.apache.commons.collections.Transformer;
* *
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public class ChainedTransformer implements Transformer, Serializable { public class ChainedTransformer<T> implements Transformer<T, T>, Serializable {
/** Serial version UID */ /** Serial version UID */
private static final long serialVersionUID = 3514945074733160196L; private static final long serialVersionUID = 3514945074733160196L;
/** The transformers to call in turn */ /** The transformers to call in turn */
private final Transformer[] iTransformers; private final Transformer<? super T, ? extends T>[] iTransformers;
/** /**
* Factory method that performs validation and copies the parameter array. * Factory method that performs validation and copies the parameter array.
@ -49,13 +48,13 @@ public class ChainedTransformer implements Transformer, Serializable {
* @throws IllegalArgumentException if the transformers array is null * @throws IllegalArgumentException if the transformers array is null
* @throws IllegalArgumentException if any transformer in the array is null * @throws IllegalArgumentException if any transformer in the array is null
*/ */
public static Transformer getInstance(Transformer[] transformers) { public static <T> Transformer<T, T> getInstance(Transformer<? super T, ? extends T>[] transformers) {
FunctorUtils.validate(transformers); FunctorUtils.validate(transformers);
if (transformers.length == 0) { if (transformers.length == 0) {
return NOPTransformer.INSTANCE; return NOPTransformer.<T>getInstance();
} }
transformers = FunctorUtils.copy(transformers); transformers = FunctorUtils.copy(transformers);
return new ChainedTransformer(transformers); return new ChainedTransformer<T>(transformers);
} }
/** /**
@ -68,21 +67,18 @@ public class ChainedTransformer implements Transformer, Serializable {
* @throws IllegalArgumentException if the transformers collection is null * @throws IllegalArgumentException if the transformers collection is null
* @throws IllegalArgumentException if any transformer in the collection is null * @throws IllegalArgumentException if any transformer in the collection is null
*/ */
public static Transformer getInstance(Collection transformers) { @SuppressWarnings("unchecked")
public static <T> Transformer<T, T> getInstance(Collection<? extends Transformer<T, T>> transformers) {
if (transformers == null) { if (transformers == null) {
throw new IllegalArgumentException("Transformer collection must not be null"); throw new IllegalArgumentException("Transformer collection must not be null");
} }
if (transformers.size() == 0) { if (transformers.size() == 0) {
return NOPTransformer.INSTANCE; return NOPTransformer.<T>getInstance();
} }
// convert to array like this to guarantee iterator() ordering // convert to array like this to guarantee iterator() ordering
Transformer[] cmds = new Transformer[transformers.size()]; Transformer<T, T>[] cmds = transformers.toArray(new Transformer[transformers.size()]);
int i = 0;
for (Iterator it = transformers.iterator(); it.hasNext();) {
cmds[i++] = (Transformer) it.next();
}
FunctorUtils.validate(cmds); FunctorUtils.validate(cmds);
return new ChainedTransformer(cmds); return new ChainedTransformer<T>(cmds);
} }
/** /**
@ -93,12 +89,13 @@ public class ChainedTransformer implements Transformer, Serializable {
* @return the <code>chained</code> transformer * @return the <code>chained</code> transformer
* @throws IllegalArgumentException if either transformer is null * @throws IllegalArgumentException if either transformer is null
*/ */
public static Transformer getInstance(Transformer transformer1, Transformer transformer2) { @SuppressWarnings("unchecked")
public static <T> Transformer<T, T> getInstance(Transformer<? super T, ? extends T> transformer1, Transformer<? super T, ? extends T> transformer2) {
if (transformer1 == null || transformer2 == null) { if (transformer1 == null || transformer2 == null) {
throw new IllegalArgumentException("Transformers must not be null"); throw new IllegalArgumentException("Transformers must not be null");
} }
Transformer[] transformers = new Transformer[] { transformer1, transformer2 }; Transformer<? super T, ? extends T>[] transformers = new Transformer[] { transformer1, transformer2 };
return new ChainedTransformer(transformers); return new ChainedTransformer<T>(transformers);
} }
/** /**
@ -107,7 +104,7 @@ public class ChainedTransformer implements Transformer, Serializable {
* *
* @param transformers the transformers to chain, not copied, no nulls * @param transformers the transformers to chain, not copied, no nulls
*/ */
public ChainedTransformer(Transformer[] transformers) { public ChainedTransformer(Transformer<? super T, ? extends T>[] transformers) {
super(); super();
iTransformers = transformers; iTransformers = transformers;
} }
@ -118,7 +115,7 @@ public class ChainedTransformer implements Transformer, Serializable {
* @param object the input object passed to the first transformer * @param object the input object passed to the first transformer
* @return the transformed result * @return the transformed result
*/ */
public Object transform(Object object) { public T transform(T object) {
for (int i = 0; i < iTransformers.length; i++) { for (int i = 0; i < iTransformers.length; i++) {
object = iTransformers[i].transform(object); object = iTransformers[i].transform(object);
} }
@ -130,7 +127,7 @@ public class ChainedTransformer implements Transformer, Serializable {
* @return the transformers * @return the transformers
* @since Commons Collections 3.1 * @since Commons Collections 3.1
*/ */
public Transformer[] getTransformers() { public Transformer<? super T, ? extends T>[] getTransformers() {
return iTransformers; return iTransformers;
} }

View File

@ -30,13 +30,13 @@ import org.apache.commons.collections.Transformer;
* *
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public class CloneTransformer implements Transformer, Serializable { public class CloneTransformer<T> implements Transformer<T, T>, Serializable {
/** Serial version UID */ /** Serial version UID */
private static final long serialVersionUID = -8188742709499652567L; private static final long serialVersionUID = -8188742709499652567L;
/** Singleton predicate instance */ /** Singleton predicate instance */
public static final Transformer INSTANCE = new CloneTransformer(); public static final Transformer<Object, Object> INSTANCE = new CloneTransformer<Object>();
/** /**
* Factory returning the singleton instance. * Factory returning the singleton instance.
@ -44,8 +44,9 @@ public class CloneTransformer implements Transformer, Serializable {
* @return the singleton instance * @return the singleton instance
* @since Commons Collections 3.1 * @since Commons Collections 3.1
*/ */
public static Transformer getInstance() { @SuppressWarnings("unchecked")
return INSTANCE; public static <T> Transformer<T, T> getInstance() {
return (Transformer<T, T>) INSTANCE;
} }
/** /**
@ -61,7 +62,7 @@ public class CloneTransformer implements Transformer, Serializable {
* @param input the input object to transform * @param input the input object to transform
* @return the transformed result * @return the transformed result
*/ */
public Object transform(Object input) { public T transform(T input) {
if (input == null) { if (input == null) {
return null; return null;
} }

View File

@ -30,13 +30,13 @@ import org.apache.commons.collections.Transformer;
* *
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public class ClosureTransformer implements Transformer, Serializable { public class ClosureTransformer<T> implements Transformer<T, T>, Serializable {
/** Serial version UID */ /** Serial version UID */
private static final long serialVersionUID = 478466901448617286L; private static final long serialVersionUID = 478466901448617286L;
/** The closure to wrap */ /** The closure to wrap */
private final Closure iClosure; private final Closure<? super T> iClosure;
/** /**
* Factory method that performs validation. * Factory method that performs validation.
@ -45,11 +45,11 @@ public class ClosureTransformer implements Transformer, Serializable {
* @return the <code>closure</code> transformer * @return the <code>closure</code> transformer
* @throws IllegalArgumentException if the closure is null * @throws IllegalArgumentException if the closure is null
*/ */
public static Transformer getInstance(Closure closure) { public static <T> Transformer<T, T> getInstance(Closure<? super T> closure) {
if (closure == null) { if (closure == null) {
throw new IllegalArgumentException("Closure must not be null"); throw new IllegalArgumentException("Closure must not be null");
} }
return new ClosureTransformer(closure); return new ClosureTransformer<T>(closure);
} }
/** /**
@ -58,7 +58,7 @@ public class ClosureTransformer implements Transformer, Serializable {
* *
* @param closure the closure to call, not null * @param closure the closure to call, not null
*/ */
public ClosureTransformer(Closure closure) { public ClosureTransformer(Closure<? super T> closure) {
super(); super();
iClosure = closure; iClosure = closure;
} }
@ -69,7 +69,7 @@ public class ClosureTransformer implements Transformer, Serializable {
* @param input the input object to transform * @param input the input object to transform
* @return the transformed result * @return the transformed result
*/ */
public Object transform(Object input) { public T transform(T input) {
iClosure.execute(input); iClosure.execute(input);
return input; return input;
} }
@ -80,7 +80,7 @@ public class ClosureTransformer implements Transformer, Serializable {
* @return the closure * @return the closure
* @since Commons Collections 3.1 * @since Commons Collections 3.1
*/ */
public Closure getClosure() { public Closure<? super T> getClosure() {
return iClosure; return iClosure;
} }

View File

@ -32,16 +32,16 @@ import org.apache.commons.collections.Factory;
* *
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public class ConstantFactory implements Factory, Serializable { public class ConstantFactory<T> implements Factory<T>, Serializable {
/** Serial version UID */ /** Serial version UID */
private static final long serialVersionUID = -3520677225766901240L; private static final long serialVersionUID = -3520677225766901240L;
/** Returns null each time */ /** Returns null each time */
public static final Factory NULL_INSTANCE = new ConstantFactory(null); public static final Factory<Object> NULL_INSTANCE = new ConstantFactory<Object>(null);
/** The closures to call in turn */ /** The closures to call in turn */
private final Object iConstant; private final T iConstant;
/** /**
* Factory method that performs validation. * Factory method that performs validation.
@ -49,11 +49,12 @@ public class ConstantFactory implements Factory, Serializable {
* @param constantToReturn the constant object to return each time in the factory * @param constantToReturn the constant object to return each time in the factory
* @return the <code>constant</code> factory. * @return the <code>constant</code> factory.
*/ */
public static Factory getInstance(Object constantToReturn) { @SuppressWarnings("unchecked")
public static <T> Factory<T> getInstance(T constantToReturn) {
if (constantToReturn == null) { if (constantToReturn == null) {
return NULL_INSTANCE; return (Factory<T>) NULL_INSTANCE;
} }
return new ConstantFactory(constantToReturn); return new ConstantFactory<T>(constantToReturn);
} }
/** /**
@ -62,7 +63,7 @@ public class ConstantFactory implements Factory, Serializable {
* *
* @param constantToReturn the constant to return each time * @param constantToReturn the constant to return each time
*/ */
public ConstantFactory(Object constantToReturn) { public ConstantFactory(T constantToReturn) {
super(); super();
iConstant = constantToReturn; iConstant = constantToReturn;
} }
@ -72,7 +73,7 @@ public class ConstantFactory implements Factory, Serializable {
* *
* @return the stored constant value * @return the stored constant value
*/ */
public Object create() { public T create() {
return iConstant; return iConstant;
} }
@ -82,7 +83,7 @@ public class ConstantFactory implements Factory, Serializable {
* @return the constant * @return the constant
* @since Commons Collections 3.1 * @since Commons Collections 3.1
*/ */
public Object getConstant() { public T getConstant() {
return iConstant; return iConstant;
} }

View File

@ -32,16 +32,27 @@ import org.apache.commons.collections.Transformer;
* *
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public class ConstantTransformer implements Transformer, Serializable { public class ConstantTransformer<I, O> implements Transformer<I, O>, Serializable {
/** Serial version UID */ /** Serial version UID */
private static final long serialVersionUID = 6374440726369055124L; private static final long serialVersionUID = 6374440726369055124L;
/** Returns null each time */ /** Returns null each time */
public static final Transformer NULL_INSTANCE = new ConstantTransformer(null); public static final Transformer<Object, Object> NULL_INSTANCE = new ConstantTransformer<Object, Object>(null);
/** The closures to call in turn */ /** The closures to call in turn */
private final Object iConstant; private final O iConstant;
/**
* Get a typed null instance.
* @param <I>
* @param <O>
* @return Transformer<I, O> that always returns null.
*/
@SuppressWarnings("unchecked")
public static <I, O> Transformer<I, O> getNullInstance() {
return (Transformer<I, O>) NULL_INSTANCE;
}
/** /**
* Transformer method that performs validation. * Transformer method that performs validation.
@ -49,11 +60,11 @@ public class ConstantTransformer implements Transformer, Serializable {
* @param constantToReturn the constant object to return each time in the factory * @param constantToReturn the constant object to return each time in the factory
* @return the <code>constant</code> factory. * @return the <code>constant</code> factory.
*/ */
public static Transformer getInstance(Object constantToReturn) { public static <I, O> Transformer<I, O> getInstance(O constantToReturn) {
if (constantToReturn == null) { if (constantToReturn == null) {
return NULL_INSTANCE; return getNullInstance();
} }
return new ConstantTransformer(constantToReturn); return new ConstantTransformer<I, O>(constantToReturn);
} }
/** /**
@ -62,7 +73,7 @@ public class ConstantTransformer implements Transformer, Serializable {
* *
* @param constantToReturn the constant to return each time * @param constantToReturn the constant to return each time
*/ */
public ConstantTransformer(Object constantToReturn) { public ConstantTransformer(O constantToReturn) {
super(); super();
iConstant = constantToReturn; iConstant = constantToReturn;
} }
@ -73,7 +84,7 @@ public class ConstantTransformer implements Transformer, Serializable {
* @param input the input object which is ignored * @param input the input object which is ignored
* @return the stored constant * @return the stored constant
*/ */
public Object transform(Object input) { public O transform(I input) {
return iConstant; return iConstant;
} }
@ -83,8 +94,34 @@ public class ConstantTransformer implements Transformer, Serializable {
* @return the constant * @return the constant
* @since Commons Collections 3.1 * @since Commons Collections 3.1
*/ */
public Object getConstant() { public O getConstant() {
return iConstant; return iConstant;
} }
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof ConstantTransformer == false) {
return false;
}
Object otherConstant = ((ConstantTransformer<?, ?>) obj).getConstant();
return otherConstant == getConstant() || otherConstant != null && otherConstant.equals(getConstant());
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
int result = "ConstantTransformer".hashCode() << 2;
if (getConstant() != null) {
result |= getConstant().hashCode();
}
return result;
}
} }

View File

@ -29,14 +29,13 @@ import org.apache.commons.collections.FunctorException;
* *
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public final class ExceptionClosure implements Closure, Serializable { public final class ExceptionClosure<E> implements Closure<E>, Serializable {
/** Serial version UID */ /** Serial version UID */
private static final long serialVersionUID = 7179106032121985545L; private static final long serialVersionUID = 7179106032121985545L;
/** Singleton predicate instance */ /** Singleton predicate instance */
public static final Closure INSTANCE = new ExceptionClosure(); public static final Closure<Object> INSTANCE = new ExceptionClosure<Object>();
/** /**
* Factory returning the singleton instance. * Factory returning the singleton instance.
@ -44,8 +43,9 @@ public final class ExceptionClosure implements Closure, Serializable {
* @return the singleton instance * @return the singleton instance
* @since Commons Collections 3.1 * @since Commons Collections 3.1
*/ */
public static Closure getInstance() { @SuppressWarnings("unchecked")
return INSTANCE; public static <E> Closure<E> getInstance() {
return (Closure<E>) INSTANCE;
} }
/** /**
@ -61,7 +61,7 @@ public final class ExceptionClosure implements Closure, Serializable {
* @param input the input object * @param input the input object
* @throws FunctorException always * @throws FunctorException always
*/ */
public void execute(Object input) { public void execute(E input) {
throw new FunctorException("ExceptionClosure invoked"); throw new FunctorException("ExceptionClosure invoked");
} }

View File

@ -29,14 +29,13 @@ import org.apache.commons.collections.FunctorException;
* *
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public final class ExceptionFactory implements Factory, Serializable { public final class ExceptionFactory<T> implements Factory<T>, Serializable {
/** Serial version UID */ /** Serial version UID */
private static final long serialVersionUID = 7179106032121985545L; private static final long serialVersionUID = 7179106032121985545L;
/** Singleton predicate instance */ /** Singleton predicate instance */
public static final Factory INSTANCE = new ExceptionFactory(); public static final Factory<Object> INSTANCE = new ExceptionFactory<Object>();
/** /**
* Factory returning the singleton instance. * Factory returning the singleton instance.
@ -44,8 +43,9 @@ public final class ExceptionFactory implements Factory, Serializable {
* @return the singleton instance * @return the singleton instance
* @since Commons Collections 3.1 * @since Commons Collections 3.1
*/ */
public static Factory getInstance() { @SuppressWarnings("unchecked")
return INSTANCE; public static <T> Factory<T> getInstance() {
return (Factory<T>) INSTANCE;
} }
/** /**
@ -61,7 +61,7 @@ public final class ExceptionFactory implements Factory, Serializable {
* @return never * @return never
* @throws FunctorException always * @throws FunctorException always
*/ */
public Object create() { public T create() {
throw new FunctorException("ExceptionFactory invoked"); throw new FunctorException("ExceptionFactory invoked");
} }

View File

@ -29,22 +29,23 @@ import org.apache.commons.collections.Predicate;
* *
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public final class ExceptionPredicate implements Predicate, Serializable { public final class ExceptionPredicate<T> implements Predicate<T>, Serializable {
/** Serial version UID */ /** Serial version UID */
private static final long serialVersionUID = 7179106032121985545L; private static final long serialVersionUID = 7179106032121985545L;
/** Singleton predicate instance */ /** Singleton predicate instance */
public static final Predicate INSTANCE = new ExceptionPredicate(); public static final Predicate<Object> INSTANCE = new ExceptionPredicate<Object>();
/** /**
* Factory returning the singleton instance. * Factory returning the singleton instance.
* *
* @return the singleton instance * @return the singleton instance
* @since Commons Collections 3.1 * @since Commons Collections 3.1
*/ */
public static Predicate getInstance() { @SuppressWarnings("unchecked")
return INSTANCE; public static <T> Predicate<T> getInstance() {
return (Predicate<T>) INSTANCE;
} }
/** /**
@ -56,13 +57,13 @@ public final class ExceptionPredicate implements Predicate, Serializable {
/** /**
* Evaluates the predicate always throwing an exception. * Evaluates the predicate always throwing an exception.
* *
* @param object the input object * @param object the input object
* @return never * @return never
* @throws FunctorException always * @throws FunctorException always
*/ */
public boolean evaluate(Object object) { public boolean evaluate(T object) {
throw new FunctorException("ExceptionPredicate invoked"); throw new FunctorException("ExceptionPredicate invoked");
} }
} }

View File

@ -29,23 +29,23 @@ import org.apache.commons.collections.Transformer;
* *
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public final class ExceptionTransformer implements Transformer, Serializable { public final class ExceptionTransformer<I, O> implements Transformer<I, O>, Serializable {
/** Serial version UID */ /** Serial version UID */
private static final long serialVersionUID = 7179106032121985545L; private static final long serialVersionUID = 7179106032121985545L;
/** Singleton predicate instance */ /** Singleton predicate instance */
public static final Transformer INSTANCE = new ExceptionTransformer(); public static final Transformer<Object, Object> INSTANCE = new ExceptionTransformer<Object, Object>();
/** /**
* Factory returning the singleton instance. * Factory returning the singleton instance.
* *
* @return the singleton instance * @return the singleton instance
* @since Commons Collections 3.1 * @since Commons Collections 3.1
*/ */
public static Transformer getInstance() { @SuppressWarnings("unchecked")
return INSTANCE; public static <I, O> Transformer<I, O> getInstance() {
return (Transformer<I, O>) INSTANCE;
} }
/** /**
@ -57,12 +57,12 @@ public final class ExceptionTransformer implements Transformer, Serializable {
/** /**
* Transforms the input to result by cloning it. * Transforms the input to result by cloning it.
* *
* @param input the input object to transform * @param input the input object to transform
* @return never * @return never
* @throws FunctorException always * @throws FunctorException always
*/ */
public Object transform(Object input) { public O transform(I input) {
throw new FunctorException("ExceptionTransformer invoked"); throw new FunctorException("ExceptionTransformer invoked");
} }

View File

@ -29,13 +29,13 @@ import org.apache.commons.collections.Transformer;
* *
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public class FactoryTransformer implements Transformer, Serializable { public class FactoryTransformer<I, O> implements Transformer<I, O>, Serializable {
/** Serial version UID */ /** Serial version UID */
private static final long serialVersionUID = -6817674502475353160L; private static final long serialVersionUID = -6817674502475353160L;
/** The factory to wrap */ /** The factory to wrap */
private final Factory iFactory; private final Factory<? extends O> iFactory;
/** /**
* Factory method that performs validation. * Factory method that performs validation.
@ -44,11 +44,11 @@ public class FactoryTransformer implements Transformer, Serializable {
* @return the <code>factory</code> transformer * @return the <code>factory</code> transformer
* @throws IllegalArgumentException if the factory is null * @throws IllegalArgumentException if the factory is null
*/ */
public static Transformer getInstance(Factory factory) { public static <I, O> Transformer<I, O> getInstance(Factory<? extends O> factory) {
if (factory == null) { if (factory == null) {
throw new IllegalArgumentException("Factory must not be null"); throw new IllegalArgumentException("Factory must not be null");
} }
return new FactoryTransformer(factory); return new FactoryTransformer<I, O>(factory);
} }
/** /**
@ -57,7 +57,7 @@ public class FactoryTransformer implements Transformer, Serializable {
* *
* @param factory the factory to call, not null * @param factory the factory to call, not null
*/ */
public FactoryTransformer(Factory factory) { public FactoryTransformer(Factory<? extends O> factory) {
super(); super();
iFactory = factory; iFactory = factory;
} }
@ -69,7 +69,7 @@ public class FactoryTransformer implements Transformer, Serializable {
* @param input the input object to transform * @param input the input object to transform
* @return the transformed result * @return the transformed result
*/ */
public Object transform(Object input) { public O transform(I input) {
return iFactory.create(); return iFactory.create();
} }
@ -79,7 +79,7 @@ public class FactoryTransformer implements Transformer, Serializable {
* @return the factory * @return the factory
* @since Commons Collections 3.1 * @since Commons Collections 3.1
*/ */
public Factory getFactory() { public Factory<? extends O> getFactory() {
return iFactory; return iFactory;
} }

View File

@ -28,22 +28,34 @@ import org.apache.commons.collections.Predicate;
* *
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public final class FalsePredicate implements Predicate, Serializable { public final class FalsePredicate<T> implements Predicate<T>, Serializable {
/** Serial version UID */ /** Serial version UID */
private static final long serialVersionUID = 7533784454832764388L; private static final long serialVersionUID = 7533784454832764388L;
/** Singleton predicate instance */ /** Singleton predicate instance */
public static final Predicate INSTANCE = new FalsePredicate(); public static final Predicate<Object> INSTANCE = new FalsePredicate<Object>();
/** /**
* Factory returning the singleton instance. * Get a typed instance.
* *
* @return the singleton instance * @return the singleton instance
* @since Commons Collections 3.1 * @since Commons Collections 3.1
* @deprecated use {@link #falsePredicate()} instead.
*/ */
public static Predicate getInstance() { public static <T> Predicate<T> getInstance() {
return INSTANCE; return FalsePredicate.<T>falsePredicate();
}
/**
* Get a typed instance.
*
* @return the singleton instance
* @since Commons Collections 5
*/
@SuppressWarnings("unchecked")
public static <T> Predicate<T> falsePredicate() {
return (Predicate<T>) INSTANCE;
} }
/** /**
@ -55,11 +67,11 @@ public final class FalsePredicate implements Predicate, Serializable {
/** /**
* Evaluates the predicate returning false always. * Evaluates the predicate returning false always.
* *
* @param object the input object * @param object the input object
* @return false always * @return false always
*/ */
public boolean evaluate(Object object) { public boolean evaluate(T object) {
return false; return false;
} }

View File

@ -28,7 +28,7 @@ import org.apache.commons.collections.Closure;
* *
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public class ForClosure implements Closure, Serializable { public class ForClosure<E> implements Closure<E>, Serializable {
/** Serial version UID */ /** Serial version UID */
private static final long serialVersionUID = -1190120533393621674L; private static final long serialVersionUID = -1190120533393621674L;
@ -36,7 +36,7 @@ public class ForClosure implements Closure, Serializable {
/** The number of times to loop */ /** The number of times to loop */
private final int iCount; private final int iCount;
/** The closure to call */ /** The closure to call */
private final Closure iClosure; private final Closure<? super E> iClosure;
/** /**
* Factory method that performs validation. * Factory method that performs validation.
@ -48,14 +48,15 @@ public class ForClosure implements Closure, Serializable {
* @param closure the closure to execute, not null * @param closure the closure to execute, not null
* @return the <code>for</code> closure * @return the <code>for</code> closure
*/ */
public static Closure getInstance(int count, Closure closure) { @SuppressWarnings("unchecked")
public static <E> Closure<E> getInstance(int count, Closure<? super E> closure) {
if (count <= 0 || closure == null) { if (count <= 0 || closure == null) {
return NOPClosure.INSTANCE; return NOPClosure.<E>getInstance();
} }
if (count == 1) { if (count == 1) {
return closure; return (Closure<E>) closure;
} }
return new ForClosure(count, closure); return new ForClosure<E>(count, closure);
} }
/** /**
@ -65,7 +66,7 @@ public class ForClosure implements Closure, Serializable {
* @param count the number of times to execute the closure * @param count the number of times to execute the closure
* @param closure the closure to execute, not null * @param closure the closure to execute, not null
*/ */
public ForClosure(int count, Closure closure) { public ForClosure(int count, Closure<? super E> closure) {
super(); super();
iCount = count; iCount = count;
iClosure = closure; iClosure = closure;
@ -76,7 +77,7 @@ public class ForClosure implements Closure, Serializable {
* *
* @param input the input object * @param input the input object
*/ */
public void execute(Object input) { public void execute(E input) {
for (int i = 0; i < iCount; i++) { for (int i = 0; i < iCount; i++) {
iClosure.execute(input); iClosure.execute(input);
} }
@ -88,7 +89,7 @@ public class ForClosure implements Closure, Serializable {
* @return the closure * @return the closure
* @since Commons Collections 3.1 * @since Commons Collections 3.1
*/ */
public Closure getClosure() { public Closure<? super E> getClosure() {
return iClosure; return iClosure;
} }

View File

@ -29,36 +29,35 @@ import org.apache.commons.collections.Predicate;
* *
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public final class IdentityPredicate implements Predicate, Serializable { public final class IdentityPredicate<T> implements Predicate<T>, Serializable {
/** Serial version UID */ /** Serial version UID */
private static final long serialVersionUID = -89901658494523293L; private static final long serialVersionUID = -89901658494523293L;
/** The value to compare to */ /** The value to compare to */
private final Object iValue; private final T iValue;
/** /**
* Factory to create the identity predicate. * Factory to create the identity predicate.
* *
* @param object the object to compare to * @param object the object to compare to
* @return the predicate * @return the predicate
* @throws IllegalArgumentException if the predicate is null * @throws IllegalArgumentException if the predicate is null
*/ */
public static Predicate getInstance(Object object) { public static <T> Predicate<T> getInstance(T object) {
if (object == null) { if (object == null) {
return NullPredicate.INSTANCE; return NullPredicate.<T>nullPredicate();
} }
return new IdentityPredicate(object); return new IdentityPredicate<T>(object);
} }
/** /**
* Constructor that performs no validation. * Constructor that performs no validation.
* Use <code>getInstance</code> if you want that. * Use <code>getInstance</code> if you want that.
* *
* @param object the object to compare to * @param object the object to compare to
*/ */
public IdentityPredicate(Object object) { public IdentityPredicate(T object) {
super(); super();
iValue = object; iValue = object;
} }
@ -66,21 +65,21 @@ public final class IdentityPredicate implements Predicate, Serializable {
/** /**
* Evaluates the predicate returning true if the input object is identical to * Evaluates the predicate returning true if the input object is identical to
* the stored object. * the stored object.
* *
* @param object the input object * @param object the input object
* @return true if input is the same object as the stored value * @return true if input is the same object as the stored value
*/ */
public boolean evaluate(Object object) { public boolean evaluate(T object) {
return (iValue == object); return (iValue == object);
} }
/** /**
* Gets the value. * Gets the value.
* *
* @return the value * @return the value
* @since Commons Collections 3.1 * @since Commons Collections 3.1
*/ */
public Object getValue() { public T getValue() {
return iValue; return iValue;
} }

View File

@ -31,17 +31,17 @@ import org.apache.commons.collections.Predicate;
* @author Stephen Colebourne * @author Stephen Colebourne
* @author Matt Benson * @author Matt Benson
*/ */
public class IfClosure implements Closure, Serializable { public class IfClosure<E> implements Closure<E>, Serializable {
/** Serial version UID */ /** Serial version UID */
private static final long serialVersionUID = 3518477308466486130L; private static final long serialVersionUID = 3518477308466486130L;
/** The test */ /** The test */
private final Predicate iPredicate; private final Predicate<? super E> iPredicate;
/** The closure to use if true */ /** The closure to use if true */
private final Closure iTrueClosure; private final Closure<? super E> iTrueClosure;
/** The closure to use if false */ /** The closure to use if false */
private final Closure iFalseClosure; private final Closure<? super E> iFalseClosure;
/** /**
* Factory method that performs validation. * Factory method that performs validation.
@ -55,8 +55,8 @@ public class IfClosure implements Closure, Serializable {
* @throws IllegalArgumentException if either argument is null * @throws IllegalArgumentException if either argument is null
* @since Commons Collections 3.2 * @since Commons Collections 3.2
*/ */
public static Closure getInstance(Predicate predicate, Closure trueClosure) { public static <E> Closure<E> getInstance(Predicate<? super E> predicate, Closure<? super E> trueClosure) {
return getInstance(predicate, trueClosure, NOPClosure.INSTANCE); return IfClosure.<E>getInstance(predicate, trueClosure, NOPClosure.<E>getInstance());
} }
/** /**
@ -68,14 +68,14 @@ public class IfClosure implements Closure, Serializable {
* @return the <code>if</code> closure * @return the <code>if</code> closure
* @throws IllegalArgumentException if any argument is null * @throws IllegalArgumentException if any argument is null
*/ */
public static Closure getInstance(Predicate predicate, Closure trueClosure, Closure falseClosure) { public static <E> Closure<E> getInstance(Predicate<? super E> predicate, Closure<? super E> trueClosure, Closure<? super E> falseClosure) {
if (predicate == null) { if (predicate == null) {
throw new IllegalArgumentException("Predicate must not be null"); throw new IllegalArgumentException("Predicate must not be null");
} }
if (trueClosure == null || falseClosure == null) { if (trueClosure == null || falseClosure == null) {
throw new IllegalArgumentException("Closures must not be null"); throw new IllegalArgumentException("Closures must not be null");
} }
return new IfClosure(predicate, trueClosure, falseClosure); return new IfClosure<E>(predicate, trueClosure, falseClosure);
} }
/** /**
@ -89,7 +89,7 @@ public class IfClosure implements Closure, Serializable {
* @param trueClosure closure used if true, not null * @param trueClosure closure used if true, not null
* @since Commons Collections 3.2 * @since Commons Collections 3.2
*/ */
public IfClosure(Predicate predicate, Closure trueClosure) { public IfClosure(Predicate<? super E> predicate, Closure<? super E> trueClosure) {
this(predicate, trueClosure, NOPClosure.INSTANCE); this(predicate, trueClosure, NOPClosure.INSTANCE);
} }
@ -101,7 +101,7 @@ public class IfClosure implements Closure, Serializable {
* @param trueClosure closure used if true, not null * @param trueClosure closure used if true, not null
* @param falseClosure closure used if false, not null * @param falseClosure closure used if false, not null
*/ */
public IfClosure(Predicate predicate, Closure trueClosure, Closure falseClosure) { public IfClosure(Predicate<? super E> predicate, Closure<? super E> trueClosure, Closure<? super E> falseClosure) {
super(); super();
iPredicate = predicate; iPredicate = predicate;
iTrueClosure = trueClosure; iTrueClosure = trueClosure;
@ -113,8 +113,8 @@ public class IfClosure implements Closure, Serializable {
* *
* @param input the input object * @param input the input object
*/ */
public void execute(Object input) { public void execute(E input) {
if (iPredicate.evaluate(input) == true) { if (iPredicate.evaluate(input)) {
iTrueClosure.execute(input); iTrueClosure.execute(input);
} else { } else {
iFalseClosure.execute(input); iFalseClosure.execute(input);
@ -127,7 +127,7 @@ public class IfClosure implements Closure, Serializable {
* @return the predicate * @return the predicate
* @since Commons Collections 3.1 * @since Commons Collections 3.1
*/ */
public Predicate getPredicate() { public Predicate<? super E> getPredicate() {
return iPredicate; return iPredicate;
} }
@ -137,7 +137,7 @@ public class IfClosure implements Closure, Serializable {
* @return the closure * @return the closure
* @since Commons Collections 3.1 * @since Commons Collections 3.1
*/ */
public Closure getTrueClosure() { public Closure<? super E> getTrueClosure() {
return iTrueClosure; return iTrueClosure;
} }
@ -147,7 +147,7 @@ public class IfClosure implements Closure, Serializable {
* @return the closure * @return the closure
* @since Commons Collections 3.1 * @since Commons Collections 3.1
*/ */
public Closure getFalseClosure() { public Closure<? super E> getFalseClosure() {
return iFalseClosure; return iFalseClosure;
} }

View File

@ -29,22 +29,22 @@ import org.apache.commons.collections.Predicate;
* *
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public final class InstanceofPredicate implements Predicate, Serializable { public final class InstanceofPredicate implements Predicate<Object>, Serializable {
/** Serial version UID */ /** Serial version UID */
private static final long serialVersionUID = -6682656911025165584L; private static final long serialVersionUID = -6682656911025165584L;
/** The type to compare to */ /** The type to compare to */
private final Class iType; private final Class<?> iType;
/** /**
* Factory to create the identity predicate. * Factory to create the identity predicate.
* *
* @param type the type to check for, may not be null * @param type the type to check for, may not be null
* @return the predicate * @return the predicate
* @throws IllegalArgumentException if the class is null * @throws IllegalArgumentException if the class is null
*/ */
public static Predicate getInstance(Class type) { public static Predicate<Object> getInstance(Class<?> type) {
if (type == null) { if (type == null) {
throw new IllegalArgumentException("The type to check instanceof must not be null"); throw new IllegalArgumentException("The type to check instanceof must not be null");
} }
@ -54,17 +54,17 @@ public final class InstanceofPredicate implements Predicate, Serializable {
/** /**
* Constructor that performs no validation. * Constructor that performs no validation.
* Use <code>getInstance</code> if you want that. * Use <code>getInstance</code> if you want that.
* *
* @param type the type to check for * @param type the type to check for
*/ */
public InstanceofPredicate(Class type) { public InstanceofPredicate(Class<?> type) {
super(); super();
iType = type; iType = type;
} }
/** /**
* Evaluates the predicate returning true if the input object is of the correct type. * Evaluates the predicate returning true if the input object is of the correct type.
* *
* @param object the input object * @param object the input object
* @return true if input is of stored type * @return true if input is of stored type
*/ */
@ -74,11 +74,11 @@ public final class InstanceofPredicate implements Predicate, Serializable {
/** /**
* Gets the type to compare to. * Gets the type to compare to.
* *
* @return the type * @return the type
* @since Commons Collections 3.1 * @since Commons Collections 3.1
*/ */
public Class getType() { public Class<?> getType() {
return iType; return iType;
} }

View File

@ -31,27 +31,36 @@ import org.apache.commons.collections.Transformer;
* *
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public class InstantiateTransformer implements Transformer, Serializable { public class InstantiateTransformer<T> implements Transformer<Class<? extends T>, T>, Serializable {
/** The serial version */ /** The serial version */
private static final long serialVersionUID = 3786388740793356347L; private static final long serialVersionUID = 3786388740793356347L;
/** Singleton instance that uses the no arg constructor */ /** Singleton instance that uses the no arg constructor */
public static final Transformer NO_ARG_INSTANCE = new InstantiateTransformer(); public static final Transformer<Class<?>, ?> NO_ARG_INSTANCE = new InstantiateTransformer<Object>();
/** The constructor parameter types */ /** The constructor parameter types */
private final Class[] iParamTypes; private final Class<?>[] iParamTypes;
/** The constructor arguments */ /** The constructor arguments */
private final Object[] iArgs; private final Object[] iArgs;
/**
* Get a typed no-arg instance.
* @param <T>
* @return Transformer<Class<? extends T>, T>
*/
public static <T> Transformer<Class<? extends T>, T> getInstance() {
return new InstantiateTransformer<T>();
}
/** /**
* Transformer method that performs validation. * Transformer method that performs validation.
* *
* @param paramTypes the constructor parameter types * @param paramTypes the constructor parameter types
* @param args the constructor arguments * @param args the constructor arguments
* @return an instantiate transformer * @return an instantiate transformer
*/ */
public static Transformer getInstance(Class[] paramTypes, Object[] args) { public static <T> Transformer<Class<? extends T>, T> getInstance(Class<?>[] paramTypes, Object[] args) {
if (((paramTypes == null) && (args != null)) if (((paramTypes == null) && (args != null))
|| ((paramTypes != null) && (args == null)) || ((paramTypes != null) && (args == null))
|| ((paramTypes != null) && (args != null) && (paramTypes.length != args.length))) { || ((paramTypes != null) && (args != null) && (paramTypes.length != args.length))) {
@ -59,12 +68,11 @@ public class InstantiateTransformer implements Transformer, Serializable {
} }
if (paramTypes == null || paramTypes.length == 0) { if (paramTypes == null || paramTypes.length == 0) {
return NO_ARG_INSTANCE; return new InstantiateTransformer<T>();
} else {
paramTypes = (Class[]) paramTypes.clone();
args = (Object[]) args.clone();
} }
return new InstantiateTransformer(paramTypes, args); paramTypes = (Class[]) paramTypes.clone();
args = (Object[]) args.clone();
return new InstantiateTransformer<T>(paramTypes, args);
} }
/** /**
@ -79,11 +87,11 @@ public class InstantiateTransformer implements Transformer, Serializable {
/** /**
* Constructor that performs no validation. * Constructor that performs no validation.
* Use <code>getInstance</code> if you want that. * Use <code>getInstance</code> if you want that.
* *
* @param paramTypes the constructor parameter types, not cloned * @param paramTypes the constructor parameter types, not cloned
* @param args the constructor arguments, not cloned * @param args the constructor arguments, not cloned
*/ */
public InstantiateTransformer(Class[] paramTypes, Object[] args) { public InstantiateTransformer(Class<?>[] paramTypes, Object[] args) {
super(); super();
iParamTypes = paramTypes; iParamTypes = paramTypes;
iArgs = args; iArgs = args;
@ -91,20 +99,19 @@ public class InstantiateTransformer implements Transformer, Serializable {
/** /**
* Transforms the input Class object to a result by instantiation. * Transforms the input Class object to a result by instantiation.
* *
* @param input the input object to transform * @param input the input object to transform
* @return the transformed result * @return the transformed result
*/ */
public Object transform(Object input) { public T transform(Class<? extends T> input) {
try { try {
if (input instanceof Class == false) { if (input instanceof Class == false) {
throw new FunctorException( throw new FunctorException(
"InstantiateTransformer: Input object was not an instanceof Class, it was a " "InstantiateTransformer: Input object was not an instanceof Class, it was a "
+ (input == null ? "null object" : input.getClass().getName())); + (input == null ? "null object" : input.getClass().getName()));
} }
Constructor con = ((Class) input).getConstructor(iParamTypes); Constructor<? extends T> con = input.getConstructor(iParamTypes);
return con.newInstance(iArgs); return con.newInstance(iArgs);
} catch (NoSuchMethodException ex) { } catch (NoSuchMethodException ex) {
throw new FunctorException("InstantiateTransformer: The constructor must exist and be public "); throw new FunctorException("InstantiateTransformer: The constructor must exist and be public ");
} catch (InstantiationException ex) { } catch (InstantiationException ex) {

View File

@ -31,7 +31,7 @@ import org.apache.commons.collections.Transformer;
* *
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public class InvokerTransformer implements Transformer, Serializable { public class InvokerTransformer<I, O> implements Transformer<I, O>, Serializable {
/** The serial version */ /** The serial version */
private static final long serialVersionUID = -8653385846894047688L; private static final long serialVersionUID = -8653385846894047688L;
@ -39,7 +39,7 @@ public class InvokerTransformer implements Transformer, Serializable {
/** The method name to call */ /** The method name to call */
private final String iMethodName; private final String iMethodName;
/** The array of reflection parameter types */ /** The array of reflection parameter types */
private final Class[] iParamTypes; private final Class<?>[] iParamTypes;
/** The array of reflection arguments */ /** The array of reflection arguments */
private final Object[] iArgs; private final Object[] iArgs;
@ -50,11 +50,11 @@ public class InvokerTransformer implements Transformer, Serializable {
* @return an invoker transformer * @return an invoker transformer
* @since Commons Collections 3.1 * @since Commons Collections 3.1
*/ */
public static Transformer getInstance(String methodName) { public static <I, O> Transformer<I, O> getInstance(String methodName) {
if (methodName == null) { if (methodName == null) {
throw new IllegalArgumentException("The method to invoke must not be null"); throw new IllegalArgumentException("The method to invoke must not be null");
} }
return new InvokerTransformer(methodName); return new InvokerTransformer<I, O>(methodName);
} }
/** /**
@ -65,7 +65,7 @@ public class InvokerTransformer implements Transformer, Serializable {
* @param args the arguments to pass to the method * @param args the arguments to pass to the method
* @return an invoker transformer * @return an invoker transformer
*/ */
public static Transformer getInstance(String methodName, Class[] paramTypes, Object[] args) { public static <I, O> Transformer<I, O> getInstance(String methodName, Class<?>[] paramTypes, Object[] args) {
if (methodName == null) { if (methodName == null) {
throw new IllegalArgumentException("The method to invoke must not be null"); throw new IllegalArgumentException("The method to invoke must not be null");
} }
@ -75,11 +75,11 @@ public class InvokerTransformer implements Transformer, Serializable {
throw new IllegalArgumentException("The parameter types must match the arguments"); throw new IllegalArgumentException("The parameter types must match the arguments");
} }
if (paramTypes == null || paramTypes.length == 0) { if (paramTypes == null || paramTypes.length == 0) {
return new InvokerTransformer(methodName); return new InvokerTransformer<I, O>(methodName);
} else { } else {
paramTypes = (Class[]) paramTypes.clone(); paramTypes = (Class[]) paramTypes.clone();
args = (Object[]) args.clone(); args = (Object[]) args.clone();
return new InvokerTransformer(methodName, paramTypes, args); return new InvokerTransformer<I, O>(methodName, paramTypes, args);
} }
} }
@ -103,7 +103,7 @@ public class InvokerTransformer implements Transformer, Serializable {
* @param paramTypes the constructor parameter types, not cloned * @param paramTypes the constructor parameter types, not cloned
* @param args the constructor arguments, not cloned * @param args the constructor arguments, not cloned
*/ */
public InvokerTransformer(String methodName, Class[] paramTypes, Object[] args) { public InvokerTransformer(String methodName, Class<?>[] paramTypes, Object[] args) {
super(); super();
iMethodName = methodName; iMethodName = methodName;
iParamTypes = paramTypes; iParamTypes = paramTypes;
@ -116,15 +116,15 @@ public class InvokerTransformer implements Transformer, Serializable {
* @param input the input object to transform * @param input the input object to transform
* @return the transformed result, null if null input * @return the transformed result, null if null input
*/ */
public Object transform(Object input) { @SuppressWarnings("unchecked")
public O transform(Object input) {
if (input == null) { if (input == null) {
return null; return null;
} }
try { try {
Class cls = input.getClass(); Class<?> cls = input.getClass();
Method method = cls.getMethod(iMethodName, iParamTypes); Method method = cls.getMethod(iMethodName, iParamTypes);
return method.invoke(input, iArgs); return (O) method.invoke(input, iArgs);
} catch (NoSuchMethodException ex) { } catch (NoSuchMethodException ex) {
throw new FunctorException("InvokerTransformer: The method '" + iMethodName + "' on '" + input.getClass() + "' does not exist"); throw new FunctorException("InvokerTransformer: The method '" + iMethodName + "' on '" + input.getClass() + "' does not exist");
} catch (IllegalAccessException ex) { } catch (IllegalAccessException ex) {

View File

@ -30,57 +30,57 @@ import org.apache.commons.collections.Transformer;
* *
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public final class MapTransformer implements Transformer, Serializable { public final class MapTransformer<I, O> implements Transformer<I, O>, Serializable {
/** Serial version UID */ /** Serial version UID */
private static final long serialVersionUID = 862391807045468939L; private static final long serialVersionUID = 862391807045468939L;
/** The map of data to lookup in */ /** The map of data to lookup in */
private final Map iMap; private final Map<? super I, ? extends O> iMap;
/** /**
* Factory to create the transformer. * Factory to create the transformer.
* <p> * <p>
* If the map is null, a transformer that always returns null is returned. * If the map is null, a transformer that always returns null is returned.
* *
* @param map the map, not cloned * @param map the map, not cloned
* @return the transformer * @return the transformer
*/ */
public static Transformer getInstance(Map map) { public static <I, O> Transformer<I, O> getInstance(Map<? super I, ? extends O> map) {
if (map == null) { if (map == null) {
return ConstantTransformer.NULL_INSTANCE; return ConstantTransformer.<I, O>getNullInstance();
} }
return new MapTransformer(map); return new MapTransformer<I, O>(map);
} }
/** /**
* Constructor that performs no validation. * Constructor that performs no validation.
* Use <code>getInstance</code> if you want that. * Use <code>getInstance</code> if you want that.
* *
* @param map the map to use for lookup, not cloned * @param map the map to use for lookup, not cloned
*/ */
private MapTransformer(Map map) { private MapTransformer(Map<? super I, ? extends O> map) {
super(); super();
iMap = map; iMap = map;
} }
/** /**
* Transforms the input to result by looking it up in a <code>Map</code>. * Transforms the input to result by looking it up in a <code>Map</code>.
* *
* @param input the input object to transform * @param input the input object to transform
* @return the transformed result * @return the transformed result
*/ */
public Object transform(Object input) { public O transform(I input) {
return iMap.get(input); return iMap.get(input);
} }
/** /**
* Gets the map to lookup in. * Gets the map to lookup in.
* *
* @return the map * @return the map
* @since Commons Collections 3.1 * @since Commons Collections 3.1
*/ */
public Map getMap() { public Map<? super I, ? extends O> getMap() {
return iMap; return iMap;
} }

View File

@ -28,13 +28,13 @@ import org.apache.commons.collections.Closure;
* *
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public class NOPClosure implements Closure, Serializable { public class NOPClosure<E> implements Closure<E>, Serializable {
/** Serial version UID */ /** Serial version UID */
private static final long serialVersionUID = 3518477308466486130L; private static final long serialVersionUID = 3518477308466486130L;
/** Singleton predicate instance */ /** Singleton predicate instance */
public static final Closure INSTANCE = new NOPClosure(); public static final Closure<Object> INSTANCE = new NOPClosure<Object>();
/** /**
* Factory returning the singleton instance. * Factory returning the singleton instance.
@ -42,8 +42,9 @@ public class NOPClosure implements Closure, Serializable {
* @return the singleton instance * @return the singleton instance
* @since Commons Collections 3.1 * @since Commons Collections 3.1
*/ */
public static Closure getInstance() { @SuppressWarnings("unchecked")
return INSTANCE; public static <E> Closure<E> getInstance() {
return (Closure<E>) INSTANCE;
} }
/** /**
@ -58,8 +59,23 @@ public class NOPClosure implements Closure, Serializable {
* *
* @param input the input object * @param input the input object
*/ */
public void execute(Object input) { public void execute(E input) {
// do nothing // do nothing
} }
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object arg0) {
return arg0.hashCode() == this.hashCode();
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
return System.identityHashCode(INSTANCE);
}
} }

View File

@ -28,13 +28,13 @@ import org.apache.commons.collections.Transformer;
* *
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public class NOPTransformer implements Transformer, Serializable { public class NOPTransformer<T> implements Transformer<T, T>, Serializable {
/** Serial version UID */ /** Serial version UID */
private static final long serialVersionUID = 2133891748318574490L; private static final long serialVersionUID = 2133891748318574490L;
/** Singleton predicate instance */ /** Singleton predicate instance */
public static final Transformer INSTANCE = new NOPTransformer(); public static final Transformer<Object, Object> INSTANCE = new NOPTransformer<Object>();
/** /**
* Factory returning the singleton instance. * Factory returning the singleton instance.
@ -42,8 +42,9 @@ public class NOPTransformer implements Transformer, Serializable {
* @return the singleton instance * @return the singleton instance
* @since Commons Collections 3.1 * @since Commons Collections 3.1
*/ */
public static Transformer getInstance() { @SuppressWarnings("unchecked")
return INSTANCE; public static <T> Transformer<T, T> getInstance() {
return (Transformer<T, T>) INSTANCE;
} }
/** /**
@ -59,7 +60,7 @@ public class NOPTransformer implements Transformer, Serializable {
* @param input the input object to transform * @param input the input object to transform
* @return the transformed result which is the input * @return the transformed result which is the input
*/ */
public Object transform(Object input) { public T transform(T input) {
return input; return input;
} }

View File

@ -35,14 +35,14 @@ import org.apache.commons.collections.Predicate;
* @author Stephen Colebourne * @author Stephen Colebourne
* @author Matt Benson * @author Matt Benson
*/ */
public final class NonePredicate implements Predicate, PredicateDecorator, Serializable { public final class NonePredicate<T> implements Predicate<T>, PredicateDecorator<T>, Serializable {
/** Serial version UID */ /** Serial version UID */
private static final long serialVersionUID = 2007613066565892961L; private static final long serialVersionUID = 2007613066565892961L;
/** The array of predicates to call */ /** The array of predicates to call */
private final Predicate[] iPredicates; private final Predicate<? super T>[] iPredicates;
/** /**
* Factory to create the predicate. * Factory to create the predicate.
* <p> * <p>
@ -53,13 +53,13 @@ public final class NonePredicate implements Predicate, PredicateDecorator, Seria
* @throws IllegalArgumentException if the predicates array is null * @throws IllegalArgumentException if the predicates array is null
* @throws IllegalArgumentException if any predicate in the array is null * @throws IllegalArgumentException if any predicate in the array is null
*/ */
public static Predicate getInstance(Predicate[] predicates) { public static <T> Predicate<T> getInstance(Predicate<? super T>[] predicates) {
FunctorUtils.validate(predicates); FunctorUtils.validate(predicates);
if (predicates.length == 0) { if (predicates.length == 0) {
return TruePredicate.INSTANCE; return TruePredicate.<T>truePredicate();
} }
predicates = FunctorUtils.copy(predicates); predicates = FunctorUtils.copy(predicates);
return new NonePredicate(predicates); return new NonePredicate<T>(predicates);
} }
/** /**
@ -72,32 +72,32 @@ public final class NonePredicate implements Predicate, PredicateDecorator, Seria
* @throws IllegalArgumentException if the predicates array is null * @throws IllegalArgumentException if the predicates array is null
* @throws IllegalArgumentException if any predicate in the array is null * @throws IllegalArgumentException if any predicate in the array is null
*/ */
public static Predicate getInstance(Collection predicates) { public static <T> Predicate<T> getInstance(Collection<? extends Predicate<T>> predicates) {
Predicate[] preds = FunctorUtils.validate(predicates); Predicate<? super T>[] preds = FunctorUtils.validate(predicates);
if (preds.length == 0) { if (preds.length == 0) {
return TruePredicate.INSTANCE; return TruePredicate.<T>truePredicate();
} }
return new NonePredicate(preds); return new NonePredicate<T>(preds);
} }
/** /**
* Constructor that performs no validation. * Constructor that performs no validation.
* Use <code>getInstance</code> if you want that. * Use <code>getInstance</code> if you want that.
* *
* @param predicates the predicates to check, not cloned, not null * @param predicates the predicates to check, not cloned, not null
*/ */
public NonePredicate(Predicate[] predicates) { public NonePredicate(Predicate<? super T>[] predicates) {
super(); super();
iPredicates = predicates; iPredicates = predicates;
} }
/** /**
* Evaluates the predicate returning false if any stored predicate returns false. * Evaluates the predicate returning false if any stored predicate returns false.
* *
* @param object the input object * @param object the input object
* @return true if none of decorated predicates return true * @return true if none of decorated predicates return true
*/ */
public boolean evaluate(Object object) { public boolean evaluate(T object) {
for (int i = 0; i < iPredicates.length; i++) { for (int i = 0; i < iPredicates.length; i++) {
if (iPredicates[i].evaluate(object)) { if (iPredicates[i].evaluate(object)) {
return false; return false;
@ -108,11 +108,11 @@ public final class NonePredicate implements Predicate, PredicateDecorator, Seria
/** /**
* Gets the predicates, do not modify the array. * Gets the predicates, do not modify the array.
* *
* @return the predicates * @return the predicates
* @since Commons Collections 3.1 * @since Commons Collections 3.1
*/ */
public Predicate[] getPredicates() { public Predicate<? super T>[] getPredicates() {
return iPredicates; return iPredicates;
} }

View File

@ -28,13 +28,13 @@ import org.apache.commons.collections.Predicate;
* *
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public final class NotNullPredicate implements Predicate, Serializable { public final class NotNullPredicate<T> implements Predicate<T>, Serializable {
/** Serial version UID */ /** Serial version UID */
private static final long serialVersionUID = 7533784454832764388L; private static final long serialVersionUID = 7533784454832764388L;
/** Singleton predicate instance */ /** Singleton predicate instance */
public static final Predicate INSTANCE = new NotNullPredicate(); public static final Predicate<Object> INSTANCE = new NotNullPredicate<Object>();
/** /**
* Factory returning the singleton instance. * Factory returning the singleton instance.
@ -42,8 +42,9 @@ public final class NotNullPredicate implements Predicate, Serializable {
* @return the singleton instance * @return the singleton instance
* @since Commons Collections 3.1 * @since Commons Collections 3.1
*/ */
public static Predicate getInstance() { @SuppressWarnings("unchecked")
return INSTANCE; public static <T> Predicate<T> getInstance() {
return (Predicate<T>) INSTANCE;
} }
/** /**
@ -59,7 +60,7 @@ public final class NotNullPredicate implements Predicate, Serializable {
* @param object the object to evaluate * @param object the object to evaluate
* @return true if not null * @return true if not null
*/ */
public boolean evaluate(Object object) { public boolean evaluate(T object) {
return (object != null); return (object != null);
} }

View File

@ -28,13 +28,13 @@ import org.apache.commons.collections.Predicate;
* *
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public final class NotPredicate implements Predicate, PredicateDecorator, Serializable { public final class NotPredicate<T> implements Predicate<T>, PredicateDecorator<T>, Serializable {
/** Serial version UID */ /** Serial version UID */
private static final long serialVersionUID = -2654603322338049674L; private static final long serialVersionUID = -2654603322338049674L;
/** The predicate to decorate */ /** The predicate to decorate */
private final Predicate iPredicate; private final Predicate<? super T> iPredicate;
/** /**
* Factory to create the not predicate. * Factory to create the not predicate.
@ -43,11 +43,11 @@ public final class NotPredicate implements Predicate, PredicateDecorator, Serial
* @return the predicate * @return the predicate
* @throws IllegalArgumentException if the predicate is null * @throws IllegalArgumentException if the predicate is null
*/ */
public static Predicate getInstance(Predicate predicate) { public static <T> Predicate<T> getInstance(Predicate<? super T> predicate) {
if (predicate == null) { if (predicate == null) {
throw new IllegalArgumentException("Predicate must not be null"); throw new IllegalArgumentException("Predicate must not be null");
} }
return new NotPredicate(predicate); return new NotPredicate<T>(predicate);
} }
/** /**
@ -56,7 +56,7 @@ public final class NotPredicate implements Predicate, PredicateDecorator, Serial
* *
* @param predicate the predicate to call after the null check * @param predicate the predicate to call after the null check
*/ */
public NotPredicate(Predicate predicate) { public NotPredicate(Predicate<? super T> predicate) {
super(); super();
iPredicate = predicate; iPredicate = predicate;
} }
@ -67,7 +67,7 @@ public final class NotPredicate implements Predicate, PredicateDecorator, Serial
* @param object the input object * @param object the input object
* @return true if predicate returns false * @return true if predicate returns false
*/ */
public boolean evaluate(Object object) { public boolean evaluate(T object) {
return !(iPredicate.evaluate(object)); return !(iPredicate.evaluate(object));
} }
@ -77,7 +77,8 @@ public final class NotPredicate implements Predicate, PredicateDecorator, Serial
* @return the predicate as the only element in an array * @return the predicate as the only element in an array
* @since Commons Collections 3.1 * @since Commons Collections 3.1
*/ */
public Predicate[] getPredicates() { @SuppressWarnings("unchecked")
public Predicate<? super T>[] getPredicates() {
return new Predicate[] {iPredicate}; return new Predicate[] {iPredicate};
} }

View File

@ -29,13 +29,13 @@ import org.apache.commons.collections.Predicate;
* *
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public final class NullIsExceptionPredicate implements Predicate, PredicateDecorator, Serializable { public final class NullIsExceptionPredicate<T> implements Predicate<T>, PredicateDecorator<T>, Serializable {
/** Serial version UID */ /** Serial version UID */
private static final long serialVersionUID = 3243449850504576071L; private static final long serialVersionUID = 3243449850504576071L;
/** The predicate to decorate */ /** The predicate to decorate */
private final Predicate iPredicate; private final Predicate<? super T> iPredicate;
/** /**
* Factory to create the null exception predicate. * Factory to create the null exception predicate.
@ -44,11 +44,11 @@ public final class NullIsExceptionPredicate implements Predicate, PredicateDecor
* @return the predicate * @return the predicate
* @throws IllegalArgumentException if the predicate is null * @throws IllegalArgumentException if the predicate is null
*/ */
public static Predicate getInstance(Predicate predicate) { public static <T> Predicate<T> getInstance(Predicate<? super T> predicate) {
if (predicate == null) { if (predicate == null) {
throw new IllegalArgumentException("Predicate must not be null"); throw new IllegalArgumentException("Predicate must not be null");
} }
return new NullIsExceptionPredicate(predicate); return new NullIsExceptionPredicate<T>(predicate);
} }
/** /**
@ -57,7 +57,7 @@ public final class NullIsExceptionPredicate implements Predicate, PredicateDecor
* *
* @param predicate the predicate to call after the null check * @param predicate the predicate to call after the null check
*/ */
public NullIsExceptionPredicate(Predicate predicate) { public NullIsExceptionPredicate(Predicate<? super T> predicate) {
super(); super();
iPredicate = predicate; iPredicate = predicate;
} }
@ -70,7 +70,7 @@ public final class NullIsExceptionPredicate implements Predicate, PredicateDecor
* @return true if decorated predicate returns true * @return true if decorated predicate returns true
* @throws FunctorException if input is null * @throws FunctorException if input is null
*/ */
public boolean evaluate(Object object) { public boolean evaluate(T object) {
if (object == null) { if (object == null) {
throw new FunctorException("Input Object must not be null"); throw new FunctorException("Input Object must not be null");
} }
@ -83,8 +83,9 @@ public final class NullIsExceptionPredicate implements Predicate, PredicateDecor
* @return the predicate as the only element in an array * @return the predicate as the only element in an array
* @since Commons Collections 3.1 * @since Commons Collections 3.1
*/ */
public Predicate[] getPredicates() { @SuppressWarnings("unchecked")
return new Predicate[] {iPredicate}; public Predicate<? super T>[] getPredicates() {
return new Predicate[] { iPredicate };
} }
} }

View File

@ -28,35 +28,35 @@ import org.apache.commons.collections.Predicate;
* *
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public final class NullIsFalsePredicate implements Predicate, PredicateDecorator, Serializable { public final class NullIsFalsePredicate<T> implements Predicate<T>, PredicateDecorator<T>, Serializable {
/** Serial version UID */ /** Serial version UID */
private static final long serialVersionUID = -2997501534564735525L; private static final long serialVersionUID = -2997501534564735525L;
/** The predicate to decorate */ /** The predicate to decorate */
private final Predicate iPredicate; private final Predicate<? super T> iPredicate;
/** /**
* Factory to create the null false predicate. * Factory to create the null false predicate.
* *
* @param predicate the predicate to decorate, not null * @param predicate the predicate to decorate, not null
* @return the predicate * @return the predicate
* @throws IllegalArgumentException if the predicate is null * @throws IllegalArgumentException if the predicate is null
*/ */
public static Predicate getInstance(Predicate predicate) { public static <T> Predicate<T> getInstance(Predicate<? super T> predicate) {
if (predicate == null) { if (predicate == null) {
throw new IllegalArgumentException("Predicate must not be null"); throw new IllegalArgumentException("Predicate must not be null");
} }
return new NullIsFalsePredicate(predicate); return new NullIsFalsePredicate<T>(predicate);
} }
/** /**
* Constructor that performs no validation. * Constructor that performs no validation.
* Use <code>getInstance</code> if you want that. * Use <code>getInstance</code> if you want that.
* *
* @param predicate the predicate to call after the null check * @param predicate the predicate to call after the null check
*/ */
public NullIsFalsePredicate(Predicate predicate) { public NullIsFalsePredicate(Predicate<? super T> predicate) {
super(); super();
iPredicate = predicate; iPredicate = predicate;
} }
@ -64,11 +64,11 @@ public final class NullIsFalsePredicate implements Predicate, PredicateDecorator
/** /**
* Evaluates the predicate returning the result of the decorated predicate * Evaluates the predicate returning the result of the decorated predicate
* once a null check is performed. * once a null check is performed.
* *
* @param object the input object * @param object the input object
* @return true if decorated predicate returns true, false if input is null * @return true if decorated predicate returns true, false if input is null
*/ */
public boolean evaluate(Object object) { public boolean evaluate(T object) {
if (object == null) { if (object == null) {
return false; return false;
} }
@ -77,12 +77,13 @@ public final class NullIsFalsePredicate implements Predicate, PredicateDecorator
/** /**
* Gets the predicate being decorated. * Gets the predicate being decorated.
* *
* @return the predicate as the only element in an array * @return the predicate as the only element in an array
* @since Commons Collections 3.1 * @since Commons Collections 3.1
*/ */
public Predicate[] getPredicates() { @SuppressWarnings("unchecked")
return new Predicate[] {iPredicate}; public Predicate<? super T>[] getPredicates() {
return new Predicate[] { iPredicate };
} }
} }

View File

@ -28,13 +28,13 @@ import org.apache.commons.collections.Predicate;
* *
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public final class NullIsTruePredicate implements Predicate, PredicateDecorator, Serializable { public final class NullIsTruePredicate<T> implements Predicate<T>, PredicateDecorator<T>, Serializable {
/** Serial version UID */ /** Serial version UID */
private static final long serialVersionUID = -7625133768987126273L; private static final long serialVersionUID = -7625133768987126273L;
/** The predicate to decorate */ /** The predicate to decorate */
private final Predicate iPredicate; private final Predicate<? super T> iPredicate;
/** /**
* Factory to create the null true predicate. * Factory to create the null true predicate.
@ -43,11 +43,11 @@ public final class NullIsTruePredicate implements Predicate, PredicateDecorator,
* @return the predicate * @return the predicate
* @throws IllegalArgumentException if the predicate is null * @throws IllegalArgumentException if the predicate is null
*/ */
public static Predicate getInstance(Predicate predicate) { public static <T> Predicate<T> getInstance(Predicate<? super T> predicate) {
if (predicate == null) { if (predicate == null) {
throw new IllegalArgumentException("Predicate must not be null"); throw new IllegalArgumentException("Predicate must not be null");
} }
return new NullIsTruePredicate(predicate); return new NullIsTruePredicate<T>(predicate);
} }
/** /**
@ -56,7 +56,7 @@ public final class NullIsTruePredicate implements Predicate, PredicateDecorator,
* *
* @param predicate the predicate to call after the null check * @param predicate the predicate to call after the null check
*/ */
public NullIsTruePredicate(Predicate predicate) { public NullIsTruePredicate(Predicate<? super T> predicate) {
super(); super();
iPredicate = predicate; iPredicate = predicate;
} }
@ -68,7 +68,7 @@ public final class NullIsTruePredicate implements Predicate, PredicateDecorator,
* @param object the input object * @param object the input object
* @return true if decorated predicate returns true or input is null * @return true if decorated predicate returns true or input is null
*/ */
public boolean evaluate(Object object) { public boolean evaluate(T object) {
if (object == null) { if (object == null) {
return true; return true;
} }
@ -81,8 +81,9 @@ public final class NullIsTruePredicate implements Predicate, PredicateDecorator,
* @return the predicate as the only element in an array * @return the predicate as the only element in an array
* @since Commons Collections 3.1 * @since Commons Collections 3.1
*/ */
public Predicate[] getPredicates() { @SuppressWarnings("unchecked")
return new Predicate[] {iPredicate}; public Predicate<? super T>[] getPredicates() {
return new Predicate[] { iPredicate };
} }
} }

View File

@ -35,13 +35,13 @@ import org.apache.commons.collections.Predicate;
* @author Stephen Colebourne * @author Stephen Colebourne
* @author Matt Benson * @author Matt Benson
*/ */
public final class OnePredicate implements Predicate, PredicateDecorator, Serializable { public final class OnePredicate<T> implements Predicate<T>, PredicateDecorator<T>, Serializable {
/** Serial version UID */ /** Serial version UID */
private static final long serialVersionUID = -8125389089924745785L; private static final long serialVersionUID = -8125389089924745785L;
/** The array of predicates to call */ /** The array of predicates to call */
private final Predicate[] iPredicates; private final Predicate<? super T>[] iPredicates;
/** /**
* Factory to create the predicate. * Factory to create the predicate.
@ -54,16 +54,17 @@ public final class OnePredicate implements Predicate, PredicateDecorator, Serial
* @throws IllegalArgumentException if the predicates array is null * @throws IllegalArgumentException if the predicates array is null
* @throws IllegalArgumentException if any predicate in the array is null * @throws IllegalArgumentException if any predicate in the array is null
*/ */
public static Predicate getInstance(Predicate[] predicates) { @SuppressWarnings("unchecked")
public static <T> Predicate<T> getInstance(Predicate<? super T>[] predicates) {
FunctorUtils.validate(predicates); FunctorUtils.validate(predicates);
if (predicates.length == 0) { if (predicates.length == 0) {
return FalsePredicate.INSTANCE; return FalsePredicate.<T>falsePredicate();
} }
if (predicates.length == 1) { if (predicates.length == 1) {
return predicates[0]; return (Predicate<T>) predicates[0];
} }
predicates = FunctorUtils.copy(predicates); predicates = FunctorUtils.copy(predicates);
return new OnePredicate(predicates); return new OnePredicate<T>(predicates);
} }
/** /**
@ -74,9 +75,9 @@ public final class OnePredicate implements Predicate, PredicateDecorator, Serial
* @throws IllegalArgumentException if the predicates array is null * @throws IllegalArgumentException if the predicates array is null
* @throws IllegalArgumentException if any predicate in the array is null * @throws IllegalArgumentException if any predicate in the array is null
*/ */
public static Predicate getInstance(Collection predicates) { public static <T> Predicate<T> getInstance(Collection<? extends Predicate<T>> predicates) {
Predicate[] preds = FunctorUtils.validate(predicates); Predicate<? super T>[] preds = FunctorUtils.validate(predicates);
return new OnePredicate(preds); return new OnePredicate<T>(preds);
} }
/** /**
@ -85,7 +86,7 @@ public final class OnePredicate implements Predicate, PredicateDecorator, Serial
* *
* @param predicates the predicates to check, not cloned, not null * @param predicates the predicates to check, not cloned, not null
*/ */
public OnePredicate(Predicate[] predicates) { public OnePredicate(Predicate<? super T>[] predicates) {
super(); super();
iPredicates = predicates; iPredicates = predicates;
} }
@ -97,7 +98,7 @@ public final class OnePredicate implements Predicate, PredicateDecorator, Serial
* @param object the input object * @param object the input object
* @return true if only one decorated predicate returns true * @return true if only one decorated predicate returns true
*/ */
public boolean evaluate(Object object) { public boolean evaluate(T object) {
boolean match = false; boolean match = false;
for (int i = 0; i < iPredicates.length; i++) { for (int i = 0; i < iPredicates.length; i++) {
if (iPredicates[i].evaluate(object)) { if (iPredicates[i].evaluate(object)) {
@ -116,7 +117,7 @@ public final class OnePredicate implements Predicate, PredicateDecorator, Serial
* @return the predicates * @return the predicates
* @since Commons Collections 3.1 * @since Commons Collections 3.1
*/ */
public Predicate[] getPredicates() { public Predicate<? super T>[] getPredicates() {
return iPredicates; return iPredicates;
} }

View File

@ -28,39 +28,39 @@ import org.apache.commons.collections.Predicate;
* *
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public final class OrPredicate implements Predicate, PredicateDecorator, Serializable { public final class OrPredicate<T> implements Predicate<T>, PredicateDecorator<T>, Serializable {
/** Serial version UID */ /** Serial version UID */
private static final long serialVersionUID = -8791518325735182855L; private static final long serialVersionUID = -8791518325735182855L;
/** The array of predicates to call */ /** The array of predicates to call */
private final Predicate iPredicate1; private final Predicate<? super T> iPredicate1;
/** The array of predicates to call */ /** The array of predicates to call */
private final Predicate iPredicate2; private final Predicate<? super T> iPredicate2;
/** /**
* Factory to create the predicate. * Factory to create the predicate.
* *
* @param predicate1 the first predicate to check, not null * @param predicate1 the first predicate to check, not null
* @param predicate2 the second predicate to check, not null * @param predicate2 the second predicate to check, not null
* @return the <code>and</code> predicate * @return the <code>and</code> predicate
* @throws IllegalArgumentException if either predicate is null * @throws IllegalArgumentException if either predicate is null
*/ */
public static Predicate getInstance(Predicate predicate1, Predicate predicate2) { public static <T> Predicate<T> getInstance(Predicate<? super T> predicate1, Predicate<? super T> predicate2) {
if (predicate1 == null || predicate2 == null) { if (predicate1 == null || predicate2 == null) {
throw new IllegalArgumentException("Predicate must not be null"); throw new IllegalArgumentException("Predicate must not be null");
} }
return new OrPredicate(predicate1, predicate2); return new OrPredicate<T>(predicate1, predicate2);
} }
/** /**
* Constructor that performs no validation. * Constructor that performs no validation.
* Use <code>getInstance</code> if you want that. * Use <code>getInstance</code> if you want that.
* *
* @param predicate1 the first predicate to check, not null * @param predicate1 the first predicate to check, not null
* @param predicate2 the second predicate to check, not null * @param predicate2 the second predicate to check, not null
*/ */
public OrPredicate(Predicate predicate1, Predicate predicate2) { public OrPredicate(Predicate<? super T> predicate1, Predicate<? super T> predicate2) {
super(); super();
iPredicate1 = predicate1; iPredicate1 = predicate1;
iPredicate2 = predicate2; iPredicate2 = predicate2;
@ -68,21 +68,22 @@ public final class OrPredicate implements Predicate, PredicateDecorator, Seriali
/** /**
* Evaluates the predicate returning true if either predicate returns true. * Evaluates the predicate returning true if either predicate returns true.
* *
* @param object the input object * @param object the input object
* @return true if either decorated predicate returns true * @return true if either decorated predicate returns true
*/ */
public boolean evaluate(Object object) { public boolean evaluate(T object) {
return (iPredicate1.evaluate(object) || iPredicate2.evaluate(object)); return (iPredicate1.evaluate(object) || iPredicate2.evaluate(object));
} }
/** /**
* Gets the two predicates being decorated as an array. * Gets the two predicates being decorated as an array.
* *
* @return the predicates * @return the predicates
* @since Commons Collections 3.1 * @since Commons Collections 3.1
*/ */
public Predicate[] getPredicates() { @SuppressWarnings("unchecked")
public Predicate<? super T>[] getPredicates() {
return new Predicate[] {iPredicate1, iPredicate2}; return new Predicate[] {iPredicate1, iPredicate2};
} }

View File

@ -30,13 +30,13 @@ import org.apache.commons.collections.Transformer;
* *
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public class PredicateTransformer implements Transformer, Serializable { public class PredicateTransformer<T> implements Transformer<T, Boolean>, Serializable {
/** Serial version UID */ /** Serial version UID */
private static final long serialVersionUID = 5278818408044349346L; private static final long serialVersionUID = 5278818408044349346L;
/** The closure to wrap */ /** The closure to wrap */
private final Predicate iPredicate; private final Predicate<? super T> iPredicate;
/** /**
* Factory method that performs validation. * Factory method that performs validation.
@ -45,11 +45,11 @@ public class PredicateTransformer implements Transformer, Serializable {
* @return the <code>predicate</code> transformer * @return the <code>predicate</code> transformer
* @throws IllegalArgumentException if the predicate is null * @throws IllegalArgumentException if the predicate is null
*/ */
public static Transformer getInstance(Predicate predicate) { public static <T> Transformer<T, Boolean> getInstance(Predicate<? super T> predicate) {
if (predicate == null) { if (predicate == null) {
throw new IllegalArgumentException("Predicate must not be null"); throw new IllegalArgumentException("Predicate must not be null");
} }
return new PredicateTransformer(predicate); return new PredicateTransformer<T>(predicate);
} }
/** /**
@ -58,7 +58,7 @@ public class PredicateTransformer implements Transformer, Serializable {
* *
* @param predicate the predicate to call, not null * @param predicate the predicate to call, not null
*/ */
public PredicateTransformer(Predicate predicate) { public PredicateTransformer(Predicate<? super T> predicate) {
super(); super();
iPredicate = predicate; iPredicate = predicate;
} }
@ -69,8 +69,8 @@ public class PredicateTransformer implements Transformer, Serializable {
* @param input the input object to transform * @param input the input object to transform
* @return the transformed result * @return the transformed result
*/ */
public Object transform(Object input) { public Boolean transform(T input) {
return (iPredicate.evaluate(input) ? Boolean.TRUE : Boolean.FALSE); return iPredicate.evaluate(input);
} }
/** /**
@ -79,7 +79,7 @@ public class PredicateTransformer implements Transformer, Serializable {
* @return the predicate * @return the predicate
* @since Commons Collections 3.1 * @since Commons Collections 3.1
*/ */
public Predicate getPredicate() { public Predicate<? super T> getPredicate() {
return iPredicate; return iPredicate;
} }

View File

@ -55,22 +55,22 @@ public class PrototypeFactory {
* @throws IllegalArgumentException if the prototype is null * @throws IllegalArgumentException if the prototype is null
* @throws IllegalArgumentException if the prototype cannot be cloned * @throws IllegalArgumentException if the prototype cannot be cloned
*/ */
public static Factory getInstance(Object prototype) { @SuppressWarnings("unchecked")
public static <T> Factory<T> getInstance(T prototype) {
if (prototype == null) { if (prototype == null) {
return ConstantFactory.NULL_INSTANCE; return ConstantFactory.<T>getInstance(null);
} }
try { try {
Method method = prototype.getClass().getMethod("clone", (Class[]) null); Method method = prototype.getClass().getMethod("clone", (Class[]) null);
return new PrototypeCloneFactory(prototype, method); return new PrototypeCloneFactory<T>(prototype, method);
} catch (NoSuchMethodException ex) { } catch (NoSuchMethodException ex) {
try { try {
prototype.getClass().getConstructor(new Class[] { prototype.getClass()}); prototype.getClass().getConstructor(new Class<?>[] { prototype.getClass() });
return new InstantiateFactory( return new InstantiateFactory<T>(
prototype.getClass(), (Class<T>) prototype.getClass(),
new Class[] { prototype.getClass()}, new Class<?>[] { prototype.getClass() },
new Object[] { prototype }); new Object[] { prototype });
} catch (NoSuchMethodException ex2) { } catch (NoSuchMethodException ex2) {
if (prototype instanceof Serializable) { if (prototype instanceof Serializable) {
return new PrototypeSerializationFactory((Serializable) prototype); return new PrototypeSerializationFactory((Serializable) prototype);
@ -93,20 +93,20 @@ public class PrototypeFactory {
/** /**
* PrototypeCloneFactory creates objects by copying a prototype using the clone method. * PrototypeCloneFactory creates objects by copying a prototype using the clone method.
*/ */
static class PrototypeCloneFactory implements Factory, Serializable { static class PrototypeCloneFactory<T> implements Factory<T>, Serializable {
/** The serial version */ /** The serial version */
private static final long serialVersionUID = 5604271422565175555L; private static final long serialVersionUID = 5604271422565175555L;
/** The object to clone each time */ /** The object to clone each time */
private final Object iPrototype; private final T iPrototype;
/** The method used to clone */ /** The method used to clone */
private transient Method iCloneMethod; private transient Method iCloneMethod;
/** /**
* Constructor to store prototype. * Constructor to store prototype.
*/ */
private PrototypeCloneFactory(Object prototype, Method method) { private PrototypeCloneFactory(T prototype, Method method) {
super(); super();
iPrototype = prototype; iPrototype = prototype;
iCloneMethod = method; iCloneMethod = method;
@ -118,7 +118,6 @@ public class PrototypeFactory {
private void findCloneMethod() { private void findCloneMethod() {
try { try {
iCloneMethod = iPrototype.getClass().getMethod("clone", (Class[]) null); iCloneMethod = iPrototype.getClass().getMethod("clone", (Class[]) null);
} catch (NoSuchMethodException ex) { } catch (NoSuchMethodException ex) {
throw new IllegalArgumentException("PrototypeCloneFactory: The clone method must exist and be public "); throw new IllegalArgumentException("PrototypeCloneFactory: The clone method must exist and be public ");
} }
@ -129,15 +128,15 @@ public class PrototypeFactory {
* *
* @return the new object * @return the new object
*/ */
public Object create() { @SuppressWarnings("unchecked")
public T create() {
// needed for post-serialization // needed for post-serialization
if (iCloneMethod == null) { if (iCloneMethod == null) {
findCloneMethod(); findCloneMethod();
} }
try { try {
return iCloneMethod.invoke(iPrototype, (Object[])null); return (T) iCloneMethod.invoke(iPrototype, (Object[]) null);
} catch (IllegalAccessException ex) { } catch (IllegalAccessException ex) {
throw new FunctorException("PrototypeCloneFactory: Clone method must be public", ex); throw new FunctorException("PrototypeCloneFactory: Clone method must be public", ex);
} catch (InvocationTargetException ex) { } catch (InvocationTargetException ex) {
@ -151,18 +150,18 @@ public class PrototypeFactory {
/** /**
* PrototypeSerializationFactory creates objects by cloning a prototype using serialization. * PrototypeSerializationFactory creates objects by cloning a prototype using serialization.
*/ */
static class PrototypeSerializationFactory implements Factory, Serializable { static class PrototypeSerializationFactory<T extends Serializable> implements Factory<T>, Serializable {
/** The serial version */ /** The serial version */
private static final long serialVersionUID = -8704966966139178833L; private static final long serialVersionUID = -8704966966139178833L;
/** The object to clone via serialization each time */ /** The object to clone via serialization each time */
private final Serializable iPrototype; private final T iPrototype;
/** /**
* Constructor to store prototype * Constructor to store prototype
*/ */
private PrototypeSerializationFactory(Serializable prototype) { private PrototypeSerializationFactory(T prototype) {
super(); super();
iPrototype = prototype; iPrototype = prototype;
} }
@ -172,7 +171,8 @@ public class PrototypeFactory {
* *
* @return the new object * @return the new object
*/ */
public Object create() { @SuppressWarnings("unchecked")
public T create() {
ByteArrayOutputStream baos = new ByteArrayOutputStream(512); ByteArrayOutputStream baos = new ByteArrayOutputStream(512);
ByteArrayInputStream bais = null; ByteArrayInputStream bais = null;
try { try {
@ -181,7 +181,7 @@ public class PrototypeFactory {
bais = new ByteArrayInputStream(baos.toByteArray()); bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream in = new ObjectInputStream(bais); ObjectInputStream in = new ObjectInputStream(bais);
return in.readObject(); return (T) in.readObject();
} catch (ClassNotFoundException ex) { } catch (ClassNotFoundException ex) {
throw new FunctorException(ex); throw new FunctorException(ex);

View File

@ -29,13 +29,13 @@ import org.apache.commons.collections.Transformer;
* *
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public final class StringValueTransformer implements Transformer, Serializable { public final class StringValueTransformer<T> implements Transformer<T, String>, Serializable {
/** Serial version UID */ /** Serial version UID */
private static final long serialVersionUID = 7511110693171758606L; private static final long serialVersionUID = 7511110693171758606L;
/** Singleton predicate instance */ /** Singleton predicate instance */
public static final Transformer INSTANCE = new StringValueTransformer(); public static final Transformer<Object, String> INSTANCE = new StringValueTransformer<Object>();
/** /**
* Factory returning the singleton instance. * Factory returning the singleton instance.
@ -43,8 +43,9 @@ public final class StringValueTransformer implements Transformer, Serializable {
* @return the singleton instance * @return the singleton instance
* @since Commons Collections 3.1 * @since Commons Collections 3.1
*/ */
public static Transformer getInstance() { @SuppressWarnings("unchecked")
return INSTANCE; public static <T> Transformer<T, String> getInstance() {
return (Transformer<T, String>) INSTANCE;
} }
/** /**
@ -60,7 +61,7 @@ public final class StringValueTransformer implements Transformer, Serializable {
* @param input the input object to transform * @param input the input object to transform
* @return the transformed result * @return the transformed result
*/ */
public Object transform(Object input) { public String transform(T input) {
return String.valueOf(input); return String.valueOf(input);
} }

View File

@ -17,7 +17,6 @@
package org.apache.commons.collections.functors; package org.apache.commons.collections.functors;
import java.io.Serializable; import java.io.Serializable;
import java.util.Iterator;
import java.util.Map; import java.util.Map;
import org.apache.commons.collections.Closure; import org.apache.commons.collections.Closure;
@ -32,21 +31,21 @@ import org.apache.commons.collections.Predicate;
* *
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public class SwitchClosure implements Closure, Serializable { public class SwitchClosure<E> implements Closure<E>, Serializable {
/** Serial version UID */ /** Serial version UID */
private static final long serialVersionUID = 3518477308466486130L; private static final long serialVersionUID = 3518477308466486130L;
/** The tests to consider */ /** The tests to consider */
private final Predicate[] iPredicates; private final Predicate<? super E>[] iPredicates;
/** The matching closures to call */ /** The matching closures to call */
private final Closure[] iClosures; private final Closure<? super E>[] iClosures;
/** The default closure to call if no tests match */ /** The default closure to call if no tests match */
private final Closure iDefault; private final Closure<? super E> iDefault;
/** /**
* Factory method that performs validation and copies the parameter arrays. * Factory method that performs validation and copies the parameter arrays.
* *
* @param predicates array of predicates, cloned, no nulls * @param predicates array of predicates, cloned, no nulls
* @param closures matching array of closures, cloned, no nulls * @param closures matching array of closures, cloned, no nulls
* @param defaultClosure the closure to use if no match, null means nop * @param defaultClosure the closure to use if no match, null means nop
@ -54,85 +53,82 @@ public class SwitchClosure implements Closure, Serializable {
* @throws IllegalArgumentException if array is null * @throws IllegalArgumentException if array is null
* @throws IllegalArgumentException if any element in the array is null * @throws IllegalArgumentException if any element in the array is null
*/ */
public static Closure getInstance(Predicate[] predicates, Closure[] closures, Closure defaultClosure) { @SuppressWarnings("unchecked")
public static <E> Closure<E> getInstance(Predicate<? super E>[] predicates, Closure<? super E>[] closures, Closure<? super E> defaultClosure) {
FunctorUtils.validate(predicates); FunctorUtils.validate(predicates);
FunctorUtils.validate(closures); FunctorUtils.validate(closures);
if (predicates.length != closures.length) { if (predicates.length != closures.length) {
throw new IllegalArgumentException("The predicate and closure arrays must be the same size"); throw new IllegalArgumentException("The predicate and closure arrays must be the same size");
} }
if (predicates.length == 0) { if (predicates.length == 0) {
return (defaultClosure == null ? NOPClosure.INSTANCE : defaultClosure); return (Closure<E>) (defaultClosure == null ? NOPClosure.<E>getInstance(): defaultClosure);
} }
predicates = FunctorUtils.copy(predicates); predicates = FunctorUtils.copy(predicates);
closures = FunctorUtils.copy(closures); closures = FunctorUtils.copy(closures);
return new SwitchClosure(predicates, closures, defaultClosure); return new SwitchClosure<E>(predicates, closures, defaultClosure);
} }
/** /**
* Create a new Closure that calls one of the closures depending * Create a new Closure that calls one of the closures depending
* on the predicates. * on the predicates.
* <p> * <p>
* The Map consists of Predicate keys and Closure values. A closure * The Map consists of Predicate keys and Closure values. A closure
* is called if its matching predicate returns true. Each predicate is evaluated * is called if its matching predicate returns true. Each predicate is evaluated
* until one returns true. If no predicates evaluate to true, the default * until one returns true. If no predicates evaluate to true, the default
* closure is called. The default closure is set in the map with a * closure is called. The default closure is set in the map with a
* null key. The ordering is that of the iterator() method on the entryset * null key. The ordering is that of the iterator() method on the entryset
* collection of the map. * collection of the map.
* *
* @param predicatesAndClosures a map of predicates to closures * @param predicatesAndClosures a map of predicates to closures
* @return the <code>switch</code> closure * @return the <code>switch</code> closure
* @throws IllegalArgumentException if the map is null * @throws IllegalArgumentException if the map is null
* @throws IllegalArgumentException if any closure in the map is null * @throws IllegalArgumentException if any closure in the map is null
* @throws ClassCastException if the map elements are of the wrong type * @throws ClassCastException if the map elements are of the wrong type
*/ */
public static Closure getInstance(Map predicatesAndClosures) { @SuppressWarnings("unchecked")
Closure[] closures = null; public static <E> Closure<E> getInstance(Map<Predicate<E>, Closure<E>> predicatesAndClosures) {
Predicate[] preds = null;
if (predicatesAndClosures == null) { if (predicatesAndClosures == null) {
throw new IllegalArgumentException("The predicate and closure map must not be null"); throw new IllegalArgumentException("The predicate and closure map must not be null");
} }
if (predicatesAndClosures.size() == 0) {
return NOPClosure.INSTANCE;
}
// convert to array like this to guarantee iterator() ordering // convert to array like this to guarantee iterator() ordering
Closure defaultClosure = (Closure) predicatesAndClosures.remove(null); Closure<? super E> defaultClosure = predicatesAndClosures.remove(null);
int size = predicatesAndClosures.size(); int size = predicatesAndClosures.size();
if (size == 0) { if (size == 0) {
return (defaultClosure == null ? NOPClosure.INSTANCE : defaultClosure); return (Closure<E>) (defaultClosure == null ? NOPClosure.<E>getInstance() : defaultClosure);
} }
closures = new Closure[size]; Closure<E>[] closures = new Closure[size];
preds = new Predicate[size]; Predicate<E>[] preds = new Predicate[size];
int i = 0; int i = 0;
for (Iterator it = predicatesAndClosures.entrySet().iterator(); it.hasNext();) { for (Map.Entry<Predicate<E>, Closure<E>> entry : predicatesAndClosures.entrySet()) {
Map.Entry entry = (Map.Entry) it.next(); preds[i] = entry.getKey();
preds[i] = (Predicate) entry.getKey(); closures[i] = entry.getValue();
closures[i] = (Closure) entry.getValue();
i++; i++;
} }
return new SwitchClosure(preds, closures, defaultClosure); return new SwitchClosure<E>(preds, closures, defaultClosure);
} }
/** /**
* Constructor that performs no validation. * Constructor that performs no validation.
* Use <code>getInstance</code> if you want that. * Use <code>getInstance</code> if you want that.
* *
* @param predicates array of predicates, not cloned, no nulls * @param predicates array of predicates, not cloned, no nulls
* @param closures matching array of closures, not cloned, no nulls * @param closures matching array of closures, not cloned, no nulls
* @param defaultClosure the closure to use if no match, null means nop * @param defaultClosure the closure to use if no match, null means nop
*/ */
public SwitchClosure(Predicate[] predicates, Closure[] closures, Closure defaultClosure) { @SuppressWarnings("unchecked")
public SwitchClosure(Predicate<? super E>[] predicates, Closure<? super E>[] closures, Closure<? super E> defaultClosure) {
super(); super();
iPredicates = predicates; iPredicates = predicates;
iClosures = closures; iClosures = closures;
iDefault = (defaultClosure == null ? NOPClosure.INSTANCE : defaultClosure); iDefault = (Closure<? super E>) (defaultClosure == null ? NOPClosure.<E>getInstance() : defaultClosure);
} }
/** /**
* Executes the closure whose matching predicate returns true * Executes the closure whose matching predicate returns true
* *
* @param input the input object * @param input the input object
*/ */
public void execute(Object input) { public void execute(E input) {
for (int i = 0; i < iPredicates.length; i++) { for (int i = 0; i < iPredicates.length; i++) {
if (iPredicates[i].evaluate(input) == true) { if (iPredicates[i].evaluate(input) == true) {
iClosures[i].execute(input); iClosures[i].execute(input);
@ -144,32 +140,32 @@ public class SwitchClosure implements Closure, Serializable {
/** /**
* Gets the predicates, do not modify the array. * Gets the predicates, do not modify the array.
* *
* @return the predicates * @return the predicates
* @since Commons Collections 3.1 * @since Commons Collections 3.1
*/ */
public Predicate[] getPredicates() { public Predicate<? super E>[] getPredicates() {
return iPredicates; return iPredicates;
} }
/** /**
* Gets the closures, do not modify the array. * Gets the closures, do not modify the array.
* *
* @return the closures * @return the closures
* @since Commons Collections 3.1 * @since Commons Collections 3.1
*/ */
public Closure[] getClosures() { public Closure<? super E>[] getClosures() {
return iClosures; return iClosures;
} }
/** /**
* Gets the default closure. * Gets the default closure.
* *
* @return the default closure * @return the default closure
* @since Commons Collections 3.1 * @since Commons Collections 3.1
*/ */
public Closure getDefaultClosure() { public Closure<? super E> getDefaultClosure() {
return iDefault; return iDefault;
} }
} }

View File

@ -17,7 +17,6 @@
package org.apache.commons.collections.functors; package org.apache.commons.collections.functors;
import java.io.Serializable; import java.io.Serializable;
import java.util.Iterator;
import java.util.Map; import java.util.Map;
import org.apache.commons.collections.Predicate; import org.apache.commons.collections.Predicate;
@ -32,17 +31,17 @@ import org.apache.commons.collections.Transformer;
* *
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public class SwitchTransformer implements Transformer, Serializable { public class SwitchTransformer<I, O> implements Transformer<I, O>, Serializable {
/** Serial version UID */ /** Serial version UID */
private static final long serialVersionUID = -6404460890903469332L; private static final long serialVersionUID = -6404460890903469332L;
/** The tests to consider */ /** The tests to consider */
private final Predicate[] iPredicates; private final Predicate<? super I>[] iPredicates;
/** The matching transformers to call */ /** The matching transformers to call */
private final Transformer[] iTransformers; private final Transformer<? super I, ? extends O>[] iTransformers;
/** The default transformer to call if no tests match */ /** The default transformer to call if no tests match */
private final Transformer iDefault; private final Transformer<? super I, ? extends O> iDefault;
/** /**
* Factory method that performs validation and copies the parameter arrays. * Factory method that performs validation and copies the parameter arrays.
@ -54,18 +53,21 @@ public class SwitchTransformer implements Transformer, Serializable {
* @throws IllegalArgumentException if array is null * @throws IllegalArgumentException if array is null
* @throws IllegalArgumentException if any element in the array is null * @throws IllegalArgumentException if any element in the array is null
*/ */
public static Transformer getInstance(Predicate[] predicates, Transformer[] transformers, Transformer defaultTransformer) { @SuppressWarnings("unchecked")
public static <I, O> Transformer<I, O> getInstance(Predicate<? super I>[] predicates,
Transformer<? super I, ? extends O>[] transformers,
Transformer<? super I, ? extends O> defaultTransformer) {
FunctorUtils.validate(predicates); FunctorUtils.validate(predicates);
FunctorUtils.validate(transformers); FunctorUtils.validate(transformers);
if (predicates.length != transformers.length) { if (predicates.length != transformers.length) {
throw new IllegalArgumentException("The predicate and transformer arrays must be the same size"); throw new IllegalArgumentException("The predicate and transformer arrays must be the same size");
} }
if (predicates.length == 0) { if (predicates.length == 0) {
return (defaultTransformer == null ? ConstantTransformer.NULL_INSTANCE : defaultTransformer); return (Transformer<I, O>) (defaultTransformer == null ? ConstantTransformer.<I, O>getNullInstance() : defaultTransformer);
} }
predicates = FunctorUtils.copy(predicates); predicates = FunctorUtils.copy(predicates);
transformers = FunctorUtils.copy(transformers); transformers = FunctorUtils.copy(transformers);
return new SwitchTransformer(predicates, transformers, defaultTransformer); return new SwitchTransformer<I, O>(predicates, transformers, defaultTransformer);
} }
/** /**
@ -85,31 +87,30 @@ public class SwitchTransformer implements Transformer, Serializable {
* @throws IllegalArgumentException if any transformer in the map is null * @throws IllegalArgumentException if any transformer in the map is null
* @throws ClassCastException if the map elements are of the wrong type * @throws ClassCastException if the map elements are of the wrong type
*/ */
public static Transformer getInstance(Map predicatesAndTransformers) { @SuppressWarnings("unchecked")
Transformer[] transformers = null; public static <I, O> Transformer<I, O> getInstance(
Predicate[] preds = null; Map<? extends Predicate<? super I>, ? extends Transformer<? super I, ? extends O>> predicatesAndTransformers) {
if (predicatesAndTransformers == null) { if (predicatesAndTransformers == null) {
throw new IllegalArgumentException("The predicate and transformer map must not be null"); throw new IllegalArgumentException("The predicate and transformer map must not be null");
} }
if (predicatesAndTransformers.size() == 0) { if (predicatesAndTransformers.size() == 0) {
return ConstantTransformer.NULL_INSTANCE; return ConstantTransformer.<I, O>getNullInstance();
} }
// convert to array like this to guarantee iterator() ordering // convert to array like this to guarantee iterator() ordering
Transformer defaultTransformer = (Transformer) predicatesAndTransformers.remove(null); Transformer<? super I, ? extends O> defaultTransformer = predicatesAndTransformers.remove(null);
int size = predicatesAndTransformers.size(); int size = predicatesAndTransformers.size();
if (size == 0) { if (size == 0) {
return (defaultTransformer == null ? ConstantTransformer.NULL_INSTANCE : defaultTransformer); return (Transformer<I, O>) (defaultTransformer == null ? ConstantTransformer.<I, O>getNullInstance() : defaultTransformer);
} }
transformers = new Transformer[size]; Transformer<? super I, ? extends O>[] transformers = new Transformer[size];
preds = new Predicate[size]; Predicate<? super I>[] preds = new Predicate[size];
int i = 0; int i = 0;
for (Iterator it = predicatesAndTransformers.entrySet().iterator(); it.hasNext();) { for (Map.Entry<? extends Predicate<? super I>, ? extends Transformer<? super I, ? extends O>> entry : predicatesAndTransformers.entrySet()) {
Map.Entry entry = (Map.Entry) it.next(); preds[i] = entry.getKey();
preds[i] = (Predicate) entry.getKey(); transformers[i] = entry.getValue();
transformers[i] = (Transformer) entry.getValue();
i++; i++;
} }
return new SwitchTransformer(preds, transformers, defaultTransformer); return new SwitchTransformer<I, O>(preds, transformers, defaultTransformer);
} }
/** /**
@ -120,11 +121,14 @@ public class SwitchTransformer implements Transformer, Serializable {
* @param transformers matching array of transformers, not cloned, no nulls * @param transformers matching array of transformers, not cloned, no nulls
* @param defaultTransformer the transformer to use if no match, null means return null * @param defaultTransformer the transformer to use if no match, null means return null
*/ */
public SwitchTransformer(Predicate[] predicates, Transformer[] transformers, Transformer defaultTransformer) { @SuppressWarnings("unchecked")
public SwitchTransformer(Predicate<? super I>[] predicates,
Transformer<? super I, ? extends O>[] transformers,
Transformer<? super I, ? extends O> defaultTransformer) {
super(); super();
iPredicates = predicates; iPredicates = predicates;
iTransformers = transformers; iTransformers = transformers;
iDefault = (defaultTransformer == null ? ConstantTransformer.NULL_INSTANCE : defaultTransformer); iDefault = (Transformer<? super I, ? extends O>) (defaultTransformer == null ? ConstantTransformer.<I, O>getNullInstance() : defaultTransformer);
} }
/** /**
@ -134,7 +138,7 @@ public class SwitchTransformer implements Transformer, Serializable {
* @param input the input object to transform * @param input the input object to transform
* @return the transformed result * @return the transformed result
*/ */
public Object transform(Object input) { public O transform(I input) {
for (int i = 0; i < iPredicates.length; i++) { for (int i = 0; i < iPredicates.length; i++) {
if (iPredicates[i].evaluate(input) == true) { if (iPredicates[i].evaluate(input) == true) {
return iTransformers[i].transform(input); return iTransformers[i].transform(input);
@ -149,7 +153,7 @@ public class SwitchTransformer implements Transformer, Serializable {
* @return the predicates * @return the predicates
* @since Commons Collections 3.1 * @since Commons Collections 3.1
*/ */
public Predicate[] getPredicates() { public Predicate<? super I>[] getPredicates() {
return iPredicates; return iPredicates;
} }
@ -159,7 +163,7 @@ public class SwitchTransformer implements Transformer, Serializable {
* @return the transformers * @return the transformers
* @since Commons Collections 3.1 * @since Commons Collections 3.1
*/ */
public Transformer[] getTransformers() { public Transformer<? super I, ? extends O>[] getTransformers() {
return iTransformers; return iTransformers;
} }
@ -169,7 +173,7 @@ public class SwitchTransformer implements Transformer, Serializable {
* @return the default transformer * @return the default transformer
* @since Commons Collections 3.1 * @since Commons Collections 3.1
*/ */
public Transformer getDefaultTransformer() { public Transformer<? super I, ? extends O> getDefaultTransformer() {
return iDefault; return iDefault;
} }

View File

@ -30,74 +30,76 @@ import org.apache.commons.collections.Transformer;
* @author Alban Peignier * @author Alban Peignier
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public final class TransformedPredicate implements Predicate, PredicateDecorator, Serializable { public final class TransformedPredicate<T> implements Predicate<T>, PredicateDecorator<T>, Serializable {
/** Serial version UID */ /** Serial version UID */
private static final long serialVersionUID = -5596090919668315834L; private static final long serialVersionUID = -5596090919668315834L;
/** The transformer to call */ /** The transformer to call */
private final Transformer iTransformer; private final Transformer<? super T, ? extends T> iTransformer;
/** The predicate to call */ /** The predicate to call */
private final Predicate iPredicate; private final Predicate<? super T> iPredicate;
/** /**
* Factory to create the predicate. * Factory to create the predicate.
* *
* @param transformer the transformer to call * @param transformer the transformer to call
* @param predicate the predicate to call with the result of the transform * @param predicate the predicate to call with the result of the transform
* @return the predicate * @return the predicate
* @throws IllegalArgumentException if the transformer or the predicate is null * @throws IllegalArgumentException if the transformer or the predicate is null
*/ */
public static Predicate getInstance(Transformer transformer, Predicate predicate) { public static <T> Predicate<T> getInstance(Transformer<? super T, ? extends T> transformer, Predicate<? super T> predicate) {
if (transformer == null) { if (transformer == null) {
throw new IllegalArgumentException("The transformer to call must not be null"); throw new IllegalArgumentException("The transformer to call must not be null");
} }
if (predicate == null) { if (predicate == null) {
throw new IllegalArgumentException("The predicate to call must not be null"); throw new IllegalArgumentException("The predicate to call must not be null");
} }
return new TransformedPredicate(transformer, predicate); return new TransformedPredicate<T>(transformer, predicate);
} }
/** /**
* Constructor that performs no validation. * Constructor that performs no validation.
* Use <code>getInstance</code> if you want that. * Use <code>getInstance</code> if you want that.
* *
* @param transformer the transformer to use * @param transformer the transformer to use
* @param predicate the predicate to decorate * @param predicate the predicate to decorate
*/ */
public TransformedPredicate(Transformer transformer, Predicate predicate) { public TransformedPredicate(Transformer<? super T, ? extends T> transformer, Predicate<? super T> predicate) {
iTransformer = transformer; iTransformer = transformer;
iPredicate = predicate; iPredicate = predicate;
} }
/** /**
* Evaluates the predicate returning the result of the decorated predicate * Evaluates the predicate returning the result of the decorated predicate
* once the input has been transformed * once the input has been transformed
* *
* @param object the input object which will be transformed * @param object the input object which will be transformed
* @return true if decorated predicate returns true * @return true if decorated predicate returns true
*/ */
public boolean evaluate(Object object) { public boolean evaluate(T object) {
Object result = iTransformer.transform(object); T result = iTransformer.transform(object);
return iPredicate.evaluate(result); return iPredicate.evaluate(result);
} }
/** /**
* Gets the predicate being decorated. * Gets the predicate being decorated.
* *
* @return the predicate as the only element in an array * @return the predicate as the only element in an array
* @since Commons Collections 3.1 * @since Commons Collections 3.1
*/ */
public Predicate[] getPredicates() { @SuppressWarnings("unchecked")
public Predicate<? super T>[] getPredicates() {
return new Predicate[] {iPredicate}; return new Predicate[] {iPredicate};
} }
/** /**
* Gets the transformer in use. * Gets the transformer in use.
* *
* @return the transformer * @return the transformer
*/ */
public Transformer getTransformer() { public Transformer<? super T, ? extends T> getTransformer() {
return iTransformer; return iTransformer;
} }

View File

@ -30,13 +30,13 @@ import org.apache.commons.collections.Transformer;
* *
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public class TransformerClosure implements Closure, Serializable { public class TransformerClosure<E> implements Closure<E>, Serializable {
/** Serial version UID */ /** Serial version UID */
private static final long serialVersionUID = -5194992589193388969L; private static final long serialVersionUID = -5194992589193388969L;
/** The transformer to wrap */ /** The transformer to wrap */
private final Transformer iTransformer; private final Transformer<? super E, ?> iTransformer;
/** /**
* Factory method that performs validation. * Factory method that performs validation.
@ -46,11 +46,11 @@ public class TransformerClosure implements Closure, Serializable {
* @param transformer the transformer to call, null means nop * @param transformer the transformer to call, null means nop
* @return the <code>transformer</code> closure * @return the <code>transformer</code> closure
*/ */
public static Closure getInstance(Transformer transformer) { public static <E> Closure<E> getInstance(Transformer<? super E, ?> transformer) {
if (transformer == null) { if (transformer == null) {
return NOPClosure.INSTANCE; return NOPClosure.<E>getInstance();
} }
return new TransformerClosure(transformer); return new TransformerClosure<E>(transformer);
} }
/** /**
@ -59,7 +59,7 @@ public class TransformerClosure implements Closure, Serializable {
* *
* @param transformer the transformer to call, not null * @param transformer the transformer to call, not null
*/ */
public TransformerClosure(Transformer transformer) { public TransformerClosure(Transformer<? super E, ?> transformer) {
super(); super();
iTransformer = transformer; iTransformer = transformer;
} }
@ -69,7 +69,7 @@ public class TransformerClosure implements Closure, Serializable {
* *
* @param input the input object * @param input the input object
*/ */
public void execute(Object input) { public void execute(E input) {
iTransformer.transform(input); iTransformer.transform(input);
} }
@ -79,7 +79,7 @@ public class TransformerClosure implements Closure, Serializable {
* @return the transformer * @return the transformer
* @since Commons Collections 3.1 * @since Commons Collections 3.1
*/ */
public Transformer getTransformer() { public Transformer<? super E, ?> getTransformer() {
return iTransformer; return iTransformer;
} }

View File

@ -30,63 +30,62 @@ import org.apache.commons.collections.Transformer;
* *
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public final class TransformerPredicate implements Predicate, Serializable { public final class TransformerPredicate<T> implements Predicate<T>, Serializable {
/** Serial version UID */ /** Serial version UID */
private static final long serialVersionUID = -2407966402920578741L; private static final long serialVersionUID = -2407966402920578741L;
/** The transformer to call */ /** The transformer to call */
private final Transformer iTransformer; private final Transformer<? super T, Boolean> iTransformer;
/** /**
* Factory to create the predicate. * Factory to create the predicate.
* *
* @param transformer the transformer to decorate * @param transformer the transformer to decorate
* @return the predicate * @return the predicate
* @throws IllegalArgumentException if the transformer is null * @throws IllegalArgumentException if the transformer is null
*/ */
public static Predicate getInstance(Transformer transformer) { public static <T> Predicate<T> getInstance(Transformer<? super T, Boolean> transformer) {
if (transformer == null) { if (transformer == null) {
throw new IllegalArgumentException("The transformer to call must not be null"); throw new IllegalArgumentException("The transformer to call must not be null");
} }
return new TransformerPredicate(transformer); return new TransformerPredicate<T>(transformer);
} }
/** /**
* Constructor that performs no validation. * Constructor that performs no validation.
* Use <code>getInstance</code> if you want that. * Use <code>getInstance</code> if you want that.
* *
* @param transformer the transformer to decorate * @param transformer the transformer to decorate
*/ */
public TransformerPredicate(Transformer transformer) { public TransformerPredicate(Transformer<? super T, Boolean> transformer) {
super(); super();
iTransformer = transformer; iTransformer = transformer;
} }
/** /**
* Evaluates the predicate returning the result of the decorated transformer. * Evaluates the predicate returning the result of the decorated transformer.
* *
* @param object the input object * @param object the input object
* @return true if decorated transformer returns Boolean.TRUE * @return true if decorated transformer returns Boolean.TRUE
* @throws FunctorException if the transformer returns an invalid type * @throws FunctorException if the transformer returns an invalid type
*/ */
public boolean evaluate(Object object) { public boolean evaluate(T object) {
Object result = iTransformer.transform(object); Boolean result = iTransformer.transform(object);
if (result instanceof Boolean == false) { if (result == null) {
throw new FunctorException( throw new FunctorException(
"Transformer must return an instanceof Boolean, it was a " "Transformer must return an instanceof Boolean, it was a null object");
+ (result == null ? "null object" : result.getClass().getName()));
} }
return ((Boolean) result).booleanValue(); return result;
} }
/** /**
* Gets the transformer. * Gets the transformer.
* *
* @return the transformer * @return the transformer
* @since Commons Collections 3.1 * @since Commons Collections 3.1
*/ */
public Transformer getTransformer() { public Transformer<? super T, Boolean> getTransformer() {
return iTransformer; return iTransformer;
} }

View File

@ -31,22 +31,22 @@ import org.apache.commons.collections.Predicate;
* *
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public final class UniquePredicate implements Predicate, Serializable { public final class UniquePredicate<T> implements Predicate<T>, Serializable {
/** Serial version UID */ /** Serial version UID */
private static final long serialVersionUID = -3319417438027438040L; private static final long serialVersionUID = -3319417438027438040L;
/** The set of previously seen objects */ /** The set of previously seen objects */
private final Set iSet = new HashSet(); private final Set<T> iSet = new HashSet<T>();
/** /**
* Factory to create the predicate. * Factory to create the predicate.
* *
* @return the predicate * @return the predicate
* @throws IllegalArgumentException if the predicate is null * @throws IllegalArgumentException if the predicate is null
*/ */
public static Predicate getInstance() { public static <E> Predicate<E> getInstance() {
return new UniquePredicate(); return new UniquePredicate<E>();
} }
/** /**
@ -60,11 +60,11 @@ public final class UniquePredicate implements Predicate, Serializable {
/** /**
* Evaluates the predicate returning true if the input object hasn't been * Evaluates the predicate returning true if the input object hasn't been
* received yet. * received yet.
* *
* @param object the input object * @param object the input object
* @return true if this is the first time the object is seen * @return true if this is the first time the object is seen
*/ */
public boolean evaluate(Object object) { public boolean evaluate(T object) {
return iSet.add(object); return iSet.add(object);
} }

View File

@ -30,15 +30,15 @@ import org.apache.commons.collections.Predicate;
* *
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public class WhileClosure implements Closure, Serializable { public class WhileClosure<E> implements Closure<E>, Serializable {
/** Serial version UID */ /** Serial version UID */
private static final long serialVersionUID = -3110538116913760108L; private static final long serialVersionUID = -3110538116913760108L;
/** The test condition */ /** The test condition */
private final Predicate iPredicate; private final Predicate<? super E> iPredicate;
/** The closure to call */ /** The closure to call */
private final Closure iClosure; private final Closure<? super E> iClosure;
/** The flag, true is a do loop, false is a while */ /** The flag, true is a do loop, false is a while */
private final boolean iDoLoop; private final boolean iDoLoop;
@ -51,14 +51,14 @@ public class WhileClosure implements Closure, Serializable {
* @return the <code>while</code> closure * @return the <code>while</code> closure
* @throws IllegalArgumentException if the predicate or closure is null * @throws IllegalArgumentException if the predicate or closure is null
*/ */
public static Closure getInstance(Predicate predicate, Closure closure, boolean doLoop) { public static <E> Closure<E> getInstance(Predicate<? super E> predicate, Closure<? super E> closure, boolean doLoop) {
if (predicate == null) { if (predicate == null) {
throw new IllegalArgumentException("Predicate must not be null"); throw new IllegalArgumentException("Predicate must not be null");
} }
if (closure == null) { if (closure == null) {
throw new IllegalArgumentException("Closure must not be null"); throw new IllegalArgumentException("Closure must not be null");
} }
return new WhileClosure(predicate, closure, doLoop); return new WhileClosure<E>(predicate, closure, doLoop);
} }
/** /**
@ -69,7 +69,7 @@ public class WhileClosure implements Closure, Serializable {
* @param closure the closure the execute, not null * @param closure the closure the execute, not null
* @param doLoop true to act as a do-while loop, always executing the closure once * @param doLoop true to act as a do-while loop, always executing the closure once
*/ */
public WhileClosure(Predicate predicate, Closure closure, boolean doLoop) { public WhileClosure(Predicate<? super E> predicate, Closure<? super E> closure, boolean doLoop) {
super(); super();
iPredicate = predicate; iPredicate = predicate;
iClosure = closure; iClosure = closure;
@ -81,7 +81,7 @@ public class WhileClosure implements Closure, Serializable {
* *
* @param input the input object * @param input the input object
*/ */
public void execute(Object input) { public void execute(E input) {
if (iDoLoop) { if (iDoLoop) {
iClosure.execute(input); iClosure.execute(input);
} }
@ -96,7 +96,7 @@ public class WhileClosure implements Closure, Serializable {
* @return the predicate * @return the predicate
* @since Commons Collections 3.1 * @since Commons Collections 3.1
*/ */
public Predicate getPredicate() { public Predicate<? super E> getPredicate() {
return iPredicate; return iPredicate;
} }
@ -106,7 +106,7 @@ public class WhileClosure implements Closure, Serializable {
* @return the closure * @return the closure
* @since Commons Collections 3.1 * @since Commons Collections 3.1
*/ */
public Closure getClosure() { public Closure<? super E> getClosure() {
return iClosure; return iClosure;
} }

View File

@ -26,7 +26,7 @@ import java.util.NoSuchElementException;
* *
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
abstract class AbstractEmptyIterator { abstract class AbstractEmptyIterator<E> {
/** /**
* Constructor. * Constructor.
@ -39,7 +39,7 @@ abstract class AbstractEmptyIterator {
return false; return false;
} }
public Object next() { public E next() {
throw new NoSuchElementException("Iterator contains no elements"); throw new NoSuchElementException("Iterator contains no elements");
} }
@ -47,7 +47,7 @@ abstract class AbstractEmptyIterator {
return false; return false;
} }
public Object previous() { public E previous() {
throw new NoSuchElementException("Iterator contains no elements"); throw new NoSuchElementException("Iterator contains no elements");
} }
@ -59,11 +59,11 @@ abstract class AbstractEmptyIterator {
return -1; return -1;
} }
public void add(Object obj) { public void add(E obj) {
throw new UnsupportedOperationException("add() not supported for empty Iterator"); throw new UnsupportedOperationException("add() not supported for empty Iterator");
} }
public void set(Object obj) { public void set(E obj) {
throw new IllegalStateException("Iterator contains no elements"); throw new IllegalStateException("Iterator contains no elements");
} }
@ -71,18 +71,6 @@ abstract class AbstractEmptyIterator {
throw new IllegalStateException("Iterator contains no elements"); throw new IllegalStateException("Iterator contains no elements");
} }
public Object getKey() {
throw new IllegalStateException("Iterator contains no elements");
}
public Object getValue() {
throw new IllegalStateException("Iterator contains no elements");
}
public Object setValue(Object value) {
throw new IllegalStateException("Iterator contains no elements");
}
public void reset() { public void reset() {
// do nothing // do nothing
} }

View File

@ -18,7 +18,7 @@ package org.apache.commons.collections.iterators;
import java.util.Iterator; import java.util.Iterator;
/** /**
* Provides basic behaviour for decorating an iterator with extra functionality. * Provides basic behaviour for decorating an iterator with extra functionality.
* <p> * <p>
* All methods are forwarded to the decorated iterator. * All methods are forwarded to the decorated iterator.
@ -29,10 +29,7 @@ import java.util.Iterator;
* @author James Strachan * @author James Strachan
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public class AbstractIteratorDecorator implements Iterator { public abstract class AbstractIteratorDecorator<E> extends AbstractUntypedIteratorDecorator<E, E> {
/** The iterator being decorated */
protected final Iterator iterator;
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
/** /**
@ -41,34 +38,12 @@ public class AbstractIteratorDecorator implements Iterator {
* @param iterator the iterator to decorate, must not be null * @param iterator the iterator to decorate, must not be null
* @throws IllegalArgumentException if the collection is null * @throws IllegalArgumentException if the collection is null
*/ */
public AbstractIteratorDecorator(Iterator iterator) { protected AbstractIteratorDecorator(Iterator<E> iterator) {
super(); super(iterator);
if (iterator == null) {
throw new IllegalArgumentException("Iterator must not be null");
}
this.iterator = iterator;
} }
/** public E next() {
* Gets the iterator being decorated. return getIterator().next();
*
* @return the decorated iterator
*/
protected Iterator getIterator() {
return iterator;
}
//-----------------------------------------------------------------------
public boolean hasNext() {
return iterator.hasNext();
}
public Object next() {
return iterator.next();
}
public void remove() {
iterator.remove();
} }
} }

View File

@ -28,10 +28,10 @@ import org.apache.commons.collections.MapIterator;
* *
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public class AbstractMapIteratorDecorator implements MapIterator { public class AbstractMapIteratorDecorator<K, V> implements MapIterator<K, V> {
/** The iterator being decorated */ /** The iterator being decorated */
protected final MapIterator iterator; protected final MapIterator<K, V> iterator;
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
/** /**
@ -40,7 +40,7 @@ public class AbstractMapIteratorDecorator implements MapIterator {
* @param iterator the iterator to decorate, must not be null * @param iterator the iterator to decorate, must not be null
* @throws IllegalArgumentException if the collection is null * @throws IllegalArgumentException if the collection is null
*/ */
public AbstractMapIteratorDecorator(MapIterator iterator) { public AbstractMapIteratorDecorator(MapIterator<K, V> iterator) {
super(); super();
if (iterator == null) { if (iterator == null) {
throw new IllegalArgumentException("MapIterator must not be null"); throw new IllegalArgumentException("MapIterator must not be null");
@ -53,7 +53,7 @@ public class AbstractMapIteratorDecorator implements MapIterator {
* *
* @return the decorated iterator * @return the decorated iterator
*/ */
protected MapIterator getMapIterator() { protected MapIterator<K, V> getMapIterator() {
return iterator; return iterator;
} }
@ -62,7 +62,7 @@ public class AbstractMapIteratorDecorator implements MapIterator {
return iterator.hasNext(); return iterator.hasNext();
} }
public Object next() { public K next() {
return iterator.next(); return iterator.next();
} }
@ -70,15 +70,15 @@ public class AbstractMapIteratorDecorator implements MapIterator {
iterator.remove(); iterator.remove();
} }
public Object getKey() { public K getKey() {
return iterator.getKey(); return iterator.getKey();
} }
public Object getValue() { public V getValue() {
return iterator.getValue(); return iterator.getValue();
} }
public Object setValue(Object obj) { public V setValue(V obj) {
return iterator.setValue(obj); return iterator.setValue(obj);
} }

View File

@ -28,10 +28,10 @@ import org.apache.commons.collections.OrderedMapIterator;
* *
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public class AbstractOrderedMapIteratorDecorator implements OrderedMapIterator { public class AbstractOrderedMapIteratorDecorator<K, V> implements OrderedMapIterator<K, V> {
/** The iterator being decorated */ /** The iterator being decorated */
protected final OrderedMapIterator iterator; protected final OrderedMapIterator<K, V> iterator;
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
/** /**
@ -40,7 +40,7 @@ public class AbstractOrderedMapIteratorDecorator implements OrderedMapIterator {
* @param iterator the iterator to decorate, must not be null * @param iterator the iterator to decorate, must not be null
* @throws IllegalArgumentException if the collection is null * @throws IllegalArgumentException if the collection is null
*/ */
public AbstractOrderedMapIteratorDecorator(OrderedMapIterator iterator) { public AbstractOrderedMapIteratorDecorator(OrderedMapIterator<K, V> iterator) {
super(); super();
if (iterator == null) { if (iterator == null) {
throw new IllegalArgumentException("OrderedMapIterator must not be null"); throw new IllegalArgumentException("OrderedMapIterator must not be null");
@ -53,7 +53,7 @@ public class AbstractOrderedMapIteratorDecorator implements OrderedMapIterator {
* *
* @return the decorated iterator * @return the decorated iterator
*/ */
protected OrderedMapIterator getOrderedMapIterator() { protected OrderedMapIterator<K, V> getOrderedMapIterator() {
return iterator; return iterator;
} }
@ -62,7 +62,7 @@ public class AbstractOrderedMapIteratorDecorator implements OrderedMapIterator {
return iterator.hasNext(); return iterator.hasNext();
} }
public Object next() { public K next() {
return iterator.next(); return iterator.next();
} }
@ -70,7 +70,7 @@ public class AbstractOrderedMapIteratorDecorator implements OrderedMapIterator {
return iterator.hasPrevious(); return iterator.hasPrevious();
} }
public Object previous() { public K previous() {
return iterator.previous(); return iterator.previous();
} }
@ -78,15 +78,15 @@ public class AbstractOrderedMapIteratorDecorator implements OrderedMapIterator {
iterator.remove(); iterator.remove();
} }
public Object getKey() { public K getKey() {
return iterator.getKey(); return iterator.getKey();
} }
public Object getValue() { public V getValue() {
return iterator.getValue(); return iterator.getValue();
} }
public Object setValue(Object obj) { public V setValue(V obj) {
return iterator.setValue(obj); return iterator.setValue(obj);
} }

View File

@ -27,12 +27,12 @@ import java.util.NoSuchElementException;
import org.apache.commons.collections.list.UnmodifiableList; import org.apache.commons.collections.list.UnmodifiableList;
/** /**
* Provides an ordered iteration over the elements contained in * Provides an ordered iteration over the elements contained in a collection of
* a collection of ordered Iterators. * ordered Iterators.
* <p> * <p>
* Given two ordered {@link Iterator} instances <code>A</code> and <code>B</code>, * Given two ordered {@link Iterator} instances <code>A</code> and
* the {@link #next} method on this iterator will return the lesser of * <code>B</code>, the {@link #next} method on this iterator will return the
* <code>A.next()</code> and <code>B.next()</code>. * lesser of <code>A.next()</code> and <code>B.next()</code>.
* *
* @since Commons Collections 2.1 * @since Commons Collections 2.1
* @version $Revision$ $Date$ * @version $Revision$ $Date$
@ -40,86 +40,93 @@ import org.apache.commons.collections.list.UnmodifiableList;
* @author Rodney Waldhoff * @author Rodney Waldhoff
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public class CollatingIterator implements Iterator { public class CollatingIterator<E> implements Iterator<E> {
/** The {@link Comparator} used to evaluate order. */ /** The {@link Comparator} used to evaluate order. */
private Comparator comparator = null; private Comparator<? super E> comparator = null;
/** The list of {@link Iterator}s to evaluate. */ /** The list of {@link Iterator}s to evaluate. */
private ArrayList iterators = null; private ArrayList<Iterator<? extends E>> iterators = null;
/** {@link Iterator#next Next} objects peeked from each iterator. */ /** {@link Iterator#next Next} objects peeked from each iterator. */
private ArrayList values = null; private ArrayList<E> values = null;
/** Whether or not each {@link #values} element has been set. */ /** Whether or not each {@link #values} element has been set. */
private BitSet valueSet = null; private BitSet valueSet = null;
/** Index of the {@link #iterators iterator} from whom the last returned value was obtained. */ /**
* Index of the {@link #iterators iterator} from whom the last returned
* value was obtained.
*/
private int lastReturned = -1; private int lastReturned = -1;
// Constructors // Constructors
// ---------------------------------------------------------------------- // ----------------------------------------------------------------------
/** /**
* Constructs a new <code>CollatingIterator</code>. Natural sort order * Constructs a new <code>CollatingIterator</code>. Natural sort order will
* will be used, and child iterators will have to be manually added * be used, and child iterators will have to be manually added using the
* using the {@link #addIterator(Iterator)} method. * {@link #addIterator(Iterator)} method.
*/ */
public CollatingIterator() { public CollatingIterator() {
this(null,2); this(null, 2);
} }
/** /**
* Constructs a new <code>CollatingIterator</code> that will used the * Constructs a new <code>CollatingIterator</code> that will used the
* specified comparator for ordering. Child iterators will have to be * specified comparator for ordering. Child iterators will have to be
* manually added using the {@link #addIterator(Iterator)} method. * manually added using the {@link #addIterator(Iterator)} method.
* *
* @param comp the comparator to use to sort, or null to use natural sort order * @param comp the comparator to use to sort, or null to use natural sort
* order
*/ */
public CollatingIterator(final Comparator comp) { public CollatingIterator(final Comparator<? super E> comp) {
this(comp,2); this(comp, 2);
} }
/** /**
* Constructs a new <code>CollatingIterator</code> that will used the * Constructs a new <code>CollatingIterator</code> that will used the
* specified comparator for ordering and have the specified initial * specified comparator for ordering and have the specified initial
* capacity. Child iterators will have to be * capacity. Child iterators will have to be manually added using the
* manually added using the {@link #addIterator(Iterator)} method. * {@link #addIterator(Iterator)} method.
* *
* @param comp the comparator to use to sort, or null to use natural sort order * @param comp the comparator to use to sort, or null to use natural sort
* @param initIterCapacity the initial capacity for the internal list * order
* of child iterators * @param initIterCapacity the initial capacity for the internal list of
* child iterators
*/ */
public CollatingIterator(final Comparator comp, final int initIterCapacity) { public CollatingIterator(final Comparator<? super E> comp, final int initIterCapacity) {
iterators = new ArrayList(initIterCapacity); iterators = new ArrayList<Iterator<? extends E>>(initIterCapacity);
setComparator(comp); setComparator(comp);
} }
/** /**
* Constructs a new <code>CollatingIterator</code> that will use the * Constructs a new <code>CollatingIterator</code> that will use the
* specified comparator to provide ordered iteration over the two * specified comparator to provide ordered iteration over the two given
* given iterators. * iterators.
* *
* @param comp the comparator to use to sort, or null to use natural sort order * @param comp the comparator to use to sort, or null to use natural sort
* @param a the first child ordered iterator * order
* @param b the second child ordered iterator * @param a the first child ordered iterator
* @param b the second child ordered iterator
* @throws NullPointerException if either iterator is null * @throws NullPointerException if either iterator is null
*/ */
public CollatingIterator(final Comparator comp, final Iterator a, final Iterator b) { public CollatingIterator(final Comparator<? super E> comp, final Iterator<? extends E> a, final Iterator<? extends E> b) {
this(comp,2); this(comp, 2);
addIterator(a); addIterator(a);
addIterator(b); addIterator(b);
} }
/** /**
* Constructs a new <code>CollatingIterator</code> that will use the * Constructs a new <code>CollatingIterator</code> that will use the
* specified comparator to provide ordered iteration over the array * specified comparator to provide ordered iteration over the array of
* of iterators. * iterators.
* *
* @param comp the comparator to use to sort, or null to use natural sort order * @param comp the comparator to use to sort, or null to use natural sort
* @param iterators the array of iterators * order
* @param iterators the array of iterators
* @throws NullPointerException if iterators array is or contains null * @throws NullPointerException if iterators array is or contains null
*/ */
public CollatingIterator(final Comparator comp, final Iterator[] iterators) { public CollatingIterator(final Comparator<? super E> comp, final Iterator<? extends E>[] iterators) {
this(comp, iterators.length); this(comp, iterators.length);
for (int i = 0; i < iterators.length; i++) { for (int i = 0; i < iterators.length; i++) {
addIterator(iterators[i]); addIterator(iterators[i]);
@ -128,20 +135,21 @@ public class CollatingIterator implements Iterator {
/** /**
* Constructs a new <code>CollatingIterator</code> that will use the * Constructs a new <code>CollatingIterator</code> that will use the
* specified comparator to provide ordered iteration over the collection * specified comparator to provide ordered iteration over the collection of
* of iterators. * iterators.
* *
* @param comp the comparator to use to sort, or null to use natural sort order * @param comp the comparator to use to sort, or null to use natural sort
* @param iterators the collection of iterators * order
* @throws NullPointerException if the iterators collection is or contains null * @param iterators the collection of iterators
* @throws NullPointerException if the iterators collection is or contains
* null
* @throws ClassCastException if the iterators collection contains an * @throws ClassCastException if the iterators collection contains an
* element that's not an {@link Iterator} * element that's not an {@link Iterator}
*/ */
public CollatingIterator(final Comparator comp, final Collection iterators) { public CollatingIterator(final Comparator<? super E> comp, final Collection<Iterator<? extends E>> iterators) {
this(comp, iterators.size()); this(comp, iterators.size());
for (Iterator it = iterators.iterator(); it.hasNext();) { for (Iterator<? extends E> iterator : iterators) {
Iterator item = (Iterator) it.next(); addIterator(iterator);
addIterator(item);
} }
} }
@ -150,11 +158,11 @@ public class CollatingIterator implements Iterator {
/** /**
* Adds the given {@link Iterator} to the iterators being collated. * Adds the given {@link Iterator} to the iterators being collated.
* *
* @param iterator the iterator to add to the collation, must not be null * @param iterator the iterator to add to the collation, must not be null
* @throws IllegalStateException if iteration has started * @throws IllegalStateException if iteration has started
* @throws NullPointerException if the iterator is null * @throws NullPointerException if the iterator is null
*/ */
public void addIterator(final Iterator iterator) { public void addIterator(final Iterator<? extends E> iterator) {
checkNotStarted(); checkNotStarted();
if (iterator == null) { if (iterator == null) {
throw new NullPointerException("Iterator must not be null"); throw new NullPointerException("Iterator must not be null");
@ -165,13 +173,13 @@ public class CollatingIterator implements Iterator {
/** /**
* Sets the iterator at the given index. * Sets the iterator at the given index.
* *
* @param index index of the Iterator to replace * @param index index of the Iterator to replace
* @param iterator Iterator to place at the given index * @param iterator Iterator to place at the given index
* @throws IndexOutOfBoundsException if index &lt; 0 or index &gt; size() * @throws IndexOutOfBoundsException if index &lt; 0 or index &gt; size()
* @throws IllegalStateException if iteration has started * @throws IllegalStateException if iteration has started
* @throws NullPointerException if the iterator is null * @throws NullPointerException if the iterator is null
*/ */
public void setIterator(final int index, final Iterator iterator) { public void setIterator(final int index, final Iterator<? extends E> iterator) {
checkNotStarted(); checkNotStarted();
if (iterator == null) { if (iterator == null) {
throw new NullPointerException("Iterator must not be null"); throw new NullPointerException("Iterator must not be null");
@ -184,14 +192,14 @@ public class CollatingIterator implements Iterator {
* *
* @return the unmodifiable list of iterators added * @return the unmodifiable list of iterators added
*/ */
public List getIterators() { public List<Iterator<? extends E>> getIterators() {
return UnmodifiableList.decorate(iterators); return UnmodifiableList.decorate(iterators);
} }
/** /**
* Gets the {@link Comparator} by which collatation occurs. * Gets the {@link Comparator} by which collatation occurs.
*/ */
public Comparator getComparator() { public Comparator<? super E> getComparator() {
return comparator; return comparator;
} }
@ -200,7 +208,7 @@ public class CollatingIterator implements Iterator {
* *
* @throws IllegalStateException if iteration has started * @throws IllegalStateException if iteration has started
*/ */
public void setComparator(final Comparator comp) { public void setComparator(final Comparator<? super E> comp) {
checkNotStarted(); checkNotStarted();
comparator = comp; comparator = comp;
} }
@ -209,7 +217,7 @@ public class CollatingIterator implements Iterator {
// ------------------------------------------------------------------- // -------------------------------------------------------------------
/** /**
* Returns <code>true</code> if any child iterator has remaining elements. * Returns <code>true</code> if any child iterator has remaining elements.
* *
* @return true if this iterator has remaining elements * @return true if this iterator has remaining elements
*/ */
public boolean hasNext() { public boolean hasNext() {
@ -219,38 +227,36 @@ public class CollatingIterator implements Iterator {
/** /**
* Returns the next ordered element from a child iterator. * Returns the next ordered element from a child iterator.
* *
* @return the next ordered element * @return the next ordered element
* @throws NoSuchElementException if no child iterator has any more elements * @throws NoSuchElementException if no child iterator has any more elements
*/ */
public Object next() throws NoSuchElementException { public E next() throws NoSuchElementException {
if (hasNext() == false) { if (hasNext() == false) {
throw new NoSuchElementException(); throw new NoSuchElementException();
} }
int leastIndex = least(); int leastIndex = least();
if (leastIndex == -1) { if (leastIndex == -1) {
throw new NoSuchElementException(); throw new NoSuchElementException();
} else {
Object val = values.get(leastIndex);
clear(leastIndex);
lastReturned = leastIndex;
return val;
} }
E val = values.get(leastIndex);
clear(leastIndex);
lastReturned = leastIndex;
return val;
} }
/** /**
* Removes the last returned element from the child iterator that * Removes the last returned element from the child iterator that produced
* produced it. * it.
* *
* @throws IllegalStateException if there is no last returned element, * @throws IllegalStateException if there is no last returned element, or if
* or if the last returned element has already been removed * the last returned element has already been removed
*/ */
public void remove() { public void remove() {
if (lastReturned == -1) { if (lastReturned == -1) {
throw new IllegalStateException("No value can be removed at present"); throw new IllegalStateException("No value can be removed at present");
} }
Iterator it = (Iterator) (iterators.get(lastReturned)); iterators.get(lastReturned).remove();
it.remove();
} }
/** /**
@ -269,12 +275,12 @@ public class CollatingIterator implements Iterator {
// Private Methods // Private Methods
// ------------------------------------------------------------------- // -------------------------------------------------------------------
/** /**
* Initializes the collating state if it hasn't been already. * Initializes the collating state if it hasn't been already.
*/ */
private void start() { private void start() {
if (values == null) { if (values == null) {
values = new ArrayList(iterators.size()); values = new ArrayList<E>(iterators.size());
valueSet = new BitSet(iterators.size()); valueSet = new BitSet(iterators.size());
for (int i = 0; i < iterators.size(); i++) { for (int i = 0; i < iterators.size(); i++) {
values.add(null); values.add(null);
@ -283,40 +289,38 @@ public class CollatingIterator implements Iterator {
} }
} }
/** /**
* Sets the {@link #values} and {@link #valueSet} attributes * Sets the {@link #values} and {@link #valueSet} attributes at position
* at position <i>i</i> to the next value of the * <i>i</i> to the next value of the {@link #iterators iterator} at position
* {@link #iterators iterator} at position <i>i</i>, or * <i>i</i>, or clear them if the <i>i</i><sup>th</sup> iterator has no next
* clear them if the <i>i</i><sup>th</sup> iterator * value.
* has no next value. *
*
* @return <tt>false</tt> iff there was no value to set * @return <tt>false</tt> iff there was no value to set
*/ */
private boolean set(int i) { private boolean set(int i) {
Iterator it = (Iterator)(iterators.get(i)); Iterator<? extends E> it = iterators.get(i);
if (it.hasNext()) { if (it.hasNext()) {
values.set(i, it.next()); values.set(i, it.next());
valueSet.set(i); valueSet.set(i);
return true; return true;
} else {
values.set(i,null);
valueSet.clear(i);
return false;
} }
values.set(i, null);
valueSet.clear(i);
return false;
} }
/** /**
* Clears the {@link #values} and {@link #valueSet} attributes * Clears the {@link #values} and {@link #valueSet} attributes at position
* at position <i>i</i>. * <i>i</i>.
*/ */
private void clear(int i) { private void clear(int i) {
values.set(i,null); values.set(i, null);
valueSet.clear(i); valueSet.clear(i);
} }
/** /**
* Throws {@link IllegalStateException} if iteration has started * Throws {@link IllegalStateException} if iteration has started via
* via {@link #start}. * {@link #start}.
* *
* @throws IllegalStateException if iteration started * @throws IllegalStateException if iteration started
*/ */
@ -326,7 +330,7 @@ public class CollatingIterator implements Iterator {
} }
} }
/** /**
* Returns the index of the least element in {@link #values}, * Returns the index of the least element in {@link #values},
* {@link #set(int) setting} any uninitialized values. * {@link #set(int) setting} any uninitialized values.
* *
@ -334,7 +338,7 @@ public class CollatingIterator implements Iterator {
*/ */
private int least() { private int least() {
int leastIndex = -1; int leastIndex = -1;
Object leastObject = null; E leastObject = null;
for (int i = 0; i < values.size(); i++) { for (int i = 0; i < values.size(); i++) {
if (valueSet.get(i) == false) { if (valueSet.get(i) == false) {
set(i); set(i);
@ -344,8 +348,8 @@ public class CollatingIterator implements Iterator {
leastIndex = i; leastIndex = i;
leastObject = values.get(i); leastObject = values.get(i);
} else { } else {
Object curObject = values.get(i); E curObject = values.get(i);
if (comparator.compare(curObject,leastObject) < 0) { if (comparator.compare(curObject, leastObject) < 0) {
leastObject = curObject; leastObject = curObject;
leastIndex = i; leastIndex = i;
} }
@ -356,7 +360,7 @@ public class CollatingIterator implements Iterator {
} }
/** /**
* Returns <code>true</code> iff any bit in the given set is * Returns <code>true</code> iff any bit in the given set is
* <code>true</code>. * <code>true</code>.
*/ */
private boolean anyValueSet(BitSet set) { private boolean anyValueSet(BitSet set) {
@ -369,13 +373,12 @@ public class CollatingIterator implements Iterator {
} }
/** /**
* Returns <code>true</code> iff any {@link Iterator} * Returns <code>true</code> iff any {@link Iterator} in the given list has
* in the given list has a next value. * a next value.
*/ */
private boolean anyHasNext(ArrayList iters) { private boolean anyHasNext(ArrayList<Iterator<? extends E>> iters) {
for (int i = 0; i < iters.size(); i++) { for (Iterator<? extends E> iterator : iters) {
Iterator it = (Iterator) iters.get(i); if (iterator.hasNext()) {
if (it.hasNext()) {
return true; return true;
} }
} }

View File

@ -32,18 +32,39 @@ import org.apache.commons.collections.ResettableIterator;
* *
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public class EmptyIterator extends AbstractEmptyIterator implements ResettableIterator { public class EmptyIterator<E> extends AbstractEmptyIterator<E> implements ResettableIterator<E> {
/** /**
* Singleton instance of the iterator. * Singleton instance of the iterator.
* @since Commons Collections 3.1 * @since Commons Collections 3.1
*/ */
public static final ResettableIterator RESETTABLE_INSTANCE = new EmptyIterator(); public static final ResettableIterator<Object> RESETTABLE_INSTANCE = new EmptyIterator<Object>();
/** /**
* Singleton instance of the iterator. * Singleton instance of the iterator.
* @since Commons Collections 2.1.1 and 3.1 * @since Commons Collections 2.1.1 and 3.1
*/ */
public static final Iterator INSTANCE = RESETTABLE_INSTANCE; public static final Iterator<Object> INSTANCE = RESETTABLE_INSTANCE;
/**
* Get a typed resettable empty iterator instance.
* @param <E>
* @return ResettableIterator<E>
*/
@SuppressWarnings("unchecked")
public static <E> ResettableIterator<E> getResettableInstance() {
return (ResettableIterator<E>) RESETTABLE_INSTANCE;
}
/**
* Get a typed empty iterator instance.
* @param <E>
* @return Iterator<E>
*/
@SuppressWarnings("unchecked")
public static <E> Iterator<E> getInstance() {
return (Iterator<E>) INSTANCE;
}
/** /**
* Constructor. * Constructor.

View File

@ -20,30 +20,52 @@ import java.util.ListIterator;
import org.apache.commons.collections.ResettableListIterator; import org.apache.commons.collections.ResettableListIterator;
/** /**
* Provides an implementation of an empty list iterator. * Provides an implementation of an empty list iterator.
* <p> * <p>
* This class provides an implementation of an empty list iterator. * This class provides an implementation of an empty list iterator. This class
* This class provides for binary compatability between Commons Collections * provides for binary compatability between Commons Collections 2.1.1 and 3.1
* 2.1.1 and 3.1 due to issues with <code>IteratorUtils</code>. * due to issues with <code>IteratorUtils</code>.
* *
* @since Commons Collections 2.1.1 and 3.1 * @since Commons Collections 2.1.1 and 3.1
* @version $Revision$ $Date$ * @version $Revision$ $Date$
* *
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public class EmptyListIterator extends AbstractEmptyIterator implements ResettableListIterator { public class EmptyListIterator<E> extends AbstractEmptyIterator<E> implements
ResettableListIterator<E> {
/** /**
* Singleton instance of the iterator. * Singleton instance of the iterator.
* @since Commons Collections 3.1 * @since Commons Collections 3.1
*/ */
public static final ResettableListIterator RESETTABLE_INSTANCE = new EmptyListIterator(); public static final ResettableListIterator<Object> RESETTABLE_INSTANCE = new EmptyListIterator<Object>();
/** /**
* Singleton instance of the iterator. * Singleton instance of the iterator.
* @since Commons Collections 2.1.1 and 3.1 * @since Commons Collections 2.1.1 and 3.1
*/ */
public static final ListIterator INSTANCE = RESETTABLE_INSTANCE; public static final ListIterator<Object> INSTANCE = RESETTABLE_INSTANCE;
/**
* Get a typed instance of the iterator.
* @param <E>
* @return {@link ResettableListIterator}<E>
*/
@SuppressWarnings("unchecked")
public static <E> ResettableListIterator<E> getResettableInstance() {
return (ResettableListIterator<E>) RESETTABLE_INSTANCE;
}
/**
* Get a typed instance of the iterator.
* @param <E>
* @return {@link ListIterator}<E>
*/
@SuppressWarnings("unchecked")
public static <E> ListIterator<E> getInstance() {
return (ListIterator<E>) INSTANCE;
}
/** /**
* Constructor. * Constructor.

View File

@ -27,13 +27,25 @@ import org.apache.commons.collections.ResettableIterator;
* *
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public class EmptyMapIterator extends AbstractEmptyIterator implements MapIterator, ResettableIterator { public class EmptyMapIterator<K, V> extends AbstractEmptyMapIterator<K, V> implements
MapIterator<K, V>, ResettableIterator<K> {
/** /**
* Singleton instance of the iterator. * Singleton instance of the iterator.
* @since Commons Collections 3.1 * @since Commons Collections 3.1
*/ */
public static final MapIterator INSTANCE = new EmptyMapIterator(); public static final MapIterator<Object, Object> INSTANCE = new EmptyMapIterator<Object, Object>();
/**
* Get a typed instance of the iterator.
* @param <K>
* @param <V>
* @return {@link MapIterator}<K, V>
*/
@SuppressWarnings("unchecked")
public static <K, V> MapIterator<K, V> getInstance() {
return (MapIterator<K, V>) INSTANCE;
}
/** /**
* Constructor. * Constructor.

View File

@ -27,13 +27,23 @@ import org.apache.commons.collections.ResettableIterator;
* *
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public class EmptyOrderedIterator extends AbstractEmptyIterator implements OrderedIterator, ResettableIterator { public class EmptyOrderedIterator<E> extends AbstractEmptyIterator<E> implements OrderedIterator<E>, ResettableIterator<E> {
/** /**
* Singleton instance of the iterator. * Singleton instance of the iterator.
* @since Commons Collections 3.1 * @since Commons Collections 3.1
*/ */
public static final OrderedIterator INSTANCE = new EmptyOrderedIterator(); public static final OrderedIterator<Object> INSTANCE = new EmptyOrderedIterator<Object>();
/**
* Typed instance of the iterator.
* @param <E>
* @return OrderedIterator<E>
*/
@SuppressWarnings("unchecked")
public static <E> OrderedIterator<E> getInstance() {
return (OrderedIterator<E>) INSTANCE;
}
/** /**
* Constructor. * Constructor.

View File

@ -27,13 +27,25 @@ import org.apache.commons.collections.ResettableIterator;
* *
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public class EmptyOrderedMapIterator extends AbstractEmptyIterator implements OrderedMapIterator, ResettableIterator { public class EmptyOrderedMapIterator<K, V> extends AbstractEmptyMapIterator<K, V> implements
OrderedMapIterator<K, V>, ResettableIterator<K> {
/** /**
* Singleton instance of the iterator. * Singleton instance of the iterator.
* @since Commons Collections 3.1 * @since Commons Collections 3.1
*/ */
public static final OrderedMapIterator INSTANCE = new EmptyOrderedMapIterator(); public static final OrderedMapIterator<Object, Object> INSTANCE = new EmptyOrderedMapIterator<Object, Object>();
/**
* Get a typed instance of the iterator.
* @param <K>
* @param <V>
* @return {@link OrderedMapIterator}<K, V>
*/
@SuppressWarnings("unchecked")
public static <K, V> OrderedMapIterator<K, V> getInstance() {
return (OrderedMapIterator<K, V>) INSTANCE;
}
/** /**
* Constructor. * Constructor.

View File

@ -39,11 +39,11 @@ import org.apache.commons.collections.ResettableIterator;
* *
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public class EntrySetMapIterator implements MapIterator, ResettableIterator { public class EntrySetMapIterator<K, V> implements MapIterator<K, V>, ResettableIterator<K> {
private final Map map; private final Map<K, V> map;
private Iterator iterator; private Iterator<Map.Entry<K, V>> iterator;
private Map.Entry last; private Map.Entry<K, V> last;
private boolean canRemove = false; private boolean canRemove = false;
/** /**
@ -51,7 +51,7 @@ public class EntrySetMapIterator implements MapIterator, ResettableIterator {
* *
* @param map the map to iterate over * @param map the map to iterate over
*/ */
public EntrySetMapIterator(Map map) { public EntrySetMapIterator(Map<K, V> map) {
super(); super();
this.map = map; this.map = map;
this.iterator = map.entrySet().iterator(); this.iterator = map.entrySet().iterator();
@ -73,8 +73,8 @@ public class EntrySetMapIterator implements MapIterator, ResettableIterator {
* @return the next key in the iteration * @return the next key in the iteration
* @throws java.util.NoSuchElementException if the iteration is finished * @throws java.util.NoSuchElementException if the iteration is finished
*/ */
public Object next() { public K next() {
last = (Map.Entry) iterator.next(); last = (Map.Entry<K, V>) iterator.next();
canRemove = true; canRemove = true;
return last.getKey(); return last.getKey();
} }
@ -107,7 +107,7 @@ public class EntrySetMapIterator implements MapIterator, ResettableIterator {
* @return the current key * @return the current key
* @throws IllegalStateException if <code>next()</code> has not yet been called * @throws IllegalStateException if <code>next()</code> has not yet been called
*/ */
public Object getKey() { public K getKey() {
if (last == null) { if (last == null) {
throw new IllegalStateException("Iterator getKey() can only be called after next() and before remove()"); throw new IllegalStateException("Iterator getKey() can only be called after next() and before remove()");
} }
@ -121,7 +121,7 @@ public class EntrySetMapIterator implements MapIterator, ResettableIterator {
* @return the current value * @return the current value
* @throws IllegalStateException if <code>next()</code> has not yet been called * @throws IllegalStateException if <code>next()</code> has not yet been called
*/ */
public Object getValue() { public V getValue() {
if (last == null) { if (last == null) {
throw new IllegalStateException("Iterator getValue() can only be called after next() and before remove()"); throw new IllegalStateException("Iterator getValue() can only be called after next() and before remove()");
} }
@ -138,7 +138,7 @@ public class EntrySetMapIterator implements MapIterator, ResettableIterator {
* @throws IllegalStateException if <code>remove()</code> has been called since the * @throws IllegalStateException if <code>remove()</code> has been called since the
* last call to <code>next()</code> * last call to <code>next()</code>
*/ */
public Object setValue(Object value) { public V setValue(V value) {
if (last == null) { if (last == null) {
throw new IllegalStateException("Iterator setValue() can only be called after next() and before remove()"); throw new IllegalStateException("Iterator setValue() can only be called after next() and before remove()");
} }
@ -163,9 +163,8 @@ public class EntrySetMapIterator implements MapIterator, ResettableIterator {
public String toString() { public String toString() {
if (last != null) { if (last != null) {
return "MapIterator[" + getKey() + "=" + getValue() + "]"; return "MapIterator[" + getKey() + "=" + getValue() + "]";
} else {
return "MapIterator[]";
} }
return "MapIterator[]";
} }
} }

View File

@ -30,14 +30,14 @@ import java.util.Iterator;
* @author <a href="mailto:jstrachan@apache.org">James Strachan</a> * @author <a href="mailto:jstrachan@apache.org">James Strachan</a>
* @author <a href="mailto:dlr@finemaltcoding.com">Daniel Rall</a> * @author <a href="mailto:dlr@finemaltcoding.com">Daniel Rall</a>
*/ */
public class EnumerationIterator implements Iterator { public class EnumerationIterator<E> implements Iterator<E> {
/** The collection to remove elements from */ /** The collection to remove elements from */
private Collection collection; private Collection<? super E> collection;
/** The enumeration being converted */ /** The enumeration being converted */
private Enumeration enumeration; private Enumeration<? extends E> enumeration;
/** The last object retrieved */ /** The last object retrieved */
private Object last; private E last;
// Constructors // Constructors
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
@ -55,7 +55,7 @@ public class EnumerationIterator implements Iterator {
* *
* @param enumeration the enumeration to use * @param enumeration the enumeration to use
*/ */
public EnumerationIterator(final Enumeration enumeration) { public EnumerationIterator(final Enumeration<? extends E> enumeration) {
this(enumeration, null); this(enumeration, null);
} }
@ -64,9 +64,9 @@ public class EnumerationIterator implements Iterator {
* elements from the specified collection. * elements from the specified collection.
* *
* @param enumeration the enumeration to use * @param enumeration the enumeration to use
* @param collection the collection to remove elements form * @param collection the collection to remove elements from
*/ */
public EnumerationIterator(final Enumeration enumeration, final Collection collection) { public EnumerationIterator(final Enumeration<? extends E> enumeration, final Collection<? super E> collection) {
super(); super();
this.enumeration = enumeration; this.enumeration = enumeration;
this.collection = collection; this.collection = collection;
@ -91,7 +91,7 @@ public class EnumerationIterator implements Iterator {
* @return the next object from the enumeration * @return the next object from the enumeration
* @throws NullPointerException if the enumeration is null * @throws NullPointerException if the enumeration is null
*/ */
public Object next() { public E next() {
last = enumeration.nextElement(); last = enumeration.nextElement();
return last; return last;
} }
@ -125,7 +125,7 @@ public class EnumerationIterator implements Iterator {
* *
* @return the underlying enumeration * @return the underlying enumeration
*/ */
public Enumeration getEnumeration() { public Enumeration<? extends E> getEnumeration() {
return enumeration; return enumeration;
} }
@ -134,7 +134,7 @@ public class EnumerationIterator implements Iterator {
* *
* @param enumeration the new underlying enumeration * @param enumeration the new underlying enumeration
*/ */
public void setEnumeration(final Enumeration enumeration) { public void setEnumeration(final Enumeration<? extends E> enumeration) {
this.enumeration = enumeration; this.enumeration = enumeration;
} }

View File

@ -35,14 +35,14 @@ import org.apache.commons.collections.Predicate;
* @author Ralph Wagner * @author Ralph Wagner
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public class FilterIterator implements Iterator { public class FilterIterator<E> implements Iterator<E> {
/** The iterator being used */ /** The iterator being used */
private Iterator iterator; private Iterator<? extends E> iterator;
/** The predicate being used */ /** The predicate being used */
private Predicate predicate; private Predicate<? super E> predicate;
/** The next object in the iteration */ /** The next object in the iteration */
private Object nextObject; private E nextObject;
/** Whether the next object has been calculated yet */ /** Whether the next object has been calculated yet */
private boolean nextObjectSet = false; private boolean nextObjectSet = false;
@ -61,7 +61,7 @@ public class FilterIterator implements Iterator {
* *
* @param iterator the iterator to use * @param iterator the iterator to use
*/ */
public FilterIterator(Iterator iterator) { public FilterIterator(Iterator<? extends E> iterator) {
super(); super();
this.iterator = iterator; this.iterator = iterator;
} }
@ -73,7 +73,7 @@ public class FilterIterator implements Iterator {
* @param iterator the iterator to use * @param iterator the iterator to use
* @param predicate the predicate to use * @param predicate the predicate to use
*/ */
public FilterIterator(Iterator iterator, Predicate predicate) { public FilterIterator(Iterator<? extends E> iterator, Predicate<? super E> predicate) {
super(); super();
this.iterator = iterator; this.iterator = iterator;
this.predicate = predicate; this.predicate = predicate;
@ -88,11 +88,7 @@ public class FilterIterator implements Iterator {
* @throws NullPointerException if either the iterator or predicate are null * @throws NullPointerException if either the iterator or predicate are null
*/ */
public boolean hasNext() { public boolean hasNext() {
if (nextObjectSet) { return nextObjectSet || setNextObject();
return true;
} else {
return setNextObject();
}
} }
/** /**
@ -103,7 +99,7 @@ public class FilterIterator implements Iterator {
* @throws NoSuchElementException if there are no more elements that * @throws NoSuchElementException if there are no more elements that
* match the predicate * match the predicate
*/ */
public Object next() { public E next() {
if (!nextObjectSet) { if (!nextObjectSet) {
if (!setNextObject()) { if (!setNextObject()) {
throw new NoSuchElementException(); throw new NoSuchElementException();
@ -137,7 +133,7 @@ public class FilterIterator implements Iterator {
* *
* @return the iterator * @return the iterator
*/ */
public Iterator getIterator() { public Iterator<? extends E> getIterator() {
return iterator; return iterator;
} }
@ -147,7 +143,7 @@ public class FilterIterator implements Iterator {
* *
* @param iterator the iterator to use * @param iterator the iterator to use
*/ */
public void setIterator(Iterator iterator) { public void setIterator(Iterator<? extends E> iterator) {
this.iterator = iterator; this.iterator = iterator;
nextObject = null; nextObject = null;
nextObjectSet = false; nextObjectSet = false;
@ -159,7 +155,7 @@ public class FilterIterator implements Iterator {
* *
* @return the predicate * @return the predicate
*/ */
public Predicate getPredicate() { public Predicate<? super E> getPredicate() {
return predicate; return predicate;
} }
@ -168,7 +164,7 @@ public class FilterIterator implements Iterator {
* *
* @param predicate the predicate to use * @param predicate the predicate to use
*/ */
public void setPredicate(Predicate predicate) { public void setPredicate(Predicate<? super E> predicate) {
this.predicate = predicate; this.predicate = predicate;
nextObject = null; nextObject = null;
nextObjectSet = false; nextObjectSet = false;
@ -181,7 +177,7 @@ public class FilterIterator implements Iterator {
*/ */
private boolean setNextObject() { private boolean setNextObject() {
while (iterator.hasNext()) { while (iterator.hasNext()) {
Object object = iterator.next(); E object = iterator.next();
if (predicate.evaluate(object)) { if (predicate.evaluate(object)) {
nextObject = object; nextObject = object;
nextObjectSet = true; nextObjectSet = true;

View File

@ -32,19 +32,19 @@ import org.apache.commons.collections.Predicate;
* *
* @author Rodney Waldhoff * @author Rodney Waldhoff
*/ */
public class FilterListIterator implements ListIterator { public class FilterListIterator<E> implements ListIterator<E> {
/** The iterator being used */ /** The iterator being used */
private ListIterator iterator; private ListIterator<? extends E> iterator;
/** The predicate being used */ /** The predicate being used */
private Predicate predicate; private Predicate<? super E> predicate;
/** /**
* The value of the next (matching) object, when * The value of the next (matching) object, when
* {@link #nextObjectSet} is true. * {@link #nextObjectSet} is true.
*/ */
private Object nextObject; private E nextObject;
/** /**
* Whether or not the {@link #nextObject} has been set * Whether or not the {@link #nextObject} has been set
@ -56,7 +56,7 @@ public class FilterListIterator implements ListIterator {
* The value of the previous (matching) object, when * The value of the previous (matching) object, when
* {@link #previousObjectSet} is true. * {@link #previousObjectSet} is true.
*/ */
private Object previousObject; private E previousObject;
/** /**
* Whether or not the {@link #previousObject} has been set * Whether or not the {@link #previousObject} has been set
@ -85,7 +85,7 @@ public class FilterListIterator implements ListIterator {
* *
* @param iterator the iterator to use * @param iterator the iterator to use
*/ */
public FilterListIterator(ListIterator iterator ) { public FilterListIterator(ListIterator<? extends E> iterator ) {
super(); super();
this.iterator = iterator; this.iterator = iterator;
} }
@ -96,7 +96,7 @@ public class FilterListIterator implements ListIterator {
* @param iterator the iterator to use * @param iterator the iterator to use
* @param predicate the predicate to use * @param predicate the predicate to use
*/ */
public FilterListIterator(ListIterator iterator, Predicate predicate) { public FilterListIterator(ListIterator<? extends E> iterator, Predicate<? super E> predicate) {
super(); super();
this.iterator = iterator; this.iterator = iterator;
this.predicate = predicate; this.predicate = predicate;
@ -108,41 +108,33 @@ public class FilterListIterator implements ListIterator {
* *
* @param predicate the predicate to use. * @param predicate the predicate to use.
*/ */
public FilterListIterator(Predicate predicate) { public FilterListIterator(Predicate<? super E> predicate) {
super(); super();
this.predicate = predicate; this.predicate = predicate;
} }
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
/** Not supported. */ /** Not supported. */
public void add(Object o) { public void add(E o) {
throw new UnsupportedOperationException("FilterListIterator.add(Object) is not supported."); throw new UnsupportedOperationException("FilterListIterator.add(Object) is not supported.");
} }
public boolean hasNext() { public boolean hasNext() {
if(nextObjectSet) { return nextObjectSet || setNextObject();
return true;
} else {
return setNextObject();
}
} }
public boolean hasPrevious() { public boolean hasPrevious() {
if(previousObjectSet) { return previousObjectSet || setPreviousObject();
return true;
} else {
return setPreviousObject();
}
} }
public Object next() { public E next() {
if(!nextObjectSet) { if (!nextObjectSet) {
if(!setNextObject()) { if (!setNextObject()) {
throw new NoSuchElementException(); throw new NoSuchElementException();
} }
} }
nextIndex++; nextIndex++;
Object temp = nextObject; E temp = nextObject;
clearNextObject(); clearNextObject();
return temp; return temp;
} }
@ -151,14 +143,14 @@ public class FilterListIterator implements ListIterator {
return nextIndex; return nextIndex;
} }
public Object previous() { public E previous() {
if(!previousObjectSet) { if (!previousObjectSet) {
if(!setPreviousObject()) { if (!setPreviousObject()) {
throw new NoSuchElementException(); throw new NoSuchElementException();
} }
} }
nextIndex--; nextIndex--;
Object temp = previousObject; E temp = previousObject;
clearPreviousObject(); clearPreviousObject();
return temp; return temp;
} }
@ -173,7 +165,7 @@ public class FilterListIterator implements ListIterator {
} }
/** Not supported. */ /** Not supported. */
public void set(Object o) { public void set(E o) {
throw new UnsupportedOperationException("FilterListIterator.set(Object) is not supported."); throw new UnsupportedOperationException("FilterListIterator.set(Object) is not supported.");
} }
@ -183,7 +175,7 @@ public class FilterListIterator implements ListIterator {
* *
* @return the iterator. * @return the iterator.
*/ */
public ListIterator getListIterator() { public ListIterator<? extends E> getListIterator() {
return iterator; return iterator;
} }
@ -193,7 +185,7 @@ public class FilterListIterator implements ListIterator {
* *
* @param iterator the iterator to use * @param iterator the iterator to use
*/ */
public void setListIterator(ListIterator iterator) { public void setListIterator(ListIterator<? extends E> iterator) {
this.iterator = iterator; this.iterator = iterator;
} }
@ -203,7 +195,7 @@ public class FilterListIterator implements ListIterator {
* *
* @return the predicate. * @return the predicate.
*/ */
public Predicate getPredicate() { public Predicate<? super E> getPredicate() {
return predicate; return predicate;
} }
@ -212,7 +204,7 @@ public class FilterListIterator implements ListIterator {
* *
* @param predicate the transformer to use * @param predicate the transformer to use
*/ */
public void setPredicate(Predicate predicate) { public void setPredicate(Predicate<? super E> predicate) {
this.predicate = predicate; this.predicate = predicate;
} }
@ -227,18 +219,17 @@ public class FilterListIterator implements ListIterator {
// then we've walked back one step in the // then we've walked back one step in the
// underlying list (due to a hasPrevious() call) // underlying list (due to a hasPrevious() call)
// so skip ahead one matching object // so skip ahead one matching object
if(previousObjectSet) { if (previousObjectSet) {
clearPreviousObject(); clearPreviousObject();
if(!setNextObject()) { if (!setNextObject()) {
return false; return false;
} else {
clearNextObject();
} }
clearNextObject();
} }
while(iterator.hasNext()) { while (iterator.hasNext()) {
Object object = iterator.next(); E object = iterator.next();
if(predicate.evaluate(object)) { if (predicate.evaluate(object)) {
nextObject = object; nextObject = object;
nextObjectSet = true; nextObjectSet = true;
return true; return true;
@ -257,18 +248,17 @@ public class FilterListIterator implements ListIterator {
// then we've walked back one step in the // then we've walked back one step in the
// underlying list (due to a hasNext() call) // underlying list (due to a hasNext() call)
// so skip ahead one matching object // so skip ahead one matching object
if(nextObjectSet) { if (nextObjectSet) {
clearNextObject(); clearNextObject();
if(!setPreviousObject()) { if (!setPreviousObject()) {
return false; return false;
} else {
clearPreviousObject();
} }
clearPreviousObject();
} }
while(iterator.hasPrevious()) { while (iterator.hasPrevious()) {
Object object = iterator.previous(); E object = iterator.previous();
if(predicate.evaluate(object)) { if (predicate.evaluate(object)) {
previousObject = object; previousObject = object;
previousObjectSet = true; previousObjectSet = true;
return true; return true;

View File

@ -26,45 +26,50 @@ import org.apache.commons.collections.list.UnmodifiableList;
/** /**
* An IteratorChain is an Iterator that wraps a number of Iterators. * An IteratorChain is an Iterator that wraps a number of Iterators.
* <p> * <p>
* This class makes multiple iterators look like one to the caller * This class makes multiple iterators look like one to the caller When any
* When any method from the Iterator interface is called, the IteratorChain * method from the Iterator interface is called, the IteratorChain will delegate
* will delegate to a single underlying Iterator. The IteratorChain will * to a single underlying Iterator. The IteratorChain will invoke the Iterators
* invoke the Iterators in sequence until all Iterators are exhausted. * in sequence until all Iterators are exhausted.
* <p> * <p>
* Under many circumstances, linking Iterators together in this manner is * Under many circumstances, linking Iterators together in this manner is more
* more efficient (and convenient) than reading out the contents of each * efficient (and convenient) than reading out the contents of each Iterator
* Iterator into a List and creating a new Iterator. * into a List and creating a new Iterator.
* <p> * <p>
* Calling a method that adds new Iterator<i>after a method in the Iterator * Calling a method that adds new Iterator<i>after a method in the Iterator
* interface has been called</i> will result in an UnsupportedOperationException. * interface has been called</i> will result in an
* Subclasses should <i>take care</i> to not alter the underlying List of Iterators. * UnsupportedOperationException. Subclasses should <i>take care</i> to not
* alter the underlying List of Iterators.
* <p> * <p>
* NOTE: As from version 3.0, the IteratorChain may contain no * NOTE: As from version 3.0, the IteratorChain may contain no iterators. In
* iterators. In this case the class will function as an empty iterator. * this case the class will function as an empty iterator.
* *
* @since Commons Collections 2.1 * @since Commons Collections 2.1
* @version $Revision$ $Date$ * @version $Revision$ $Date: 2006-10-27 19:52:37 -0500 (Fri, 27 Oct
* 2006) $
* *
* @author Morgan Delagrange * @author Morgan Delagrange
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public class IteratorChain implements Iterator { public class IteratorChain<E> implements Iterator<E> {
/** The chain of iterators */ /** The chain of iterators */
protected final List iteratorChain = new ArrayList(); protected final List<Iterator<? extends E>> iteratorChain = new ArrayList<Iterator<? extends E>>();
/** The index of the current iterator */ /** The index of the current iterator */
protected int currentIteratorIndex = 0; protected int currentIteratorIndex = 0;
/** The current iterator */ /** The current iterator */
protected Iterator currentIterator = null; protected Iterator<? extends E> currentIterator = null;
/** /**
* The "last used" Iterator is the Iterator upon which * The "last used" Iterator is the Iterator upon which next() or hasNext()
* next() or hasNext() was most recently called * was most recently called used for the remove() operation only
* used for the remove() operation only
*/ */
protected Iterator lastUsedIterator = null; protected Iterator<? extends E> lastUsedIterator = null;
/** /**
* ComparatorChain is "locked" after the first time * ComparatorChain is "locked" after the first time compare(Object,Object)
* compare(Object,Object) is called * is called
*/ */
protected boolean isLocked = false; protected boolean isLocked = false;
@ -72,8 +77,8 @@ public class IteratorChain implements Iterator {
/** /**
* Construct an IteratorChain with no Iterators. * Construct an IteratorChain with no Iterators.
* <p> * <p>
* You will normally use {@link #addIterator(Iterator)} to add * You will normally use {@link #addIterator(Iterator)} to add some
* some iterators after using this constructor. * iterators after using this constructor.
*/ */
public IteratorChain() { public IteratorChain() {
super(); super();
@ -82,49 +87,47 @@ public class IteratorChain implements Iterator {
/** /**
* Construct an IteratorChain with a single Iterator. * Construct an IteratorChain with a single Iterator.
* <p> * <p>
* This method takes one iterator. The newly constructed iterator * This method takes one iterator. The newly constructed iterator will
* will iterate through that iterator. Thus calling this constructor * iterate through that iterator. Thus calling this constructor on its own
* on its own will have no effect other than decorating the input iterator. * will have no effect other than decorating the input iterator.
* <p> * <p>
* You will normally use {@link #addIterator(Iterator)} to add * You will normally use {@link #addIterator(Iterator)} to add some more
* some more iterators after using this constructor. * iterators after using this constructor.
* *
* @param iterator the first child iterator in the IteratorChain, not null * @param iterator the first child iterator in the IteratorChain, not null
* @throws NullPointerException if the iterator is null * @throws NullPointerException if the iterator is null
*/ */
public IteratorChain(Iterator iterator) { public IteratorChain(Iterator<? extends E> iterator) {
super(); super();
addIterator(iterator); addIterator(iterator);
} }
/** /**
* Constructs a new <code>IteratorChain</code> over the two * Constructs a new <code>IteratorChain</code> over the two given iterators.
* given iterators.
* <p> * <p>
* This method takes two iterators. The newly constructed iterator * This method takes two iterators. The newly constructed iterator will
* will iterate through each one of the input iterators in turn. * iterate through each one of the input iterators in turn.
* *
* @param first the first child iterator in the IteratorChain, not null * @param first the first child iterator in the IteratorChain, not null
* @param second the second child iterator in the IteratorChain, not null * @param second the second child iterator in the IteratorChain, not null
* @throws NullPointerException if either iterator is null * @throws NullPointerException if either iterator is null
*/ */
public IteratorChain(Iterator first, Iterator second) { public IteratorChain(Iterator<? extends E> first, Iterator<? extends E> second) {
super(); super();
addIterator(first); addIterator(first);
addIterator(second); addIterator(second);
} }
/** /**
* Constructs a new <code>IteratorChain</code> over the array * Constructs a new <code>IteratorChain</code> over the array of iterators.
* of iterators.
* <p> * <p>
* This method takes an array of iterators. The newly constructed iterator * This method takes an array of iterators. The newly constructed iterator
* will iterate through each one of the input iterators in turn. * will iterate through each one of the input iterators in turn.
* *
* @param iteratorChain the array of iterators, not null * @param iteratorChain the array of iterators, not null
* @throws NullPointerException if iterators array is or contains null * @throws NullPointerException if iterators array is or contains null
*/ */
public IteratorChain(Iterator[] iteratorChain) { public IteratorChain(Iterator<? extends E>[] iteratorChain) {
super(); super();
for (int i = 0; i < iteratorChain.length; i++) { for (int i = 0; i < iteratorChain.length; i++) {
addIterator(iteratorChain[i]); addIterator(iteratorChain[i]);
@ -132,33 +135,33 @@ public class IteratorChain implements Iterator {
} }
/** /**
* Constructs a new <code>IteratorChain</code> over the collection * Constructs a new <code>IteratorChain</code> over the collection of
* of iterators. * iterators.
* <p> * <p>
* This method takes a collection of iterators. The newly constructed iterator * This method takes a collection of iterators. The newly constructed
* will iterate through each one of the input iterators in turn. * iterator will iterate through each one of the input iterators in turn.
* *
* @param iteratorChain the collection of iterators, not null * @param iteratorChain the collection of iterators, not null
* @throws NullPointerException if iterators collection is or contains null * @throws NullPointerException if iterators collection is or contains null
* @throws ClassCastException if iterators collection doesn't contain an iterator * @throws ClassCastException if iterators collection doesn't contain an
* iterator
*/ */
public IteratorChain(Collection iteratorChain) { public IteratorChain(Collection<Iterator<? extends E>> iteratorChain) {
super(); super();
for (Iterator it = iteratorChain.iterator(); it.hasNext();) { for (Iterator<? extends E> iterator : iteratorChain) {
Iterator item = (Iterator) it.next(); addIterator(iterator);
addIterator(item);
} }
} }
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
/** /**
* Add an Iterator to the end of the chain * Add an Iterator to the end of the chain
* *
* @param iterator Iterator to add * @param iterator Iterator to add
* @throws IllegalStateException if I've already started iterating * @throws IllegalStateException if I've already started iterating
* @throws NullPointerException if the iterator is null * @throws NullPointerException if the iterator is null
*/ */
public void addIterator(Iterator iterator) { public void addIterator(Iterator<? extends E> iterator) {
checkLocked(); checkLocked();
if (iterator == null) { if (iterator == null) {
throw new NullPointerException("Iterator must not be null"); throw new NullPointerException("Iterator must not be null");
@ -168,14 +171,15 @@ public class IteratorChain implements Iterator {
/** /**
* Set the Iterator at the given index * Set the Iterator at the given index
* *
* @param index index of the Iterator to replace * @param index index of the Iterator to replace
* @param iterator Iterator to place at the given index * @param iterator Iterator to place at the given index
* @throws IndexOutOfBoundsException if index &lt; 0 or index &gt; size() * @throws IndexOutOfBoundsException if index &lt; 0 or index &gt; size()
* @throws IllegalStateException if I've already started iterating * @throws IllegalStateException if I've already started iterating
* @throws NullPointerException if the iterator is null * @throws NullPointerException if the iterator is null
*/ */
public void setIterator(int index, Iterator iterator) throws IndexOutOfBoundsException { public void setIterator(int index, Iterator<? extends E> iterator)
throws IndexOutOfBoundsException {
checkLocked(); checkLocked();
if (iterator == null) { if (iterator == null) {
throw new NullPointerException("Iterator must not be null"); throw new NullPointerException("Iterator must not be null");
@ -185,16 +189,16 @@ public class IteratorChain implements Iterator {
/** /**
* Get the list of Iterators (unmodifiable) * Get the list of Iterators (unmodifiable)
* *
* @return the unmodifiable list of iterators added * @return the unmodifiable list of iterators added
*/ */
public List getIterators() { public List<Iterator<? extends E>> getIterators() {
return UnmodifiableList.decorate(iteratorChain); return UnmodifiableList.decorate(iteratorChain);
} }
/** /**
* Number of Iterators in the current IteratorChain. * Number of Iterators in the current IteratorChain.
* *
* @return Iterator count * @return Iterator count
*/ */
public int size() { public int size() {
@ -203,9 +207,9 @@ public class IteratorChain implements Iterator {
/** /**
* Determine if modifications can still be made to the IteratorChain. * Determine if modifications can still be made to the IteratorChain.
* IteratorChains cannot be modified once they have executed a method * IteratorChains cannot be modified once they have executed a method from
* from the Iterator interface. * the Iterator interface.
* *
* @return true if IteratorChain cannot be modified, false if it can * @return true if IteratorChain cannot be modified, false if it can
*/ */
public boolean isLocked() { public boolean isLocked() {
@ -217,13 +221,14 @@ public class IteratorChain implements Iterator {
*/ */
private void checkLocked() { private void checkLocked() {
if (isLocked == true) { if (isLocked == true) {
throw new UnsupportedOperationException("IteratorChain cannot be changed after the first use of a method from the Iterator interface"); throw new UnsupportedOperationException(
"IteratorChain cannot be changed after the first use of a method from the Iterator interface");
} }
} }
/** /**
* Lock the chain so no more iterators can be added. * Lock the chain so no more iterators can be added. This must be called
* This must be called from all Iterator interface methods. * from all Iterator interface methods.
*/ */
private void lockChain() { private void lockChain() {
if (isLocked == false) { if (isLocked == false) {
@ -232,31 +237,32 @@ public class IteratorChain implements Iterator {
} }
/** /**
* Updates the current iterator field to ensure that the current Iterator * Updates the current iterator field to ensure that the current Iterator is
* is not exhausted * not exhausted
*/ */
protected void updateCurrentIterator() { protected void updateCurrentIterator() {
if (currentIterator == null) { if (currentIterator == null) {
if (iteratorChain.isEmpty()) { if (iteratorChain.isEmpty()) {
currentIterator = EmptyIterator.INSTANCE; currentIterator = EmptyIterator.<E> getInstance();
} else { } else {
currentIterator = (Iterator) iteratorChain.get(0); currentIterator = iteratorChain.get(0);
} }
// set last used iterator here, in case the user calls remove // set last used iterator here, in case the user calls remove
// before calling hasNext() or next() (although they shouldn't) // before calling hasNext() or next() (although they shouldn't)
lastUsedIterator = currentIterator; lastUsedIterator = currentIterator;
} }
while (currentIterator.hasNext() == false && currentIteratorIndex < iteratorChain.size() - 1) { while (currentIterator.hasNext() == false
&& currentIteratorIndex < iteratorChain.size() - 1) {
currentIteratorIndex++; currentIteratorIndex++;
currentIterator = (Iterator) iteratorChain.get(currentIteratorIndex); currentIterator = iteratorChain.get(currentIteratorIndex);
} }
} }
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
/** /**
* Return true if any Iterator in the IteratorChain has a remaining element. * Return true if any Iterator in the IteratorChain has a remaining element.
* *
* @return true if elements remain * @return true if elements remain
*/ */
public boolean hasNext() { public boolean hasNext() {
@ -269,11 +275,12 @@ public class IteratorChain implements Iterator {
/** /**
* Returns the next Object of the current Iterator * Returns the next Object of the current Iterator
* *
* @return Object from the current Iterator * @return Object from the current Iterator
* @throws java.util.NoSuchElementException if all the Iterators are exhausted * @throws java.util.NoSuchElementException if all the Iterators are
* exhausted
*/ */
public Object next() { public E next() {
lockChain(); lockChain();
updateCurrentIterator(); updateCurrentIterator();
lastUsedIterator = currentIterator; lastUsedIterator = currentIterator;
@ -282,18 +289,17 @@ public class IteratorChain implements Iterator {
} }
/** /**
* Removes from the underlying collection the last element * Removes from the underlying collection the last element returned by the
* returned by the Iterator. As with next() and hasNext(), * Iterator. As with next() and hasNext(), this method calls remove() on the
* this method calls remove() on the underlying Iterator. * underlying Iterator. Therefore, this method may throw an
* Therefore, this method may throw an * UnsupportedOperationException if the underlying Iterator does not support
* UnsupportedOperationException if the underlying * this method.
* Iterator does not support this method. *
* * @throws UnsupportedOperationException if the remove operator is not
* @throws UnsupportedOperationException * supported by the underlying Iterator
* if the remove operator is not supported by the underlying Iterator * @throws IllegalStateException if the next method has not yet been called,
* @throws IllegalStateException * or the remove method has already been called after the last call to the
* if the next method has not yet been called, or the remove method has * next method.
* already been called after the last call to the next method.
*/ */
public void remove() { public void remove() {
lockChain(); lockChain();

View File

@ -19,36 +19,35 @@ package org.apache.commons.collections.iterators;
import java.util.Enumeration; import java.util.Enumeration;
import java.util.Iterator; import java.util.Iterator;
/** /**
* Adapter to make an {@link Iterator Iterator} instance appear to be * Adapter to make an {@link Iterator Iterator} instance appear to be an
* an {@link Enumeration Enumeration} instance. * {@link Enumeration Enumeration} instance.
* *
* @since Commons Collections 1.0 * @since Commons Collections 1.0
* @version $Revision$ $Date$ * @version $Revision$ $Date$
* *
* @author <a href="mailto:jstrachan@apache.org">James Strachan</a> * @author <a href="mailto:jstrachan@apache.org">James Strachan</a>
*/ */
public class IteratorEnumeration implements Enumeration { public class IteratorEnumeration<E> implements Enumeration<E> {
/** The iterator being decorated. */ /** The iterator being decorated. */
private Iterator iterator; private Iterator<? extends E> iterator;
/** /**
* Constructs a new <code>IteratorEnumeration</code> that will not * Constructs a new <code>IteratorEnumeration</code> that will not function
* function until {@link #setIterator(Iterator) setIterator} is * until {@link #setIterator(Iterator) setIterator} is invoked.
* invoked.
*/ */
public IteratorEnumeration() { public IteratorEnumeration() {
super(); super();
} }
/** /**
* Constructs a new <code>IteratorEnumeration</code> that will use * Constructs a new <code>IteratorEnumeration</code> that will use the given
* the given iterator. * iterator.
* *
* @param iterator the iterator to use * @param iterator the iterator to use
*/ */
public IteratorEnumeration( Iterator iterator ) { public IteratorEnumeration(Iterator<? extends E> iterator) {
super(); super();
this.iterator = iterator; this.iterator = iterator;
} }
@ -57,22 +56,22 @@ public class IteratorEnumeration implements Enumeration {
//------------------------------------------------------------------------- //-------------------------------------------------------------------------
/** /**
* Returns true if the underlying iterator has more elements. * Returns true if the underlying iterator has more elements.
* *
* @return true if the underlying iterator has more elements * @return true if the underlying iterator has more elements
*/ */
public boolean hasMoreElements() { public boolean hasMoreElements() {
return iterator.hasNext(); return iterator.hasNext();
} }
/** /**
* Returns the next element from the underlying iterator. * Returns the next element from the underlying iterator.
* *
* @return the next element from the underlying iterator. * @return the next element from the underlying iterator.
* @throws java.util.NoSuchElementException if the underlying iterator has no * @throws java.util.NoSuchElementException if the underlying iterator has
* more elements * no more elements
*/ */
public Object nextElement() { public E nextElement() {
return iterator.next(); return iterator.next();
} }
@ -80,21 +79,21 @@ public class IteratorEnumeration implements Enumeration {
//------------------------------------------------------------------------- //-------------------------------------------------------------------------
/** /**
* Returns the underlying iterator. * Returns the underlying iterator.
* *
* @return the underlying iterator * @return the underlying iterator
*/ */
public Iterator getIterator() { public Iterator<? extends E> getIterator() {
return iterator; return iterator;
} }
/** /**
* Sets the underlying iterator. * Sets the underlying iterator.
* *
* @param iterator the new underlying iterator * @param iterator the new underlying iterator
*/ */
public void setIterator( Iterator iterator ) { public void setIterator(Iterator<? extends E> iterator) {
this.iterator = iterator; this.iterator = iterator;
} }
} }

View File

@ -38,12 +38,12 @@ import org.apache.commons.collections.ResettableIterator;
* @author <a href="mailto:joncrlsn@users.sf.net">Jonathan Carlson</a> * @author <a href="mailto:joncrlsn@users.sf.net">Jonathan Carlson</a>
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public class LoopingIterator implements ResettableIterator { public class LoopingIterator<E> implements ResettableIterator<E> {
/** The collection to base the iterator on */ /** The collection to base the iterator on */
private Collection collection; private Collection<? extends E> collection;
/** The current iterator */ /** The current iterator */
private Iterator iterator; private Iterator<? extends E> iterator;
/** /**
* Constructor that wraps a collection. * Constructor that wraps a collection.
@ -54,7 +54,7 @@ public class LoopingIterator implements ResettableIterator {
* @param coll the collection to wrap * @param coll the collection to wrap
* @throws NullPointerException if the collection is null * @throws NullPointerException if the collection is null
*/ */
public LoopingIterator(Collection coll) { public LoopingIterator(Collection<? extends E> coll) {
if (coll == null) { if (coll == null) {
throw new NullPointerException("The collection must not be null"); throw new NullPointerException("The collection must not be null");
} }
@ -82,7 +82,7 @@ public class LoopingIterator implements ResettableIterator {
* @throws NoSuchElementException if there are no elements * @throws NoSuchElementException if there are no elements
* at all. Use {@link #hasNext} to avoid this error. * at all. Use {@link #hasNext} to avoid this error.
*/ */
public Object next() { public E next() {
if (collection.size() == 0) { if (collection.size() == 0) {
throw new NoSuchElementException("There are no elements for this iterator to loop on"); throw new NoSuchElementException("There are no elements for this iterator to loop on");
} }

View File

@ -39,12 +39,12 @@ import org.apache.commons.collections.ResettableListIterator;
* *
* @author Eric Crampton <ccesc@eonomine.com> * @author Eric Crampton <ccesc@eonomine.com>
*/ */
public class LoopingListIterator implements ResettableListIterator { public class LoopingListIterator<E> implements ResettableListIterator<E> {
/** The list to base the iterator on */ /** The list to base the iterator on */
private List list; private List<E> list;
/** The current list iterator */ /** The current list iterator */
private ListIterator iterator; private ListIterator<E> iterator;
/** /**
* Constructor that wraps a list. * Constructor that wraps a list.
@ -56,7 +56,7 @@ public class LoopingListIterator implements ResettableListIterator {
* @param list the list to wrap * @param list the list to wrap
* @throws NullPointerException if the list it null * @throws NullPointerException if the list it null
*/ */
public LoopingListIterator(List list) { public LoopingListIterator(List<E> list) {
if (list == null) { if (list == null) {
throw new NullPointerException("The list must not be null"); throw new NullPointerException("The list must not be null");
} }
@ -84,7 +84,7 @@ public class LoopingListIterator implements ResettableListIterator {
* @return the object after the last element returned * @return the object after the last element returned
* @throws NoSuchElementException if there are no elements in the list * @throws NoSuchElementException if there are no elements in the list
*/ */
public Object next() { public E next() {
if (list.isEmpty()) { if (list.isEmpty()) {
throw new NoSuchElementException( throw new NoSuchElementException(
"There are no elements for this iterator to loop on"); "There are no elements for this iterator to loop on");
@ -113,9 +113,8 @@ public class LoopingListIterator implements ResettableListIterator {
} }
if (iterator.hasNext() == false) { if (iterator.hasNext() == false) {
return 0; return 0;
} else {
return iterator.nextIndex();
} }
return iterator.nextIndex();
} }
/** /**
@ -139,21 +138,20 @@ public class LoopingListIterator implements ResettableListIterator {
* @return the object before the last element returned * @return the object before the last element returned
* @throws NoSuchElementException if there are no elements in the list * @throws NoSuchElementException if there are no elements in the list
*/ */
public Object previous() { public E previous() {
if (list.isEmpty()) { if (list.isEmpty()) {
throw new NoSuchElementException( throw new NoSuchElementException(
"There are no elements for this iterator to loop on"); "There are no elements for this iterator to loop on");
} }
if (iterator.hasPrevious() == false) { if (iterator.hasPrevious() == false) {
Object result = null; E result = null;
while (iterator.hasNext()) { while (iterator.hasNext()) {
result = iterator.next(); result = iterator.next();
} }
iterator.previous(); iterator.previous();
return result; return result;
} else {
return iterator.previous();
} }
return iterator.previous();
} }
/** /**
@ -174,9 +172,8 @@ public class LoopingListIterator implements ResettableListIterator {
} }
if (iterator.hasPrevious() == false) { if (iterator.hasPrevious() == false) {
return list.size() - 1; return list.size() - 1;
} else {
return iterator.previousIndex();
} }
return iterator.previousIndex();
} }
/** /**
@ -216,7 +213,7 @@ public class LoopingListIterator implements ResettableListIterator {
* @throws UnsupportedOperationException if the add method is not * @throws UnsupportedOperationException if the add method is not
* supported by the iterator implementation of the underlying list * supported by the iterator implementation of the underlying list
*/ */
public void add(Object obj) { public void add(E obj) {
iterator.add(obj); iterator.add(obj);
} }
@ -232,7 +229,7 @@ public class LoopingListIterator implements ResettableListIterator {
* @throws UnsupportedOperationException if the set method is not * @throws UnsupportedOperationException if the set method is not
* supported by the iterator implementation of the underlying list * supported by the iterator implementation of the underlying list
*/ */
public void set(Object obj) { public void set(E obj) {
iterator.set(obj); iterator.set(obj);
} }

View File

@ -40,11 +40,11 @@ import org.apache.commons.collections.ResettableIterator;
* @author Stephen Colebourne * @author Stephen Colebourne
* @author Phil Steitz * @author Phil Steitz
*/ */
public class ObjectArrayIterator public class ObjectArrayIterator<E>
implements Iterator, ResettableIterator { implements Iterator<E>, ResettableIterator<E> {
/** The array */ /** The array */
protected Object[] array = null; protected E[] array = null;
/** The start index to loop from */ /** The start index to loop from */
protected int startIndex = 0; protected int startIndex = 0;
/** The end index to loop to */ /** The end index to loop to */
@ -69,7 +69,7 @@ public class ObjectArrayIterator
* @param array the array to iterate over * @param array the array to iterate over
* @throws NullPointerException if <code>array</code> is <code>null</code> * @throws NullPointerException if <code>array</code> is <code>null</code>
*/ */
public ObjectArrayIterator(Object[] array) { public ObjectArrayIterator(E[] array) {
this(array, 0, array.length); this(array, 0, array.length);
} }
@ -82,7 +82,7 @@ public class ObjectArrayIterator
* @throws NullPointerException if <code>array</code> is <code>null</code> * @throws NullPointerException if <code>array</code> is <code>null</code>
* @throws IndexOutOfBoundsException if the start index is out of bounds * @throws IndexOutOfBoundsException if the start index is out of bounds
*/ */
public ObjectArrayIterator(Object array[], int start) { public ObjectArrayIterator(E array[], int start) {
this(array, start, array.length); this(array, start, array.length);
} }
@ -97,7 +97,7 @@ public class ObjectArrayIterator
* @throws IllegalArgumentException if end index is before the start * @throws IllegalArgumentException if end index is before the start
* @throws NullPointerException if <code>array</code> is <code>null</code> * @throws NullPointerException if <code>array</code> is <code>null</code>
*/ */
public ObjectArrayIterator(Object array[], int start, int end) { public ObjectArrayIterator(E array[], int start, int end) {
super(); super();
if (start < 0) { if (start < 0) {
throw new ArrayIndexOutOfBoundsException("Start index must not be less than zero"); throw new ArrayIndexOutOfBoundsException("Start index must not be less than zero");
@ -136,7 +136,7 @@ public class ObjectArrayIterator
* @throws NoSuchElementException if all the elements in the array * @throws NoSuchElementException if all the elements in the array
* have already been returned * have already been returned
*/ */
public Object next() { public E next() {
if (hasNext() == false) { if (hasNext() == false) {
throw new NoSuchElementException(); throw new NoSuchElementException();
} }
@ -162,7 +162,7 @@ public class ObjectArrayIterator
* the no-arg constructor was used and {@link #setArray} has never * the no-arg constructor was used and {@link #setArray} has never
* been called with a valid array. * been called with a valid array.
*/ */
public Object[] getArray() { public E[] getArray() {
return this.array; return this.array;
} }
@ -178,7 +178,7 @@ public class ObjectArrayIterator
* @throws IllegalStateException if the <code>array</code> was set in the constructor * @throws IllegalStateException if the <code>array</code> was set in the constructor
* @throws NullPointerException if <code>array</code> is <code>null</code> * @throws NullPointerException if <code>array</code> is <code>null</code>
*/ */
public void setArray(Object[] array) { public void setArray(E[] array) {
if (this.array != null) { if (this.array != null) {
throw new IllegalStateException("The array to iterate over has already been set"); throw new IllegalStateException("The array to iterate over has already been set");
} }

View File

@ -38,12 +38,12 @@ import org.apache.commons.collections.ResettableListIterator;
* @since Commons Collections 3.2 * @since Commons Collections 3.2
* @version $Revision: $ $Date$ * @version $Revision: $ $Date$
*/ */
public class ReverseListIterator implements ResettableListIterator { public class ReverseListIterator<E> implements ResettableListIterator<E> {
/** The list being wrapped. */ /** The list being wrapped. */
private final List list; private final List<E> list;
/** The list iterator being wrapped. */ /** The list iterator being wrapped. */
private ListIterator iterator; private ListIterator<E> iterator;
/** Flag to indicate if updating is possible at the moment. */ /** Flag to indicate if updating is possible at the moment. */
private boolean validForUpdate = true; private boolean validForUpdate = true;
@ -53,7 +53,7 @@ public class ReverseListIterator implements ResettableListIterator {
* @param list the list to create a reversed iterator for * @param list the list to create a reversed iterator for
* @throws NullPointerException if the list is null * @throws NullPointerException if the list is null
*/ */
public ReverseListIterator(List list) { public ReverseListIterator(List<E> list) {
super(); super();
this.list = list; this.list = list;
iterator = list.listIterator(list.size()); iterator = list.listIterator(list.size());
@ -75,8 +75,8 @@ public class ReverseListIterator implements ResettableListIterator {
* *
* @return the next element in the iterator * @return the next element in the iterator
*/ */
public Object next() { public E next() {
Object obj = iterator.previous(); E obj = iterator.previous();
validForUpdate = true; validForUpdate = true;
return obj; return obj;
} }
@ -105,8 +105,8 @@ public class ReverseListIterator implements ResettableListIterator {
* *
* @return the previous element in the iterator * @return the previous element in the iterator
*/ */
public Object previous() { public E previous() {
Object obj = iterator.next(); E obj = iterator.next();
validForUpdate = true; validForUpdate = true;
return obj; return obj;
} }
@ -140,7 +140,7 @@ public class ReverseListIterator implements ResettableListIterator {
* @throws UnsupportedOperationException if the list is unmodifiable * @throws UnsupportedOperationException if the list is unmodifiable
* @throws IllegalStateException if the iterator is not in a valid state for set * @throws IllegalStateException if the iterator is not in a valid state for set
*/ */
public void set(Object obj) { public void set(E obj) {
if (validForUpdate == false) { if (validForUpdate == false) {
throw new IllegalStateException("Cannot set to list until next() or previous() called"); throw new IllegalStateException("Cannot set to list until next() or previous() called");
} }
@ -154,7 +154,7 @@ public class ReverseListIterator implements ResettableListIterator {
* @throws UnsupportedOperationException if the list is unmodifiable * @throws UnsupportedOperationException if the list is unmodifiable
* @throws IllegalStateException if the iterator is not in a valid state for set * @throws IllegalStateException if the iterator is not in a valid state for set
*/ */
public void add(Object obj) { public void add(E obj) {
// the validForUpdate flag is needed as the necessary previous() // the validForUpdate flag is needed as the necessary previous()
// method call re-enables remove and add // method call re-enables remove and add
if (validForUpdate == false) { if (validForUpdate == false) {

View File

@ -31,19 +31,19 @@ import org.apache.commons.collections.ResettableListIterator;
* @author Stephen Colebourne * @author Stephen Colebourne
* @author Rodney Waldhoff * @author Rodney Waldhoff
*/ */
public class SingletonListIterator implements ListIterator, ResettableListIterator { public class SingletonListIterator<E> implements ListIterator<E>, ResettableListIterator<E> {
private boolean beforeFirst = true; private boolean beforeFirst = true;
private boolean nextCalled = false; private boolean nextCalled = false;
private boolean removed = false; private boolean removed = false;
private Object object; private E object;
/** /**
* Constructs a new <code>SingletonListIterator</code>. * Constructs a new <code>SingletonListIterator</code>.
* *
* @param object the single object to return from the iterator * @param object the single object to return from the iterator
*/ */
public SingletonListIterator(Object object) { public SingletonListIterator(E object) {
super(); super();
this.object = object; this.object = object;
} }
@ -100,7 +100,7 @@ public class SingletonListIterator implements ListIterator, ResettableListIterat
* @throws NoSuchElementException if the single object has already * @throws NoSuchElementException if the single object has already
* been returned * been returned
*/ */
public Object next() { public E next() {
if (!beforeFirst || removed) { if (!beforeFirst || removed) {
throw new NoSuchElementException(); throw new NoSuchElementException();
} }
@ -118,7 +118,7 @@ public class SingletonListIterator implements ListIterator, ResettableListIterat
* @throws NoSuchElementException if the single object has not already * @throws NoSuchElementException if the single object has not already
* been returned * been returned
*/ */
public Object previous() { public E previous() {
if (beforeFirst || removed) { if (beforeFirst || removed) {
throw new NoSuchElementException(); throw new NoSuchElementException();
} }
@ -147,7 +147,7 @@ public class SingletonListIterator implements ListIterator, ResettableListIterat
* *
* @throws UnsupportedOperationException always * @throws UnsupportedOperationException always
*/ */
public void add(Object obj) { public void add(E obj) {
throw new UnsupportedOperationException("add() is not supported by this iterator"); throw new UnsupportedOperationException("add() is not supported by this iterator");
} }
@ -158,7 +158,7 @@ public class SingletonListIterator implements ListIterator, ResettableListIterat
* @throws IllegalStateException if <tt>next</tt> has not been called * @throws IllegalStateException if <tt>next</tt> has not been called
* or the object has been removed * or the object has been removed
*/ */
public void set(Object obj) { public void set(E obj) {
if (!nextCalled || removed) { if (!nextCalled || removed) {
throw new IllegalStateException(); throw new IllegalStateException();
} }

View File

@ -29,18 +29,18 @@ import org.apache.commons.collections.Transformer;
* @author James Strachan * @author James Strachan
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public class TransformIterator implements Iterator { public class TransformIterator<I, O> implements Iterator<O> {
/** The iterator being used */ /** The iterator being used */
private Iterator iterator; private Iterator<? extends I> iterator;
/** The transformer being used */ /** The transformer being used */
private Transformer transformer; private Transformer<? super I, ? extends O> transformer;
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
/** /**
* Constructs a new <code>TransformIterator</code> that will not function * Constructs a new <code>TransformIterator</code> that will not function
* until the {@link #setIterator(Iterator) setIterator} method is * until the {@link #setIterator(Iterator) setIterator} and
* invoked. * {@link #setTransformer(Transformer)} methods are invoked.
*/ */
public TransformIterator() { public TransformIterator() {
super(); super();
@ -52,7 +52,7 @@ public class TransformIterator implements Iterator {
* *
* @param iterator the iterator to use * @param iterator the iterator to use
*/ */
public TransformIterator(Iterator iterator) { public TransformIterator(Iterator<? extends I> iterator) {
super(); super();
this.iterator = iterator; this.iterator = iterator;
} }
@ -65,7 +65,7 @@ public class TransformIterator implements Iterator {
* @param iterator the iterator to use * @param iterator the iterator to use
* @param transformer the transformer to use * @param transformer the transformer to use
*/ */
public TransformIterator(Iterator iterator, Transformer transformer) { public TransformIterator(Iterator<? extends I> iterator, Transformer<? super I, ? extends O> transformer) {
super(); super();
this.iterator = iterator; this.iterator = iterator;
this.transformer = transformer; this.transformer = transformer;
@ -84,7 +84,7 @@ public class TransformIterator implements Iterator {
* @return the next object * @return the next object
* @throws java.util.NoSuchElementException if there are no more elements * @throws java.util.NoSuchElementException if there are no more elements
*/ */
public Object next() { public O next() {
return transform(iterator.next()); return transform(iterator.next());
} }
@ -98,7 +98,7 @@ public class TransformIterator implements Iterator {
* *
* @return the iterator. * @return the iterator.
*/ */
public Iterator getIterator() { public Iterator<? extends I> getIterator() {
return iterator; return iterator;
} }
@ -108,7 +108,7 @@ public class TransformIterator implements Iterator {
* *
* @param iterator the iterator to use * @param iterator the iterator to use
*/ */
public void setIterator(Iterator iterator) { public void setIterator(Iterator<? extends I> iterator) {
this.iterator = iterator; this.iterator = iterator;
} }
@ -118,7 +118,7 @@ public class TransformIterator implements Iterator {
* *
* @return the transformer. * @return the transformer.
*/ */
public Transformer getTransformer() { public Transformer<? super I, ? extends O> getTransformer() {
return transformer; return transformer;
} }
@ -128,7 +128,7 @@ public class TransformIterator implements Iterator {
* *
* @param transformer the transformer to use * @param transformer the transformer to use
*/ */
public void setTransformer(Transformer transformer) { public void setTransformer(Transformer<? super I, ? extends O> transformer) {
this.transformer = transformer; this.transformer = transformer;
} }
@ -140,10 +140,7 @@ public class TransformIterator implements Iterator {
* @param source the object to transform * @param source the object to transform
* @return the transformed object * @return the transformed object
*/ */
protected Object transform(Object source) { protected O transform(I source) {
if (transformer != null) { return transformer.transform(source);
return transformer.transform(source);
}
return source;
} }
} }

View File

@ -20,7 +20,7 @@ import java.util.Iterator;
import org.apache.commons.collections.functors.UniquePredicate; import org.apache.commons.collections.functors.UniquePredicate;
/** /**
* A FilterIterator which only returns "unique" Objects. Internally, * A FilterIterator which only returns "unique" Objects. Internally,
* the Iterator maintains a Set of objects it has already encountered, * the Iterator maintains a Set of objects it has already encountered,
* and duplicate Objects are skipped. * and duplicate Objects are skipped.
@ -30,16 +30,16 @@ import org.apache.commons.collections.functors.UniquePredicate;
* *
* @author Morgan Delagrange * @author Morgan Delagrange
*/ */
public class UniqueFilterIterator extends FilterIterator { public class UniqueFilterIterator<E> extends FilterIterator<E> {
//------------------------------------------------------------------------- //-------------------------------------------------------------------------
/** /**
* Constructs a new <code>UniqueFilterIterator</code>. * Constructs a new <code>UniqueFilterIterator</code>.
* *
* @param iterator the iterator to use * @param iterator the iterator to use
*/ */
public UniqueFilterIterator( Iterator iterator ) { public UniqueFilterIterator(Iterator<E> iterator) {
super(iterator, UniquePredicate.getInstance()); super(iterator, UniquePredicate.getInstance());
} }

View File

@ -30,10 +30,10 @@ import org.apache.commons.collections.Unmodifiable;
* *
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public final class UnmodifiableIterator implements Iterator, Unmodifiable { public final class UnmodifiableIterator<E> implements Iterator<E>, Unmodifiable {
/** The iterator being decorated */ /** The iterator being decorated */
private Iterator iterator; private Iterator<E> iterator;
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
/** /**
@ -44,23 +44,23 @@ public final class UnmodifiableIterator implements Iterator, Unmodifiable {
* @param iterator the iterator to decorate * @param iterator the iterator to decorate
* @throws IllegalArgumentException if the iterator is null * @throws IllegalArgumentException if the iterator is null
*/ */
public static Iterator decorate(Iterator iterator) { public static <E> Iterator<E> decorate(Iterator<E> iterator) {
if (iterator == null) { if (iterator == null) {
throw new IllegalArgumentException("Iterator must not be null"); throw new IllegalArgumentException("Iterator must not be null");
} }
if (iterator instanceof Unmodifiable) { if (iterator instanceof Unmodifiable) {
return iterator; return iterator;
} }
return new UnmodifiableIterator(iterator); return new UnmodifiableIterator<E>(iterator);
} }
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
/** /**
* Constructor. * Constructor.
* *
* @param iterator the iterator to decorate * @param iterator the iterator to decorate
*/ */
private UnmodifiableIterator(Iterator iterator) { private UnmodifiableIterator(Iterator<E> iterator) {
super(); super();
this.iterator = iterator; this.iterator = iterator;
} }
@ -70,7 +70,7 @@ public final class UnmodifiableIterator implements Iterator, Unmodifiable {
return iterator.hasNext(); return iterator.hasNext();
} }
public Object next() { public E next() {
return iterator.next(); return iterator.next();
} }

View File

@ -30,10 +30,10 @@ import org.apache.commons.collections.Unmodifiable;
* *
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public final class UnmodifiableListIterator implements ListIterator, Unmodifiable { public final class UnmodifiableListIterator<E> implements ListIterator<E>, Unmodifiable {
/** The iterator being decorated */ /** The iterator being decorated */
private ListIterator iterator; private ListIterator<E> iterator;
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
/** /**
@ -42,14 +42,14 @@ public final class UnmodifiableListIterator implements ListIterator, Unmodifiabl
* @param iterator the iterator to decorate * @param iterator the iterator to decorate
* @throws IllegalArgumentException if the iterator is null * @throws IllegalArgumentException if the iterator is null
*/ */
public static ListIterator decorate(ListIterator iterator) { public static <E> ListIterator<E> decorate(ListIterator<E> iterator) {
if (iterator == null) { if (iterator == null) {
throw new IllegalArgumentException("ListIterator must not be null"); throw new IllegalArgumentException("ListIterator must not be null");
} }
if (iterator instanceof Unmodifiable) { if (iterator instanceof Unmodifiable) {
return iterator; return iterator;
} }
return new UnmodifiableListIterator(iterator); return new UnmodifiableListIterator<E>(iterator);
} }
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
@ -58,7 +58,7 @@ public final class UnmodifiableListIterator implements ListIterator, Unmodifiabl
* *
* @param iterator the iterator to decorate * @param iterator the iterator to decorate
*/ */
private UnmodifiableListIterator(ListIterator iterator) { private UnmodifiableListIterator(ListIterator<E> iterator) {
super(); super();
this.iterator = iterator; this.iterator = iterator;
} }
@ -68,7 +68,7 @@ public final class UnmodifiableListIterator implements ListIterator, Unmodifiabl
return iterator.hasNext(); return iterator.hasNext();
} }
public Object next() { public E next() {
return iterator.next(); return iterator.next();
} }
@ -80,7 +80,7 @@ public final class UnmodifiableListIterator implements ListIterator, Unmodifiabl
return iterator.hasPrevious(); return iterator.hasPrevious();
} }
public Object previous() { public E previous() {
return iterator.previous(); return iterator.previous();
} }
@ -92,11 +92,11 @@ public final class UnmodifiableListIterator implements ListIterator, Unmodifiabl
throw new UnsupportedOperationException("remove() is not supported"); throw new UnsupportedOperationException("remove() is not supported");
} }
public void set(Object obj) { public void set(E obj) {
throw new UnsupportedOperationException("set() is not supported"); throw new UnsupportedOperationException("set() is not supported");
} }
public void add(Object obj) { public void add(E obj) {
throw new UnsupportedOperationException("add() is not supported"); throw new UnsupportedOperationException("add() is not supported");
} }

View File

@ -29,10 +29,10 @@ import org.apache.commons.collections.Unmodifiable;
* *
* @author Stephen Colebourne * @author Stephen Colebourne
*/ */
public final class UnmodifiableMapIterator implements MapIterator, Unmodifiable { public final class UnmodifiableMapIterator<K, V> implements MapIterator<K, V>, Unmodifiable {
/** The iterator being decorated */ /** The iterator being decorated */
private MapIterator iterator; private MapIterator<K, V> iterator;
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
/** /**
@ -41,23 +41,23 @@ public final class UnmodifiableMapIterator implements MapIterator, Unmodifiable
* @param iterator the iterator to decorate * @param iterator the iterator to decorate
* @throws IllegalArgumentException if the iterator is null * @throws IllegalArgumentException if the iterator is null
*/ */
public static MapIterator decorate(MapIterator iterator) { public static <K, V> MapIterator<K, V> decorate(MapIterator<K, V> iterator) {
if (iterator == null) { if (iterator == null) {
throw new IllegalArgumentException("MapIterator must not be null"); throw new IllegalArgumentException("MapIterator must not be null");
} }
if (iterator instanceof Unmodifiable) { if (iterator instanceof Unmodifiable) {
return iterator; return iterator;
} }
return new UnmodifiableMapIterator(iterator); return new UnmodifiableMapIterator<K, V>(iterator);
} }
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
/** /**
* Constructor. * Constructor.
* *
* @param iterator the iterator to decorate * @param iterator the iterator to decorate
*/ */
private UnmodifiableMapIterator(MapIterator iterator) { private UnmodifiableMapIterator(MapIterator<K, V> iterator) {
super(); super();
this.iterator = iterator; this.iterator = iterator;
} }
@ -67,19 +67,19 @@ public final class UnmodifiableMapIterator implements MapIterator, Unmodifiable
return iterator.hasNext(); return iterator.hasNext();
} }
public Object next() { public K next() {
return iterator.next(); return iterator.next();
} }
public Object getKey() { public K getKey() {
return iterator.getKey(); return iterator.getKey();
} }
public Object getValue() { public V getValue() {
return iterator.getValue(); return iterator.getValue();
} }
public Object setValue(Object value) { public V setValue(V value) {
throw new UnsupportedOperationException("setValue() is not supported"); throw new UnsupportedOperationException("setValue() is not supported");
} }

Some files were not shown because too many files have changed in this diff Show More