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

View File

@ -34,7 +34,7 @@ import java.util.Collection;
* @author Herve Quiroz
* @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.

View File

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

View File

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

View File

@ -24,7 +24,8 @@ package org.apache.commons.collections;
* <p>
* Standard implementations of common closures are provided by
* {@link ClosureUtils}. These include method invokation and for/while loops.
*
*
* @param <T> the type that the closure acts on
* @since Commons Collections 1.0
* @version $Revision$ $Date$
*
@ -32,7 +33,7 @@ package org.apache.commons.collections;
* @author Nicola Ken Barozzi
* @author Stephen Colebourne
*/
public interface Closure {
public interface Closure<T> {
/**
* Performs an action on the specified input object.
@ -42,6 +43,6 @@ public interface Closure {
* @throws IllegalArgumentException (runtime) if the input is invalid
* @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
*/
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.
*
* @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;
}
@ -76,7 +78,8 @@ public class ComparatorUtils {
* @throws NullPointerException if either comparator is null
* @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});
}
@ -89,8 +92,8 @@ public class ComparatorUtils {
* @throws NullPointerException if comparators array is null or contains a null
* @see ComparatorChain
*/
public static Comparator chainedComparator(Comparator[] comparators) {
ComparatorChain chain = new ComparatorChain();
public static <E extends Comparable<? super E>> Comparator<E> chainedComparator(Comparator<E>[] comparators) {
ComparatorChain<E> chain = new ComparatorChain<E>();
for (int i = 0; i < comparators.length; i++) {
if (comparators[i] == 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
* @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(
(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
* @see ReverseComparator
*/
public static Comparator reversedComparator(Comparator comparator) {
if (comparator == null) {
comparator = NATURAL_COMPARATOR;
}
return new ReverseComparator(comparator);
public static <E> Comparator<E> reversedComparator(Comparator<E> comparator) {
return new ReverseComparator<E>(comparator);
}
/**
@ -143,7 +144,7 @@ public class ComparatorUtils {
* <code>false</code> {@link Boolean}s.
* @return a comparator that sorts booleans
*/
public static Comparator booleanComparator(boolean trueFirst) {
public static Comparator<Boolean> booleanComparator(boolean trueFirst) {
return BooleanComparator.getBooleanComparator(trueFirst);
}
@ -158,11 +159,12 @@ public class ComparatorUtils {
* @return a version of that comparator that allows nulls
* @see NullComparator
*/
public static Comparator nullLowComparator(Comparator comparator) {
@SuppressWarnings("unchecked")
public static <E> Comparator<E> nullLowComparator(Comparator<E> comparator) {
if (comparator == null) {
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
* @see NullComparator
*/
public static Comparator nullHighComparator(Comparator comparator) {
@SuppressWarnings("unchecked")
public static <E> Comparator<E> nullHighComparator(Comparator<E> comparator) {
if (comparator == null) {
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
* @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) {
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
* @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) {
comparator = NATURAL_COMPARATOR;
}
@ -230,7 +235,8 @@ public class ComparatorUtils {
* @param comparator the sort order to use
* @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) {
comparator = NATURAL_COMPARATOR;
}

View File

@ -16,8 +16,10 @@
*/
package org.apache.commons.collections;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.StringTokenizer;
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>.
* @throws NullPointerException if the enumeration parameter is <code>null</code>.
*/
public static List toList(Enumeration enumeration) {
return IteratorUtils.toList(new EnumerationIterator(enumeration));
public static <E> List<E> toList(Enumeration<E> 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,
* a copy of a prototype or a new instance.
*
* @param <T> the type that the factory creates
*
* @since Commons Collections 2.1
* @version $Revision$ $Date$
*
* @author Arron Bates
* @author Stephen Colebourne
*/
public interface Factory {
public interface Factory<T> {
/**
* Create a new object.
@ -40,6 +42,6 @@ public interface Factory {
* @return a new 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 {
/** Serialization version */
private static final long serialVersionUID = 9139387246344345475L;
/**
* Does JDK support nested exceptions
*/
private static final boolean JDK_SUPPORTS_NESTED;
static {
boolean flag = false;
try {
@ -45,7 +48,7 @@ public class FunctorException extends RuntimeException {
}
JDK_SUPPORTS_NESTED = flag;
}
/**
* 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,
* or, not, method invokation and null testing.
*
* @param <T> the type that the predicate queries
*
* @since Commons Collections 1.0
* @version $Revision$ $Date$
*
* @author James Strachan
* @author Stephen Colebourne
*/
public interface Predicate {
public interface Predicate<T> {
/**
* 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 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,
* 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
* @version $Revision$ $Date$
*
* @author James Strachan
* @author Stephen Colebourne
*/
public interface Transformer {
public interface Transformer<I, O> {
/**
* 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 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
* of subclass implementations.
* <p>
* Subclasses specify a Map implementation to use as the internal storage.
* The map will be used to map bag elements to a number; the number represents
* the number of occurrences of that element in the bag.
* Subclasses specify a Map implementation to use as the internal storage. The
* map will be used to map bag elements to a number; the number represents the
* number of occurrences of that element in the bag.
*
* @since Commons Collections 3.0 (previously DefaultMapBag v2.0)
* @version $Revision$ $Date$
@ -46,16 +46,16 @@ import org.apache.commons.collections.set.UnmodifiableSet;
* @author Janek Bogucki
* @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 */
private transient Map map;
private transient Map<E, MutableInteger> map;
/** The current total size of the bag */
private int size;
/** The modification count for fail fast iterators */
private transient int modCount;
/** The modification count for fail fast iterators */
private transient Set uniqueSet;
private transient Set<E> uniqueSet;
/**
* 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.
* The map must be empty and non-null.
* Constructor that assigns the specified Map as the backing store. The map
* 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();
this.map = map;
}
/**
* Utility method for implementations to access the map that backs
* this bag. Not intended for interactive use outside of subclasses.
* Utility method for implementations to access the map that backs this bag.
* Not intended for interactive use outside of subclasses.
*
* @return the map being used by the Bag
*/
protected Map getMap() {
protected Map<E, MutableInteger> getMap() {
return map;
}
//-----------------------------------------------------------------------
/**
* Returns the number of elements in this bag.
*
*
* @return current size of the bag
*/
public int size() {
@ -98,7 +98,7 @@ public abstract class AbstractMapBag implements Bag {
/**
* Returns true if the underlying map is empty.
*
*
* @return true if bag is empty
*/
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
* by looking up its count in the underlying map.
*
* @param object the object to search for
* Returns the number of occurrence of the given element in this bag by
* looking up its count in the underlying map.
*
* @param object the object to search for
* @return the number of occurrences of the object, zero if not found
*/
public int getCount(Object object) {
MutableInteger count = (MutableInteger) map.get(object);
MutableInteger count = map.get(object);
if (count != null) {
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
* 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
*/
public boolean contains(Object object) {
@ -135,26 +135,27 @@ public abstract class AbstractMapBag implements Bag {
/**
* 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
*/
public boolean containsAll(Collection coll) {
@SuppressWarnings("unchecked")
public boolean containsAll(Collection<?> coll) {
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
* the given collection, respecting cardinality.
* Returns <code>true</code> if the bag contains all elements in the given
* 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
*/
boolean containsAll(Bag other) {
boolean containsAll(Bag<?> other) {
boolean result = true;
Iterator it = other.uniqueSet().iterator();
Iterator<?> it = other.uniqueSet().iterator();
while (it.hasNext()) {
Object current = it.next();
boolean contains = getCount(current) >= other.getCount(current);
@ -165,22 +166,22 @@ public abstract class AbstractMapBag implements Bag {
//-----------------------------------------------------------------------
/**
* Gets an iterator over the bag elements.
* Elements present in the Bag more than once will be returned repeatedly.
* Gets an iterator over the bag elements. Elements present in the Bag more
* than once will be returned repeatedly.
*
* @return the iterator
*/
public Iterator iterator() {
return new BagIterator(this);
public Iterator<E> iterator() {
return new BagIterator<E>(this);
}
/**
* Inner class iterator for the Bag.
*/
static class BagIterator implements Iterator {
private AbstractMapBag parent;
private Iterator entryIterator;
private Map.Entry current;
static class BagIterator<E> implements Iterator<E> {
private AbstractMapBag<E> parent;
private Iterator<Map.Entry<E, MutableInteger>> entryIterator;
private Map.Entry<E, MutableInteger> current;
private int itemCount;
private final int mods;
private boolean canRemove;
@ -188,9 +189,9 @@ public abstract class AbstractMapBag implements Bag {
/**
* Constructor.
*
* @param parent the parent bag
* @param parent the parent bag
*/
public BagIterator(AbstractMapBag parent) {
public BagIterator(AbstractMapBag<E> parent) {
this.parent = parent;
this.entryIterator = parent.map.entrySet().iterator();
this.current = null;
@ -202,13 +203,13 @@ public abstract class AbstractMapBag implements Bag {
return (itemCount > 0 || entryIterator.hasNext());
}
public Object next() {
public E next() {
if (parent.modCount != mods) {
throw new ConcurrentModificationException();
}
if (itemCount == 0) {
current = (Map.Entry) entryIterator.next();
itemCount = ((MutableInteger) current.getValue()).value;
current = (Map.Entry<E, MutableInteger>) entryIterator.next();
itemCount = current.getValue().value;
}
canRemove = true;
itemCount--;
@ -222,7 +223,7 @@ public abstract class AbstractMapBag implements Bag {
if (canRemove == false) {
throw new IllegalStateException();
}
MutableInteger mut = (MutableInteger) current.getValue();
MutableInteger mut = current.getValue();
if (mut.value > 1) {
mut.value--;
} 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.
*
* @param object the object to add
* @return <code>true</code> if the object was not already in the <code>uniqueSet</code>
* 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>
*/
public boolean add(Object object) {
public boolean add(E object) {
return add(object, 1);
}
/**
* Adds a new element to the bag, incrementing its count in the map.
*
* @param object the object to search for
* @param nCopies the number of copies to add
* @return <code>true</code> if the object was not already in the <code>uniqueSet</code>
*
* @param object the object to search for
* @param nCopies the number of copies to add
* @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++;
if (nCopies > 0) {
MutableInteger mut = (MutableInteger) map.get(object);
MutableInteger mut = map.get(object);
size += nCopies;
if (mut == null) {
map.put(object, new MutableInteger(nCopies));
return true;
} else {
mut.value += nCopies;
return false;
}
} else {
mut.value += nCopies;
return false;
}
return false;
}
/**
* 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
*/
public boolean addAll(Collection coll) {
public boolean addAll(Collection<? extends E> coll) {
boolean changed = false;
Iterator i = coll.iterator();
Iterator<? extends E> i = coll.iterator();
while (i.hasNext()) {
boolean added = add(i.next());
changed = changed || added;
@ -297,11 +299,11 @@ public abstract class AbstractMapBag implements 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
*/
public boolean remove(Object object) {
MutableInteger mut = (MutableInteger) map.get(object);
MutableInteger mut = map.get(object);
if (mut == null) {
return false;
}
@ -314,12 +316,12 @@ public abstract class AbstractMapBag implements Bag {
/**
* Removes a specified number of copies of an object from the bag.
*
* @param object the object to remove
* @param nCopies the number of copies to remove
* @param object the object to remove
* @param nCopies the number of copies to remove
* @return true if the bag changed
*/
public boolean remove(Object object, int nCopies) {
MutableInteger mut = (MutableInteger) map.get(object);
MutableInteger mut = map.get(object);
if (mut == null) {
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
*/
public boolean removeAll(Collection coll) {
public boolean removeAll(Collection<?> coll) {
boolean result = false;
if (coll != null) {
Iterator i = coll.iterator();
Iterator<?> i = coll.iterator();
while (i.hasNext()) {
boolean changed = remove(i.next(), 1);
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
* bag, respecting cardinality.
*
* @param coll the collection to retain
* Remove any members of the bag that are not in the given bag, respecting
* cardinality.
*
* @param coll the collection to retain
* @return true if this call changed the collection
*/
public boolean retainAll(Collection coll) {
@SuppressWarnings("unchecked")
public boolean retainAll(Collection<?> coll) {
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
* bag, respecting cardinality.
* Remove any members of the bag that are not in the given bag, respecting
* cardinality.
* @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
*/
boolean retainAll(Bag other) {
boolean retainAll(Bag<?> other) {
boolean result = false;
Bag excess = new HashBag();
Iterator i = uniqueSet().iterator();
Bag<E> excess = new HashBag<E>();
Iterator<E> i = uniqueSet().iterator();
while (i.hasNext()) {
Object current = i.next();
E current = i.next();
int myCount = getCount(current);
int otherCount = other.getCount(current);
if (1 <= otherCount && otherCount <= myCount) {
@ -404,15 +408,15 @@ public abstract class AbstractMapBag implements Bag {
protected static class MutableInteger {
/** The value of this mutable. */
protected int value;
/**
* Constructor.
* @param value the initial value
* @param value the initial value
*/
MutableInteger(int value) {
this.value = value;
}
public boolean equals(Object obj) {
if (obj instanceof MutableInteger == false) {
return false;
@ -424,19 +428,19 @@ public abstract class AbstractMapBag implements Bag {
return value;
}
}
//-----------------------------------------------------------------------
/**
* Returns an array of all of this bag's elements.
*
*
* @return an array of all of this bag's elements
*/
public Object[] toArray() {
Object[] result = new Object[size()];
int i = 0;
Iterator it = map.keySet().iterator();
Iterator<E> it = map.keySet().iterator();
while (it.hasNext()) {
Object current = it.next();
E current = it.next();
for (int index = getCount(current); index > 0; index--) {
result[i++] = current;
}
@ -446,38 +450,39 @@ public abstract class AbstractMapBag implements Bag {
/**
* 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
*/
public Object[] toArray(Object[] array) {
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] array) {
int size = size();
if (array.length < size) {
array = (Object[]) Array.newInstance(array.getClass().getComponentType(), size);
array = (T[]) Array.newInstance(array.getClass().getComponentType(), size);
}
int i = 0;
Iterator it = map.keySet().iterator();
Iterator<E> it = map.keySet().iterator();
while (it.hasNext()) {
Object current = it.next();
E current = it.next();
for (int index = getCount(current); index > 0; index--) {
array[i++] = current;
array[i++] = (T) current;
}
}
if (array.length > size) {
array[size] = null;
while (i < array.length) {
array[i++] = null;
}
return array;
}
/**
* Returns an unmodifiable view of the underlying map's key set.
*
*
* @return the set of unique elements in this bag
*/
public Set uniqueSet() {
public Set<E> uniqueSet() {
if (uniqueSet == null) {
uniqueSet = UnmodifiableSet.decorate(map.keySet());
uniqueSet = UnmodifiableSet.<E> decorate(map.keySet());
}
return uniqueSet;
}
@ -485,26 +490,28 @@ public abstract class AbstractMapBag implements Bag {
//-----------------------------------------------------------------------
/**
* Write the map out using a custom routine.
* @param out the output stream
* @param out the output stream
* @throws IOException
*/
protected void doWriteObject(ObjectOutputStream out) throws IOException {
out.writeInt(map.size());
for (Iterator it = map.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
for (Iterator<Map.Entry<E, MutableInteger>> it = map.entrySet().iterator(); it.hasNext();) {
Map.Entry<E, MutableInteger> entry = it.next();
out.writeObject(entry.getKey());
out.writeInt(((MutableInteger) entry.getValue()).value);
out.writeInt(entry.getValue().value);
}
}
/**
* Read the map in using a custom routine.
* @param map the map to use
* @param in the input stream
* @param map the map to use
* @param in the input stream
* @throws IOException
* @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;
int entrySize = in.readInt();
for (int i = 0; i < entrySize; i++) {
@ -514,14 +521,13 @@ public abstract class AbstractMapBag implements Bag {
size += count;
}
}
//-----------------------------------------------------------------------
/**
* Compares this Bag to another.
* This Bag equals another Bag if it contains the same number of occurrences of
* the same elements.
* Compares this Bag to another. This Bag equals another Bag if it contains
* the same number of occurrences of the same elements.
*
* @param object the Bag to compare to
* @param object the Bag to compare to
* @return true if equal
*/
public boolean equals(Object object) {
@ -531,12 +537,12 @@ public abstract class AbstractMapBag implements Bag {
if (object instanceof Bag == false) {
return false;
}
Bag other = (Bag) object;
Bag<?> other = (Bag<?>) object;
if (other.size() != size()) {
return false;
}
for (Iterator it = map.keySet().iterator(); it.hasNext();) {
Object element = it.next();
for (Iterator<E> it = map.keySet().iterator(); it.hasNext();) {
E element = it.next();
if (other.getCount(element) != getCount(element)) {
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.
* The hash code is defined as the sum total of a hash code for each element.
* The per element hash code is defined as
* <code>(e==null ? 0 : e.hashCode()) ^ noOccurances)</code>.
* This hash code is compatible with the Set interface.
* The hash code is defined as the sum total of a hash code for each
* element. The per element hash code is defined as
* <code>(e==null ? 0 : e.hashCode()) ^ noOccurances)</code>. This hash code
* is compatible with the Set interface.
*
* @return the hash code of the Bag
*/
public int hashCode() {
int total = 0;
for (Iterator it = map.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
Object element = entry.getKey();
MutableInteger count = (MutableInteger) entry.getValue();
for (Iterator<Map.Entry<E, MutableInteger>> it = map.entrySet().iterator(); it.hasNext();) {
Map.Entry<E, MutableInteger> entry = it.next();
E element = entry.getKey();
MutableInteger count = entry.getValue();
total += (element == null ? 0 : element.hashCode()) ^ count.value;
}
return total;
@ -575,7 +581,7 @@ public abstract class AbstractMapBag implements Bag {
}
StringBuffer buf = new StringBuffer();
buf.append('[');
Iterator it = uniqueSet().iterator();
Iterator<E> it = uniqueSet().iterator();
while (it.hasNext()) {
Object current = it.next();
int count = getCount(current);
@ -589,5 +595,5 @@ public abstract class AbstractMapBag implements Bag {
buf.append(']');
return buf.toString();
}
}

View File

@ -41,8 +41,8 @@ import org.apache.commons.collections.Bag;
* @author Chuck Burdick
* @author Stephen Colebourne
*/
public class HashBag
extends AbstractMapBag implements Bag, Serializable {
public class HashBag<E>
extends AbstractMapBag<E> implements Bag<E>, Serializable {
/** Serial version lock */
private static final long serialVersionUID = -6561115435802554013L;
@ -51,7 +51,7 @@ public class HashBag
* Constructs an empty <code>HashBag</code>.
*/
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
*/
public HashBag(Collection coll) {
public HashBag(Collection<? extends E> coll) {
this();
addAll(coll);
}
@ -78,7 +78,7 @@ public class HashBag
*/
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
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
*/
public class TransformedBag
extends TransformedCollection implements Bag {
public class TransformedBag<E>
extends TransformedCollection<E> implements Bag<E> {
/** Serialization version */
private static final long serialVersionUID = 5421170911299074185L;
@ -56,8 +56,8 @@ public class TransformedBag
* @return a new transformed Bag
* @throws IllegalArgumentException if bag or transformer is null
*/
public static Bag decorate(Bag bag, Transformer transformer) {
return new TransformedBag(bag, transformer);
public static <E> Bag<E> decorate(Bag<E> bag, Transformer<? super E, ? extends E> transformer) {
return new TransformedBag<E>(bag, transformer);
}
/**
@ -74,13 +74,14 @@ public class TransformedBag
* @throws IllegalArgumentException if bag or transformer is null
* @since Commons Collections 3.3
*/
// TODO: Generics
public static Bag decorateTransform(Bag bag, Transformer transformer) {
TransformedBag decorated = new TransformedBag(bag, transformer);
if (transformer != null && bag != null && bag.size() > 0) {
Object[] values = bag.toArray();
bag.clear();
for(int i=0; i<values.length; i++) {
decorated.getCollection().add(transformer.transform(values[i]));
decorated.decorated().add(transformer.transform(values[i]));
}
}
return decorated;
@ -97,7 +98,7 @@ public class TransformedBag
* @param transformer the transformer to use for conversion, must not be 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);
}
@ -106,8 +107,8 @@ public class TransformedBag
*
* @return the decorated bag
*/
protected Bag getBag() {
return (Bag) collection;
protected Bag<E> getBag() {
return (Bag<E>) collection;
}
//-----------------------------------------------------------------------
@ -120,14 +121,13 @@ public class TransformedBag
}
//-----------------------------------------------------------------------
public boolean add(Object object, int nCopies) {
object = transform(object);
return getBag().add(object, nCopies);
public boolean add(E object, int nCopies) {
return getBag().add(transform(object), nCopies);
}
public Set uniqueSet() {
Set set = getBag().uniqueSet();
return TransformedSet.decorate(set, transformer);
public Set<E> uniqueSet() {
Set<E> set = getBag().uniqueSet();
return TransformedSet.<E>decorate(set, transformer);
}
}

View File

@ -36,8 +36,8 @@ import org.apache.commons.collections.Transformer;
*
* @author Stephen Colebourne
*/
public class TransformedSortedBag
extends TransformedBag implements SortedBag {
public class TransformedSortedBag<E>
extends TransformedBag<E> implements SortedBag<E> {
/** Serialization version */
private static final long serialVersionUID = -251737742649401930L;
@ -54,8 +54,8 @@ public class TransformedSortedBag
* @return a new transformed SortedBag
* @throws IllegalArgumentException if bag or transformer is null
*/
public static SortedBag decorate(SortedBag bag, Transformer transformer) {
return new TransformedSortedBag(bag, transformer);
public static <E> SortedBag<E> decorate(SortedBag<E> bag, Transformer<? super E, ? extends E> transformer) {
return new TransformedSortedBag<E>(bag, transformer);
}
/**
@ -72,13 +72,14 @@ public class TransformedSortedBag
* @throws IllegalArgumentException if bag or transformer is null
* @since Commons Collections 3.3
*/
// TODO: Generics
public static SortedBag decorateTransform(SortedBag bag, Transformer transformer) {
TransformedSortedBag decorated = new TransformedSortedBag(bag, transformer);
if (transformer != null && bag != null && bag.size() > 0) {
Object[] values = bag.toArray();
bag.clear();
for(int i=0; i<values.length; i++) {
decorated.getCollection().add(transformer.transform(values[i]));
decorated.decorated().add(transformer.transform(values[i]));
}
}
return decorated;
@ -95,7 +96,7 @@ public class TransformedSortedBag
* @param transformer the transformer to use for conversion, must not be 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);
}
@ -104,20 +105,20 @@ public class TransformedSortedBag
*
* @return the decorated bag
*/
protected SortedBag getSortedBag() {
return (SortedBag) collection;
protected SortedBag<E> getSortedBag() {
return (SortedBag<E>) collection;
}
//-----------------------------------------------------------------------
public Object first() {
public E first() {
return getSortedBag().first();
}
public Object last() {
public E last() {
return getSortedBag().last();
}
public Comparator comparator() {
public Comparator<? super E> 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
* iterator.
* <p>
* A <code>Bag</code> stores each object in the collection together with a
* count of occurrences. Extra methods on the interface allow multiple copies
* of an object to be added or removed at once. It is important to read the
* interface javadoc carefully as several methods violate the
* <code>Collection</code> interface specification.
* A <code>Bag</code> stores each object in the collection together with a count
* of occurrences. Extra methods on the interface allow multiple copies of an
* object to be added or removed at once. It is important to read the interface
* javadoc carefully as several methods violate the <code>Collection</code>
* interface specification.
*
* @since Commons Collections 3.0 (previously in main package v2.0)
* @version $Revision$ $Date$
@ -46,60 +46,69 @@ import org.apache.commons.collections.SortedBag;
* @author Chuck Burdick
* @author Stephen Colebourne
*/
public class TreeBag
extends AbstractMapBag implements SortedBag, Serializable {
public class TreeBag<E> extends AbstractMapBag<E> implements SortedBag<E>, Serializable {
/** Serial version lock */
private static final long serialVersionUID = -7740146511091606676L;
/**
* Constructs an empty <code>TreeBag</code>.
*/
public TreeBag() {
super(new TreeMap());
super(new TreeMap<E, MutableInteger>());
}
/**
* Constructs an empty bag that maintains order on its unique
* representative members according to the given {@link Comparator}.
* Constructs an empty bag that maintains order on its unique representative
* members according to the given {@link Comparator}.
*
* @param comparator the comparator to use
* @param comparator the comparator to use
*/
public TreeBag(Comparator comparator) {
super(new TreeMap(comparator));
public TreeBag(Comparator<? super E> comparator) {
super(new TreeMap<E, MutableInteger>(comparator));
}
/**
* Constructs a <code>TreeBag</code> containing all the members of the
* 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();
addAll(coll);
}
//-----------------------------------------------------------------------
public boolean add(Object o) {
if(comparator() == null && !(o instanceof Comparable)) {
throw new IllegalArgumentException("Objects of type " + o.getClass() + " cannot be added to " +
// TODO: Generics - should this be E<? extends Comparable> or some such?
public boolean add(E object) {
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");
}
return super.add(o);
return super.add(object);
}
//-----------------------------------------------------------------------
public Object first() {
return ((SortedMap) getMap()).firstKey();
public E first() {
return getMap().firstKey();
}
public Object last() {
return ((SortedMap) getMap()).lastKey();
public E last() {
return getMap().lastKey();
}
public Comparator comparator() {
return ((SortedMap) getMap()).comparator();
public Comparator<? super E> 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.
*/
@SuppressWarnings("unchecked")
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
Comparator comp = (Comparator) in.readObject();
super.doReadObject(new TreeMap(comp), in);
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -18,11 +18,11 @@ package org.apache.commons.collections.buffer;
import java.util.Collection;
/**
/**
* CircularFifoBuffer is a first in first out buffer with a fixed size that
* replaces its oldest element if full.
* <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
* were added. The iteration order is the same as the removal order.
* <p>
@ -46,7 +46,7 @@ import java.util.Collection;
* @author Stefano Fornari
* @author Stephen Colebourne
*/
public class CircularFifoBuffer extends BoundedFifoBuffer {
public class CircularFifoBuffer<E> extends BoundedFifoBuffer<E> {
/** Serialization version */
private static final long serialVersionUID = -8423413834657610406L;
@ -60,7 +60,7 @@ public class CircularFifoBuffer extends BoundedFifoBuffer {
/**
* Constructor that creates a buffer with the specified size.
*
*
* @param size the size of the buffer (cannot be changed)
* @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.
* The collection size also sets the buffer size
*
*
* @param coll the collection to copy into the buffer, may not be null
* @throws NullPointerException if the collection is null
*/
public CircularFifoBuffer(Collection coll) {
public CircularFifoBuffer(Collection<E> coll) {
super(coll);
}
@ -86,11 +86,11 @@ public class CircularFifoBuffer extends BoundedFifoBuffer {
* @param element the element to add
* @return true, always
*/
public boolean add(Object element) {
public boolean add(E element) {
if (isFull()) {
remove();
}
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.BufferUnderflowException;
import org.apache.commons.collections.comparators.ComparableComparator;
/**
* Binary heap implementation of <code>Buffer</code> that provides for
@ -62,8 +63,7 @@ import org.apache.commons.collections.BufferUnderflowException;
* @author Stephen Colebourne
* @author Steve Phelps
*/
public class PriorityBuffer extends AbstractCollection
implements Buffer, Serializable {
public class PriorityBuffer<E> extends AbstractCollection<E> implements Buffer<E>, Serializable {
/** Serialization lock. */
private static final long serialVersionUID = 6891186490470027896L;
@ -76,21 +76,24 @@ public class PriorityBuffer extends AbstractCollection
/**
* The elements in this buffer.
*/
protected Object[] elements;
protected E[] elements;
/**
* The number of elements currently in this buffer.
*/
protected int size;
/**
* If true, the first element as determined by the sort order will
* be returned. If false, the last element as determined by the
* sort order will be returned.
*/
protected boolean ascendingOrder;
/**
* 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,
* null means use natural order
*/
public PriorityBuffer(Comparator comparator) {
public PriorityBuffer(Comparator<? super E> comparator) {
this(DEFAULT_CAPACITY, true, comparator);
}
@ -131,7 +134,7 @@ public class PriorityBuffer extends AbstractCollection
* @param comparator the comparator used to order the elements,
* null means use natural order
*/
public PriorityBuffer(boolean ascendingOrder, Comparator comparator) {
public PriorityBuffer(boolean ascendingOrder, Comparator<? super E> comparator) {
this(DEFAULT_CAPACITY, ascendingOrder, comparator);
}
@ -155,7 +158,7 @@ public class PriorityBuffer extends AbstractCollection
* null means use natural order
* @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);
}
@ -183,7 +186,8 @@ public class PriorityBuffer extends AbstractCollection
* null means use natural order
* @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();
if (capacity <= 0) {
throw new IllegalArgumentException("invalid capacity");
@ -191,8 +195,8 @@ public class PriorityBuffer extends AbstractCollection
this.ascendingOrder = ascendingOrder;
//+1 as 0 is noop
this.elements = new Object[capacity + 1];
this.comparator = comparator;
this.elements = (E[]) new Object[capacity + 1];
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
*/
public Comparator comparator() {
public Comparator<? super E> comparator() {
return comparator;
}
@ -227,8 +231,9 @@ public class PriorityBuffer extends AbstractCollection
/**
* Clears all elements from the buffer.
*/
@SuppressWarnings("unchecked")
public void clear() {
elements = new Object[elements.length]; // for gc
elements = (E[]) new Object[elements.length]; // for gc
size = 0;
}
@ -240,11 +245,11 @@ public class PriorityBuffer extends AbstractCollection
* @param element the element to be added
* @return true always
*/
public boolean add(Object element) {
public boolean add(E element) {
if (isAtCapacity()) {
grow();
}
// percolate element to it's place in tree
// percolate element to its place in tree
if (ascendingOrder) {
percolateUpMinHeap(element);
} else {
@ -259,12 +264,11 @@ public class PriorityBuffer extends AbstractCollection
* @return the next element
* @throws BufferUnderflowException if the buffer is empty
*/
public Object get() {
public E get() {
if (isEmpty()) {
throw new BufferUnderflowException();
} else {
return elements[1];
}
return elements[1];
}
/**
@ -273,8 +277,8 @@ public class PriorityBuffer extends AbstractCollection
* @return the next element
* @throws BufferUnderflowException if the buffer is empty
*/
public Object remove() {
final Object result = get();
public E remove() {
final E result = get();
elements[1] = elements[size--];
// 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
*/
protected void percolateDownMinHeap(final int index) {
final Object element = elements[index];
final E element = elements[index];
int hole = index;
while ((hole * 2) <= size) {
@ -345,7 +349,7 @@ public class PriorityBuffer extends AbstractCollection
* @param index the index of the element
*/
protected void percolateDownMaxHeap(final int index) {
final Object element = elements[index];
final E element = elements[index];
int hole = index;
while ((hole * 2) <= size) {
@ -378,7 +382,7 @@ public class PriorityBuffer extends AbstractCollection
*/
protected void percolateUpMinHeap(final int index) {
int hole = index;
Object element = elements[hole];
E element = elements[hole];
while (hole > 1 && compare(element, elements[hole / 2]) < 0) {
// save element that is being pushed down
// as the element "bubble" is percolated up
@ -396,7 +400,7 @@ public class PriorityBuffer extends AbstractCollection
*
* @param element the element
*/
protected void percolateUpMinHeap(final Object element) {
protected void percolateUpMinHeap(final E element) {
elements[++size] = element;
percolateUpMinHeap(size);
}
@ -410,7 +414,7 @@ public class PriorityBuffer extends AbstractCollection
*/
protected void percolateUpMaxHeap(final int index) {
int hole = index;
Object element = elements[hole];
E element = elements[hole];
while (hole > 1 && compare(element, elements[hole / 2]) > 0) {
// save element that is being pushed down
@ -430,7 +434,7 @@ public class PriorityBuffer extends AbstractCollection
*
* @param element the element
*/
protected void percolateUpMaxHeap(final Object element) {
protected void percolateUpMaxHeap(final E element) {
elements[++size] = element;
percolateUpMaxHeap(size);
}
@ -443,19 +447,16 @@ public class PriorityBuffer extends AbstractCollection
* @param b the second object
* @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) {
if (comparator != null) {
return comparator.compare(a, b);
} else {
return ((Comparable) a).compareTo(b);
}
protected int compare(E a, E b) {
return comparator.compare(a, b);
}
/**
* Increases the size of the heap to support additional elements
*/
@SuppressWarnings("unchecked")
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);
elements = array;
}
@ -466,8 +467,8 @@ public class PriorityBuffer extends AbstractCollection
*
* @return an iterator over this heap's elements
*/
public Iterator iterator() {
return new Iterator() {
public Iterator<E> iterator() {
return new Iterator<E>() {
private int index = 1;
private int lastReturnedIndex = -1;
@ -476,7 +477,7 @@ public class PriorityBuffer extends AbstractCollection
return index <= size;
}
public Object next() {
public E next() {
if (!hasNext()) {
throw new NoSuchElementException();
}

View File

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

View File

@ -63,7 +63,7 @@ import org.apache.commons.collections.BufferUnderflowException;
* @author Thomas Knych
* @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()
// 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;
/** The array of objects in the buffer. */
protected transient Object[] buffer;
protected transient E[] buffer;
/** The current head index. */
protected transient int head;
/** The current tail index. */
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.
* The integer must be a positive integer.
*
*
* @param initialSize the initial size of the buffer
* @throws IllegalArgumentException if the size is less than 1
*/
@SuppressWarnings("unchecked")
public UnboundedFifoBuffer(int initialSize) {
if (initialSize <= 0) {
throw new IllegalArgumentException("The size must be greater than 0");
}
buffer = new Object[initialSize + 1];
buffer = (E[]) new Object[initialSize + 1];
head = 0;
tail = 0;
}
@ -108,7 +111,7 @@ public class UnboundedFifoBuffer extends AbstractCollection implements Buffer, S
//-----------------------------------------------------------------------
/**
* Write the buffer out using a custom routine.
*
*
* @param out the output stream
* @throws IOException
*/
@ -116,25 +119,26 @@ public class UnboundedFifoBuffer extends AbstractCollection implements Buffer, S
out.defaultWriteObject();
out.writeInt(size());
out.writeInt(buffer.length);
for (Iterator it = iterator(); it.hasNext();) {
for (Iterator<E> it = iterator(); it.hasNext();) {
out.writeObject(it.next());
}
}
/**
* Read the buffer in using a custom routine.
*
*
* @param in the input stream
* @throws IOException
* @throws ClassNotFoundException
*/
@SuppressWarnings("unchecked")
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
int size = in.readInt();
int length = in.readInt();
buffer = new Object[length];
buffer = (E[]) new Object[length];
for (int i = 0; i < size; i++) {
buffer[i] = in.readObject();
buffer[i] = (E) in.readObject();
}
head = 0;
tail = size;
@ -174,14 +178,15 @@ public class UnboundedFifoBuffer extends AbstractCollection implements Buffer, S
* @return true, always
* @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) {
throw new NullPointerException("Attempted to add null object to buffer");
}
if (size() + 1 >= buffer.length) {
// 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;
// move head to element zero in the new array
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
* @throws BufferUnderflowException if this buffer is empty
*/
public Object get() {
public E get() {
if (isEmpty()) {
throw new BufferUnderflowException("The buffer is already empty");
}
@ -221,12 +226,12 @@ public class UnboundedFifoBuffer extends AbstractCollection implements Buffer, S
* @return the removed object
* @throws BufferUnderflowException if this buffer is empty
*/
public Object remove() {
public E remove() {
if (isEmpty()) {
throw new BufferUnderflowException("The buffer is already empty");
}
Object element = buffer[head];
E element = buffer[head];
if (element != null) {
buffer[head] = null;
head = increment(head);
@ -236,7 +241,7 @@ public class UnboundedFifoBuffer extends AbstractCollection implements Buffer, S
/**
* Increments the internal index.
*
*
* @param index the index to increment
* @return the updated index
*/
@ -250,7 +255,7 @@ public class UnboundedFifoBuffer extends AbstractCollection implements Buffer, S
/**
* Decrements the internal index.
*
*
* @param index the index to decrement
* @return the updated index
*/
@ -267,8 +272,8 @@ public class UnboundedFifoBuffer extends AbstractCollection implements Buffer, S
*
* @return an iterator over this buffer's elements
*/
public Iterator iterator() {
return new Iterator() {
public Iterator<E> iterator() {
return new Iterator<E>() {
private int index = head;
private int lastReturnedIndex = -1;
@ -278,7 +283,7 @@ public class UnboundedFifoBuffer extends AbstractCollection implements Buffer, S
}
public Object next() {
public E next() {
if (!hasNext()) {
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
*/
public final class BooleanComparator implements Comparator, Serializable {
public final class BooleanComparator implements Comparator<Boolean>, Serializable {
/** Serialization version. */
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
* according to the value of {@link #sortsTrueFirst()}.

View File

@ -40,13 +40,14 @@ import java.util.Comparator;
*
* @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. */
private static final long serialVersionUID=-291439688585137865L;
/** 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
*/
public static ComparableComparator getInstance() {
return instance;
@SuppressWarnings("unchecked")
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>,
* or when <code>((Comparable)obj1).compareTo(obj2)</code> does
*/
public int compare(Object obj1, Object obj2) {
return ((Comparable)obj1).compareTo(obj2);
public int compare(E obj1, E obj2) {
return obj1.compareTo(obj2);
}
//-----------------------------------------------------------------------

View File

@ -54,13 +54,13 @@ import java.util.List;
* @author Morgan Delagrange
* @version $Revision$ $Date$
*/
public class ComparatorChain implements Comparator, Serializable {
public class ComparatorChain<E> implements Comparator<E>, Serializable {
/** Serialization version from Collections 2.0. */
private static final long serialVersionUID = -721644942746081630L;
/** The list of comparators in the chain. */
protected List comparatorChain = null;
protected List<Comparator<E>> comparatorChain = null;
/** Order - false (clear) = ascend; true (set) = descend. */
protected BitSet orderingBits = null;
/** Whether the chain has been "locked". */
@ -70,32 +70,32 @@ public class ComparatorChain implements Comparator, Serializable {
/**
* Construct a ComparatorChain with no Comparators.
* 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
*/
public ComparatorChain() {
this(new ArrayList(),new BitSet());
this(new ArrayList<Comparator<E>>(), new BitSet());
}
/**
* Construct a ComparatorChain with a single Comparator,
* sorting in the forward order
*
*
* @param comparator First comparator in the Comparator chain
*/
public ComparatorChain(Comparator comparator) {
this(comparator,false);
public ComparatorChain(Comparator<E> comparator) {
this(comparator, false);
}
/**
* Construct a Comparator chain with a single Comparator,
* sorting in the given order
*
*
* @param comparator First Comparator in the ComparatorChain
* @param reverse false = forward sort; true = reverse sort
*/
public ComparatorChain(Comparator comparator, boolean reverse) {
comparatorChain = new ArrayList();
public ComparatorChain(Comparator<E> comparator, boolean reverse) {
comparatorChain = new ArrayList<Comparator<E>>();
comparatorChain.add(comparator);
orderingBits = new BitSet(1);
if (reverse == true) {
@ -105,14 +105,14 @@ public class ComparatorChain implements Comparator, Serializable {
/**
* 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.
*
*
* @param list List of Comparators
* @see #ComparatorChain(List,BitSet)
*/
public ComparatorChain(List list) {
this(list,new BitSet(list.size()));
public ComparatorChain(List<Comparator<E>> list) {
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
* sort order is used; a return value of <i>true</i>
* indicates reverse sort order.
*
*
* @param list List of Comparators. NOTE: This constructor does not perform a
* defensive copy of the list
* @param bits Sort order for each Comparator. Extra bits are ignored,
* unless extra Comparators are added by another method.
*/
public ComparatorChain(List list, BitSet bits) {
public ComparatorChain(List<Comparator<E>> list, BitSet bits) {
comparatorChain = list;
orderingBits = bits;
}
@ -139,23 +139,23 @@ public class ComparatorChain implements Comparator, Serializable {
/**
* Add a Comparator to the end of the chain using the
* forward sort order
*
*
* @param comparator Comparator with the forward sort order
*/
public void addComparator(Comparator comparator) {
addComparator(comparator,false);
public void addComparator(Comparator<E> comparator) {
addComparator(comparator, false);
}
/**
* Add a Comparator to the end of the chain using the
* given sort order
*
*
* @param comparator Comparator to add to the end of the chain
* @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();
comparatorChain.add(comparator);
if (reverse == true) {
orderingBits.set(comparatorChain.size() - 1);
@ -165,26 +165,25 @@ public class ComparatorChain implements Comparator, Serializable {
/**
* Replace the Comparator at the given index, maintaining
* the existing sort order.
*
*
* @param index index of the Comparator to replace
* @param comparator Comparator to place at the given index
* @exception IndexOutOfBoundsException
* if index &lt; 0 or index &gt;= size()
*/
public void setComparator(int index, Comparator comparator)
throws IndexOutOfBoundsException {
setComparator(index,comparator,false);
public void setComparator(int index, Comparator<E> comparator) throws IndexOutOfBoundsException {
setComparator(index, comparator, false);
}
/**
* Replace the Comparator at the given index in the
* ComparatorChain, using the given sort order
*
*
* @param index index of the Comparator to replace
* @param comparator Comparator to set
* @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();
comparatorChain.set(index,comparator);
@ -195,11 +194,10 @@ public class ComparatorChain implements Comparator, Serializable {
}
}
/**
* Change the sort order at the given index in the
* ComparatorChain to a forward sort.
*
*
* @param index Index of the ComparatorChain
*/
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
* ComparatorChain to a reverse sort.
*
*
* @param index Index of the ComparatorChain
*/
public void setReverseSort(int index) {
@ -220,7 +218,7 @@ public class ComparatorChain implements Comparator, Serializable {
/**
* Number of Comparators in the current ComparatorChain.
*
*
* @return Comparator count
*/
public int size() {
@ -231,8 +229,8 @@ public class ComparatorChain implements Comparator, Serializable {
* Determine if modifications can still be made to the
* ComparatorChain. ComparatorChains cannot be modified
* 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.
*/
public boolean isLocked() {
@ -256,7 +254,7 @@ public class ComparatorChain implements Comparator, Serializable {
/**
* Perform comparisons on the Objects as per
* Comparator.compare(o1,o2).
*
*
* @param o1 the first object to compare
* @param o2 the second object to compare
* @return -1, 0, or 1
@ -264,31 +262,29 @@ public class ComparatorChain implements Comparator, Serializable {
* if the ComparatorChain does not contain at least one
* Comparator
*/
public int compare(Object o1, Object o2) throws UnsupportedOperationException {
public int compare(E o1, E o2) throws UnsupportedOperationException {
if (isLocked == false) {
checkChainIntegrity();
isLocked = true;
}
// iterate over all comparators in the chain
Iterator comparators = comparatorChain.iterator();
Iterator<Comparator<E>> comparators = comparatorChain.iterator();
for (int comparatorIndex = 0; comparators.hasNext(); ++comparatorIndex) {
Comparator comparator = (Comparator) comparators.next();
Comparator<E> comparator = comparators.next();
int retval = comparator.compare(o1,o2);
if (retval != 0) {
// invert the order if it is a reverse sort
if (orderingBits.get(comparatorIndex) == true) {
if(Integer.MIN_VALUE == retval) {
retval = Integer.MAX_VALUE;
} else {
} else {
retval *= -1;
}
}
return retval;
}
}
// 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
* {@link #equals(Object) equals}.
*
*
* @return a suitable hash code
* @since Commons Collections 3.0
*/
public int hashCode() {
int hash = 0;
if(null != comparatorChain) {
if (null != comparatorChain) {
hash ^= comparatorChain.hashCode();
}
if(null != orderingBits) {
if (null != orderingBits) {
hash ^= orderingBits.hashCode();
}
return hash;
}
/**
* Returns <code>true</code> iff <i>that</i> Object is
* is a {@link Comparator} whose ordering is known to be
* Returns <code>true</code> iff <i>that</i> Object is
* is a {@link Comparator} whose ordering is known to be
* equivalent to mine.
* <p>
* This implementation returns <code>true</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.
* Subclasses may want to override this behavior to remain consistent
* with the {@link Comparator#equals(Object)} contract.
*
*
* @param object the object to compare with
* @return true if equal
* @since Commons Collections 3.0
*/
public boolean equals(Object object) {
if(this == object) {
if (this == object) {
return true;
} else if(null == object) {
return false;
} 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 {
}
if (null == object) {
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.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
/**
* A Comparator which imposes a specific order on a specific set of Objects.
* Objects are presented to the FixedOrderComparator in a specified order and
* subsequent calls to {@link #compare(Object, Object) compare} yield that order.
@ -48,55 +47,47 @@ import java.util.Map;
* @author Stephen Colebourne
* @author Janek Bogucki
*/
public class FixedOrderComparator implements Comparator {
public class FixedOrderComparator<T> implements Comparator<T> {
/**
* Behavior when comparing unknown Objects:
* unknown objects compare as before known Objects.
/**
* Unknown object behavior enum.
* @since Commons Collections 5
*/
public static final int UNKNOWN_BEFORE = 0;
/**
* 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;
public static enum UnknownObjectBehavior {
BEFORE, AFTER, EXCEPTION;
}
/** 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 */
private int counter = 0;
/** Is the comparator locked against further change */
private boolean isLocked = false;
/** The behaviour in the case of an unknown object */
private int unknownObjectBehavior = UNKNOWN_THROW_EXCEPTION;
private UnknownObjectBehavior unknownObjectBehavior = UnknownObjectBehavior.EXCEPTION;
// Constructors
//-----------------------------------------------------------------------
/**
/**
* Constructs an empty FixedOrderComparator.
*/
public FixedOrderComparator() {
super();
}
/**
/**
* Constructs a FixedOrderComparator which uses the order of the given array
* to compare the objects.
* <p>
* The array is copied, so later changes will not affect the comparator.
*
*
* @param items the items that the comparator can compare in order
* @throws IllegalArgumentException if the array is null
*/
public FixedOrderComparator(Object[] items) {
public FixedOrderComparator(T[] items) {
super();
if (items == 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
* to compare the objects.
* <p>
* The list is copied, so later changes will not affect the comparator.
*
*
* @param items the items that the comparator can compare in order
* @throws IllegalArgumentException if the list is null
*/
public FixedOrderComparator(List items) {
public FixedOrderComparator(List<T> items) {
super();
if (items == null) {
throw new IllegalArgumentException("The list of items must not be null");
}
for (Iterator it = items.iterator(); it.hasNext();) {
add(it.next());
for (T t : items) {
add(t);
}
}
@ -130,7 +121,7 @@ public class FixedOrderComparator implements Comparator {
/**
* Returns true if modifications cannot be made to the FixedOrderComparator.
* FixedOrderComparators cannot be modified once they have performed a comparison.
*
*
* @return true if attempts to change the FixedOrderComparator yield an
* 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.
*
*
* @throws UnsupportedOperationException if the comparator is locked
*/
protected void checkLocked() {
@ -149,118 +140,108 @@ public class FixedOrderComparator implements Comparator {
}
}
/**
/**
* Gets the behavior for comparing unknown objects.
*
* @return the flag for unknown behaviour - UNKNOWN_AFTER,
* UNKNOWN_BEFORE or UNKNOWN_THROW_EXCEPTION
*
* @return {@link UnknownObjectBehavior}
*/
public int getUnknownObjectBehavior() {
public UnknownObjectBehavior getUnknownObjectBehavior() {
return unknownObjectBehavior;
}
/**
/**
* Sets the behavior for comparing unknown objects.
*
*
* @param unknownObjectBehavior the flag for unknown behaviour -
* UNKNOWN_AFTER, UNKNOWN_BEFORE or UNKNOWN_THROW_EXCEPTION
* @throws UnsupportedOperationException if a comparison has been performed
* @throws IllegalArgumentException if the unknown flag is not valid
*/
public void setUnknownObjectBehavior(int unknownObjectBehavior) {
public void setUnknownObjectBehavior(UnknownObjectBehavior unknownObjectBehavior) {
checkLocked();
if (unknownObjectBehavior != UNKNOWN_AFTER
&& unknownObjectBehavior != UNKNOWN_BEFORE
&& unknownObjectBehavior != UNKNOWN_THROW_EXCEPTION) {
throw new IllegalArgumentException("Unrecognised value for unknown behaviour flag");
if (unknownObjectBehavior == null) {
throw new IllegalArgumentException("Unknown object behavior must not be null");
}
this.unknownObjectBehavior = unknownObjectBehavior;
}
// Methods for adding items
//-----------------------------------------------------------------------
/**
/**
* 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
* replaced with the new position.
*
*
* @param obj the item to be added to the Comparator.
* @return true if obj has been added for the first time, false if
* it was already known to the Comparator.
* @throws UnsupportedOperationException if a comparison has already been made
*/
public boolean add(Object obj) {
public boolean add(T obj) {
checkLocked();
Object position = map.put(obj, new Integer(counter++));
Integer position = map.put(obj, new Integer(counter++));
return (position == null);
}
/**
* 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
* @param newObj an item to be added to the Comparator's set of
* known objects
* @return true if newObj has been added for the first time, false if
* 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.
* @throws UnsupportedOperationException if a comparison has already been made
*/
public boolean addAsEqual(Object existingObj, Object newObj) {
public boolean addAsEqual(T existingObj, T newObj) {
checkLocked();
Integer position = (Integer) map.get(existingObj);
Integer position = map.get(existingObj);
if (position == null) {
throw new IllegalArgumentException(existingObj + " not known to " + this);
}
Object result = map.put(newObj, position);
Integer result = map.put(newObj, position);
return (result == null);
}
// Comparator methods
//-----------------------------------------------------------------------
/**
/**
* Compares two objects according to the order of this Comparator.
* <p>
* 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.
*
*
* @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 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
* via {@link #setUnknownObjectBehavior(int)}.
*/
public int compare(Object obj1, Object obj2) {
public int compare(T obj1, T obj2) {
isLocked = true;
Integer position1 = (Integer) map.get(obj1);
Integer position2 = (Integer) map.get(obj2);
Integer position1 = map.get(obj1);
Integer position2 = map.get(obj2);
if (position1 == null || position2 == null) {
switch (unknownObjectBehavior) {
case UNKNOWN_BEFORE :
if (position1 == null) {
return (position2 == null) ? 0 : -1;
} else {
return 1;
}
case UNKNOWN_AFTER :
if (position1 == null) {
return (position2 == null) ? 0 : 1;
} else {
return -1;
}
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);
case BEFORE:
return position1 == null ? position2 == null ? 0 : -1 : 1;
case AFTER:
return position1 == null ? position2 == null ? 0 : 1 : -1;
case EXCEPTION:
Object unknownObj = (position1 == null) ? obj1 : obj2;
throw new IllegalArgumentException("Attempting to compare unknown object "
+ unknownObj);
default: //could be null
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.util.Comparator;
import org.apache.commons.collections.ComparatorUtils;
/**
* Reverses the order of another comparator by reversing the arguments
* to its {@link #compare(Object, Object) compare} method.
@ -30,13 +32,13 @@ import java.util.Comparator;
*
* @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. */
private static final long serialVersionUID = 2858887242028539265L;
/** 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
*/
public ReverseComparator(Comparator comparator) {
if(comparator != null) {
this.comparator = comparator;
} else {
this.comparator = ComparableComparator.getInstance();
}
@SuppressWarnings("unchecked")
public ReverseComparator(Comparator<E> comparator) {
this.comparator = comparator == null ? ComparatorUtils.NATURAL_COMPARATOR : comparator;
}
//-----------------------------------------------------------------------
@ -76,7 +75,7 @@ public class ReverseComparator implements Comparator, Serializable {
* @param obj2 the second object to compare
* @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);
}
@ -109,16 +108,17 @@ public class ReverseComparator implements Comparator, Serializable {
* @since Commons Collections 3.0
*/
public boolean equals(Object object) {
if(this == object) {
if (this == object) {
return true;
} else if(null == object) {
return false;
} else if(object.getClass().equals(this.getClass())) {
ReverseComparator thatrc = (ReverseComparator)object;
return comparator.equals(thatrc.comparator);
} else {
}
if (null == object) {
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 org.apache.commons.collections.ComparatorUtils;
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.comparators.ComparableComparator
*/
public class TransformingComparator implements Comparator {
public class TransformingComparator<E> implements Comparator<E> {
/** The decorated comparator. */
protected Comparator decorated;
protected Comparator<E> decorated;
/** 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>
*/
public TransformingComparator(Transformer transformer) {
this(transformer, new ComparableComparator());
@SuppressWarnings("unchecked")
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 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.transformer = transformer;
}
@ -68,9 +70,9 @@ public class TransformingComparator implements Comparator {
* @param obj2 the second object to transform then compare
* @return negative if obj1 is less, positive if greater, zero if equal
*/
public int compare(Object obj1, Object obj2) {
Object value1 = this.transformer.transform(obj1);
Object value2 = this.transformer.transform(obj2);
public int compare(E obj1, E obj2) {
E value1 = this.transformer.transform(obj1);
E value2 = this.transformer.transform(obj2);
return this.decorated.compare(value1, value2);
}

View File

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

View File

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

View File

@ -18,7 +18,6 @@ package org.apache.commons.collections.functors;
import java.io.Serializable;
import java.util.Collection;
import java.util.Iterator;
import org.apache.commons.collections.Closure;
@ -30,13 +29,13 @@ import org.apache.commons.collections.Closure;
*
* @author Stephen Colebourne
*/
public class ChainedClosure implements Closure, Serializable {
public class ChainedClosure<E> implements Closure<E>, Serializable {
/** Serial version UID */
private static final long serialVersionUID = -3520677225766901240L;
/** 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.
@ -46,15 +45,15 @@ public class ChainedClosure implements Closure, Serializable {
* @throws IllegalArgumentException if the closures 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);
if (closures.length == 0) {
return NOPClosure.INSTANCE;
return NOPClosure.<E>getInstance();
}
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
* 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 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) {
throw new IllegalArgumentException("Closure collection must not be null");
}
if (closures.size() == 0) {
return NOPClosure.INSTANCE;
return NOPClosure.<E>getInstance();
}
// 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;
for (Iterator it = closures.iterator(); it.hasNext();) {
cmds[i++] = (Closure) it.next();
for (Closure<? super E> closure : closures) {
cmds[i++] = (Closure<E>) closure;
}
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
* @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) {
throw new IllegalArgumentException("Closures must not be null");
}
Closure[] closures = new Closure[] { closure1, closure2 };
return new ChainedClosure(closures);
Closure<E>[] closures = new Closure[] { closure1, closure2 };
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
*/
public ChainedClosure(Closure[] closures) {
public ChainedClosure(Closure<? super E>[] closures) {
super();
iClosures = closures;
}
@ -114,7 +115,7 @@ public class ChainedClosure implements Closure, Serializable {
*
* @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++) {
iClosures[i].execute(input);
}
@ -125,7 +126,7 @@ public class ChainedClosure implements Closure, Serializable {
* @return the closures
* @since Commons Collections 3.1
*/
public Closure[] getClosures() {
public Closure<? super E>[] getClosures() {
return iClosures;
}

View File

@ -18,7 +18,6 @@ package org.apache.commons.collections.functors;
import java.io.Serializable;
import java.util.Collection;
import java.util.Iterator;
import org.apache.commons.collections.Transformer;
@ -33,13 +32,13 @@ import org.apache.commons.collections.Transformer;
*
* @author Stephen Colebourne
*/
public class ChainedTransformer implements Transformer, Serializable {
public class ChainedTransformer<T> implements Transformer<T, T>, Serializable {
/** Serial version UID */
private static final long serialVersionUID = 3514945074733160196L;
/** 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.
@ -49,13 +48,13 @@ public class ChainedTransformer implements Transformer, Serializable {
* @throws IllegalArgumentException if the transformers 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);
if (transformers.length == 0) {
return NOPTransformer.INSTANCE;
return NOPTransformer.<T>getInstance();
}
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 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) {
throw new IllegalArgumentException("Transformer collection must not be null");
}
if (transformers.size() == 0) {
return NOPTransformer.INSTANCE;
return NOPTransformer.<T>getInstance();
}
// convert to array like this to guarantee iterator() ordering
Transformer[] cmds = new Transformer[transformers.size()];
int i = 0;
for (Iterator it = transformers.iterator(); it.hasNext();) {
cmds[i++] = (Transformer) it.next();
}
Transformer<T, T>[] cmds = transformers.toArray(new Transformer[transformers.size()]);
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
* @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) {
throw new IllegalArgumentException("Transformers must not be null");
}
Transformer[] transformers = new Transformer[] { transformer1, transformer2 };
return new ChainedTransformer(transformers);
Transformer<? super T, ? extends T>[] transformers = new Transformer[] { transformer1, transformer2 };
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
*/
public ChainedTransformer(Transformer[] transformers) {
public ChainedTransformer(Transformer<? super T, ? extends T>[] transformers) {
super();
iTransformers = transformers;
}
@ -118,7 +115,7 @@ public class ChainedTransformer implements Transformer, Serializable {
* @param object the input object passed to the first transformer
* @return the transformed result
*/
public Object transform(Object object) {
public T transform(T object) {
for (int i = 0; i < iTransformers.length; i++) {
object = iTransformers[i].transform(object);
}
@ -130,7 +127,7 @@ public class ChainedTransformer implements Transformer, Serializable {
* @return the transformers
* @since Commons Collections 3.1
*/
public Transformer[] getTransformers() {
public Transformer<? super T, ? extends T>[] getTransformers() {
return iTransformers;
}

View File

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

View File

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

View File

@ -32,16 +32,16 @@ import org.apache.commons.collections.Factory;
*
* @author Stephen Colebourne
*/
public class ConstantFactory implements Factory, Serializable {
public class ConstantFactory<T> implements Factory<T>, Serializable {
/** Serial version UID */
private static final long serialVersionUID = -3520677225766901240L;
/** 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 */
private final Object iConstant;
private final T iConstant;
/**
* 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
* @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) {
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
*/
public ConstantFactory(Object constantToReturn) {
public ConstantFactory(T constantToReturn) {
super();
iConstant = constantToReturn;
}
@ -72,7 +73,7 @@ public class ConstantFactory implements Factory, Serializable {
*
* @return the stored constant value
*/
public Object create() {
public T create() {
return iConstant;
}
@ -82,7 +83,7 @@ public class ConstantFactory implements Factory, Serializable {
* @return the constant
* @since Commons Collections 3.1
*/
public Object getConstant() {
public T getConstant() {
return iConstant;
}

View File

@ -32,16 +32,27 @@ import org.apache.commons.collections.Transformer;
*
* @author Stephen Colebourne
*/
public class ConstantTransformer implements Transformer, Serializable {
public class ConstantTransformer<I, O> implements Transformer<I, O>, Serializable {
/** Serial version UID */
private static final long serialVersionUID = 6374440726369055124L;
/** 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 */
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.
@ -49,11 +60,11 @@ public class ConstantTransformer implements Transformer, Serializable {
* @param constantToReturn the constant object to return each time in the 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) {
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
*/
public ConstantTransformer(Object constantToReturn) {
public ConstantTransformer(O constantToReturn) {
super();
iConstant = constantToReturn;
}
@ -73,7 +84,7 @@ public class ConstantTransformer implements Transformer, Serializable {
* @param input the input object which is ignored
* @return the stored constant
*/
public Object transform(Object input) {
public O transform(I input) {
return iConstant;
}
@ -83,8 +94,34 @@ public class ConstantTransformer implements Transformer, Serializable {
* @return the constant
* @since Commons Collections 3.1
*/
public Object getConstant() {
public O getConstant() {
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
*/
public final class ExceptionClosure implements Closure, Serializable {
public final class ExceptionClosure<E> implements Closure<E>, Serializable {
/** Serial version UID */
private static final long serialVersionUID = 7179106032121985545L;
/** Singleton predicate instance */
public static final Closure INSTANCE = new ExceptionClosure();
public static final Closure<Object> INSTANCE = new ExceptionClosure<Object>();
/**
* Factory returning the singleton instance.
@ -44,8 +43,9 @@ public final class ExceptionClosure implements Closure, Serializable {
* @return the singleton instance
* @since Commons Collections 3.1
*/
public static Closure getInstance() {
return INSTANCE;
@SuppressWarnings("unchecked")
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
* @throws FunctorException always
*/
public void execute(Object input) {
public void execute(E input) {
throw new FunctorException("ExceptionClosure invoked");
}

View File

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

View File

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

View File

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

View File

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

View File

@ -28,22 +28,34 @@ import org.apache.commons.collections.Predicate;
*
* @author Stephen Colebourne
*/
public final class FalsePredicate implements Predicate, Serializable {
public final class FalsePredicate<T> implements Predicate<T>, Serializable {
/** Serial version UID */
private static final long serialVersionUID = 7533784454832764388L;
/** 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
* @since Commons Collections 3.1
* @deprecated use {@link #falsePredicate()} instead.
*/
public static Predicate getInstance() {
return INSTANCE;
public static <T> Predicate<T> getInstance() {
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.
*
*
* @param object the input object
* @return false always
*/
public boolean evaluate(Object object) {
public boolean evaluate(T object) {
return false;
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -28,13 +28,13 @@ import org.apache.commons.collections.Predicate;
*
* @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 */
private static final long serialVersionUID = -2654603322338049674L;
/** The predicate to decorate */
private final Predicate iPredicate;
private final Predicate<? super T> iPredicate;
/**
* Factory to create the not predicate.
@ -43,11 +43,11 @@ public final class NotPredicate implements Predicate, PredicateDecorator, Serial
* @return the predicate
* @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) {
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
*/
public NotPredicate(Predicate predicate) {
public NotPredicate(Predicate<? super T> predicate) {
super();
iPredicate = predicate;
}
@ -67,7 +67,7 @@ public final class NotPredicate implements Predicate, PredicateDecorator, Serial
* @param object the input object
* @return true if predicate returns false
*/
public boolean evaluate(Object object) {
public boolean evaluate(T 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
* @since Commons Collections 3.1
*/
public Predicate[] getPredicates() {
@SuppressWarnings("unchecked")
public Predicate<? super T>[] getPredicates() {
return new Predicate[] {iPredicate};
}

View File

@ -29,13 +29,13 @@ import org.apache.commons.collections.Predicate;
*
* @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 */
private static final long serialVersionUID = 3243449850504576071L;
/** The predicate to decorate */
private final Predicate iPredicate;
private final Predicate<? super T> iPredicate;
/**
* Factory to create the null exception predicate.
@ -44,11 +44,11 @@ public final class NullIsExceptionPredicate implements Predicate, PredicateDecor
* @return the predicate
* @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) {
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
*/
public NullIsExceptionPredicate(Predicate predicate) {
public NullIsExceptionPredicate(Predicate<? super T> predicate) {
super();
iPredicate = predicate;
}
@ -70,7 +70,7 @@ public final class NullIsExceptionPredicate implements Predicate, PredicateDecor
* @return true if decorated predicate returns true
* @throws FunctorException if input is null
*/
public boolean evaluate(Object object) {
public boolean evaluate(T object) {
if (object == 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
* @since Commons Collections 3.1
*/
public Predicate[] getPredicates() {
return new Predicate[] {iPredicate};
@SuppressWarnings("unchecked")
public Predicate<? super T>[] getPredicates() {
return new Predicate[] { iPredicate };
}
}

View File

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

View File

@ -28,13 +28,13 @@ import org.apache.commons.collections.Predicate;
*
* @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 */
private static final long serialVersionUID = -7625133768987126273L;
/** The predicate to decorate */
private final Predicate iPredicate;
private final Predicate<? super T> iPredicate;
/**
* Factory to create the null true predicate.
@ -43,11 +43,11 @@ public final class NullIsTruePredicate implements Predicate, PredicateDecorator,
* @return the predicate
* @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) {
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
*/
public NullIsTruePredicate(Predicate predicate) {
public NullIsTruePredicate(Predicate<? super T> predicate) {
super();
iPredicate = predicate;
}
@ -68,7 +68,7 @@ public final class NullIsTruePredicate implements Predicate, PredicateDecorator,
* @param object the input object
* @return true if decorated predicate returns true or input is null
*/
public boolean evaluate(Object object) {
public boolean evaluate(T object) {
if (object == null) {
return true;
}
@ -81,8 +81,9 @@ public final class NullIsTruePredicate implements Predicate, PredicateDecorator,
* @return the predicate as the only element in an array
* @since Commons Collections 3.1
*/
public Predicate[] getPredicates() {
return new Predicate[] {iPredicate};
@SuppressWarnings("unchecked")
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 Matt Benson
*/
public final class OnePredicate implements Predicate, PredicateDecorator, Serializable {
public final class OnePredicate<T> implements Predicate<T>, PredicateDecorator<T>, Serializable {
/** Serial version UID */
private static final long serialVersionUID = -8125389089924745785L;
/** The array of predicates to call */
private final Predicate[] iPredicates;
private final Predicate<? super T>[] iPredicates;
/**
* 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 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);
if (predicates.length == 0) {
return FalsePredicate.INSTANCE;
return FalsePredicate.<T>falsePredicate();
}
if (predicates.length == 1) {
return predicates[0];
return (Predicate<T>) predicates[0];
}
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 any predicate in the array is null
*/
public static Predicate getInstance(Collection predicates) {
Predicate[] preds = FunctorUtils.validate(predicates);
return new OnePredicate(preds);
public static <T> Predicate<T> getInstance(Collection<? extends Predicate<T>> predicates) {
Predicate<? super T>[] preds = FunctorUtils.validate(predicates);
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
*/
public OnePredicate(Predicate[] predicates) {
public OnePredicate(Predicate<? super T>[] predicates) {
super();
iPredicates = predicates;
}
@ -97,7 +98,7 @@ public final class OnePredicate implements Predicate, PredicateDecorator, Serial
* @param object the input object
* @return true if only one decorated predicate returns true
*/
public boolean evaluate(Object object) {
public boolean evaluate(T object) {
boolean match = false;
for (int i = 0; i < iPredicates.length; i++) {
if (iPredicates[i].evaluate(object)) {
@ -116,7 +117,7 @@ public final class OnePredicate implements Predicate, PredicateDecorator, Serial
* @return the predicates
* @since Commons Collections 3.1
*/
public Predicate[] getPredicates() {
public Predicate<? super T>[] getPredicates() {
return iPredicates;
}

View File

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

View File

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

View File

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

View File

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

View File

@ -17,7 +17,6 @@
package org.apache.commons.collections.functors;
import java.io.Serializable;
import java.util.Iterator;
import java.util.Map;
import org.apache.commons.collections.Closure;
@ -32,21 +31,21 @@ import org.apache.commons.collections.Predicate;
*
* @author Stephen Colebourne
*/
public class SwitchClosure implements Closure, Serializable {
public class SwitchClosure<E> implements Closure<E>, Serializable {
/** Serial version UID */
private static final long serialVersionUID = 3518477308466486130L;
/** The tests to consider */
private final Predicate[] iPredicates;
private final Predicate<? super E>[] iPredicates;
/** The matching closures to call */
private final Closure[] iClosures;
private final Closure<? super E>[] iClosures;
/** 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.
*
*
* @param predicates array of predicates, cloned, no nulls
* @param closures matching array of closures, cloned, no nulls
* @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 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(closures);
if (predicates.length != closures.length) {
throw new IllegalArgumentException("The predicate and closure arrays must be the same size");
}
if (predicates.length == 0) {
return (defaultClosure == null ? NOPClosure.INSTANCE : defaultClosure);
return (Closure<E>) (defaultClosure == null ? NOPClosure.<E>getInstance(): defaultClosure);
}
predicates = FunctorUtils.copy(predicates);
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
* on the predicates.
* Create a new Closure that calls one of the closures depending
* on the predicates.
* <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
* 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
* null key. The ordering is that of the iterator() method on the entryset
* 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
* collection of the map.
*
*
* @param predicatesAndClosures a map of predicates to closures
* @return the <code>switch</code> closure
* @throws IllegalArgumentException if 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
*/
public static Closure getInstance(Map predicatesAndClosures) {
Closure[] closures = null;
Predicate[] preds = null;
@SuppressWarnings("unchecked")
public static <E> Closure<E> getInstance(Map<Predicate<E>, Closure<E>> predicatesAndClosures) {
if (predicatesAndClosures == 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
Closure defaultClosure = (Closure) predicatesAndClosures.remove(null);
Closure<? super E> defaultClosure = predicatesAndClosures.remove(null);
int size = predicatesAndClosures.size();
if (size == 0) {
return (defaultClosure == null ? NOPClosure.INSTANCE : defaultClosure);
return (Closure<E>) (defaultClosure == null ? NOPClosure.<E>getInstance() : defaultClosure);
}
closures = new Closure[size];
preds = new Predicate[size];
Closure<E>[] closures = new Closure[size];
Predicate<E>[] preds = new Predicate[size];
int i = 0;
for (Iterator it = predicatesAndClosures.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
preds[i] = (Predicate) entry.getKey();
closures[i] = (Closure) entry.getValue();
for (Map.Entry<Predicate<E>, Closure<E>> entry : predicatesAndClosures.entrySet()) {
preds[i] = entry.getKey();
closures[i] = entry.getValue();
i++;
}
return new SwitchClosure(preds, closures, defaultClosure);
return new SwitchClosure<E>(preds, closures, defaultClosure);
}
/**
* Constructor that performs no validation.
* Use <code>getInstance</code> if you want that.
*
*
* @param predicates array of predicates, 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
*/
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();
iPredicates = predicates;
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
*
*
* @param input the input object
*/
public void execute(Object input) {
public void execute(E input) {
for (int i = 0; i < iPredicates.length; i++) {
if (iPredicates[i].evaluate(input) == true) {
iClosures[i].execute(input);
@ -144,32 +140,32 @@ public class SwitchClosure implements Closure, Serializable {
/**
* Gets the predicates, do not modify the array.
*
*
* @return the predicates
* @since Commons Collections 3.1
*/
public Predicate[] getPredicates() {
public Predicate<? super E>[] getPredicates() {
return iPredicates;
}
/**
* Gets the closures, do not modify the array.
*
*
* @return the closures
* @since Commons Collections 3.1
*/
public Closure[] getClosures() {
public Closure<? super E>[] getClosures() {
return iClosures;
}
/**
* Gets the default closure.
*
*
* @return the default closure
* @since Commons Collections 3.1
*/
public Closure getDefaultClosure() {
public Closure<? super E> getDefaultClosure() {
return iDefault;
}
}

View File

@ -17,7 +17,6 @@
package org.apache.commons.collections.functors;
import java.io.Serializable;
import java.util.Iterator;
import java.util.Map;
import org.apache.commons.collections.Predicate;
@ -32,17 +31,17 @@ import org.apache.commons.collections.Transformer;
*
* @author Stephen Colebourne
*/
public class SwitchTransformer implements Transformer, Serializable {
public class SwitchTransformer<I, O> implements Transformer<I, O>, Serializable {
/** Serial version UID */
private static final long serialVersionUID = -6404460890903469332L;
/** The tests to consider */
private final Predicate[] iPredicates;
private final Predicate<? super I>[] iPredicates;
/** 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 */
private final Transformer iDefault;
private final Transformer<? super I, ? extends O> iDefault;
/**
* 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 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(transformers);
if (predicates.length != transformers.length) {
throw new IllegalArgumentException("The predicate and transformer arrays must be the same size");
}
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);
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 ClassCastException if the map elements are of the wrong type
*/
public static Transformer getInstance(Map predicatesAndTransformers) {
Transformer[] transformers = null;
Predicate[] preds = null;
@SuppressWarnings("unchecked")
public static <I, O> Transformer<I, O> getInstance(
Map<? extends Predicate<? super I>, ? extends Transformer<? super I, ? extends O>> predicatesAndTransformers) {
if (predicatesAndTransformers == null) {
throw new IllegalArgumentException("The predicate and transformer map must not be null");
}
if (predicatesAndTransformers.size() == 0) {
return ConstantTransformer.NULL_INSTANCE;
return ConstantTransformer.<I, O>getNullInstance();
}
// 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();
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];
preds = new Predicate[size];
Transformer<? super I, ? extends O>[] transformers = new Transformer[size];
Predicate<? super I>[] preds = new Predicate[size];
int i = 0;
for (Iterator it = predicatesAndTransformers.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
preds[i] = (Predicate) entry.getKey();
transformers[i] = (Transformer) entry.getValue();
for (Map.Entry<? extends Predicate<? super I>, ? extends Transformer<? super I, ? extends O>> entry : predicatesAndTransformers.entrySet()) {
preds[i] = entry.getKey();
transformers[i] = entry.getValue();
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 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();
iPredicates = predicates;
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
* @return the transformed result
*/
public Object transform(Object input) {
public O transform(I input) {
for (int i = 0; i < iPredicates.length; i++) {
if (iPredicates[i].evaluate(input) == true) {
return iTransformers[i].transform(input);
@ -149,7 +153,7 @@ public class SwitchTransformer implements Transformer, Serializable {
* @return the predicates
* @since Commons Collections 3.1
*/
public Predicate[] getPredicates() {
public Predicate<? super I>[] getPredicates() {
return iPredicates;
}
@ -159,7 +163,7 @@ public class SwitchTransformer implements Transformer, Serializable {
* @return the transformers
* @since Commons Collections 3.1
*/
public Transformer[] getTransformers() {
public Transformer<? super I, ? extends O>[] getTransformers() {
return iTransformers;
}
@ -169,7 +173,7 @@ public class SwitchTransformer implements Transformer, Serializable {
* @return the default transformer
* @since Commons Collections 3.1
*/
public Transformer getDefaultTransformer() {
public Transformer<? super I, ? extends O> getDefaultTransformer() {
return iDefault;
}

View File

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

View File

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

View File

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

View File

@ -31,22 +31,22 @@ import org.apache.commons.collections.Predicate;
*
* @author Stephen Colebourne
*/
public final class UniquePredicate implements Predicate, Serializable {
public final class UniquePredicate<T> implements Predicate<T>, Serializable {
/** Serial version UID */
private static final long serialVersionUID = -3319417438027438040L;
/** 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.
*
*
* @return the predicate
* @throws IllegalArgumentException if the predicate is null
*/
public static Predicate getInstance() {
return new UniquePredicate();
public static <E> Predicate<E> getInstance() {
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
* received yet.
*
*
* @param object the input object
* @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);
}

View File

@ -30,15 +30,15 @@ import org.apache.commons.collections.Predicate;
*
* @author Stephen Colebourne
*/
public class WhileClosure implements Closure, Serializable {
public class WhileClosure<E> implements Closure<E>, Serializable {
/** Serial version UID */
private static final long serialVersionUID = -3110538116913760108L;
/** The test condition */
private final Predicate iPredicate;
private final Predicate<? super E> iPredicate;
/** 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 */
private final boolean iDoLoop;
@ -51,14 +51,14 @@ public class WhileClosure implements Closure, Serializable {
* @return the <code>while</code> closure
* @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) {
throw new IllegalArgumentException("Predicate must not be null");
}
if (closure == 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 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();
iPredicate = predicate;
iClosure = closure;
@ -81,7 +81,7 @@ public class WhileClosure implements Closure, Serializable {
*
* @param input the input object
*/
public void execute(Object input) {
public void execute(E input) {
if (iDoLoop) {
iClosure.execute(input);
}
@ -96,7 +96,7 @@ public class WhileClosure implements Closure, Serializable {
* @return the predicate
* @since Commons Collections 3.1
*/
public Predicate getPredicate() {
public Predicate<? super E> getPredicate() {
return iPredicate;
}
@ -106,7 +106,7 @@ public class WhileClosure implements Closure, Serializable {
* @return the closure
* @since Commons Collections 3.1
*/
public Closure getClosure() {
public Closure<? super E> getClosure() {
return iClosure;
}

View File

@ -26,7 +26,7 @@ import java.util.NoSuchElementException;
*
* @author Stephen Colebourne
*/
abstract class AbstractEmptyIterator {
abstract class AbstractEmptyIterator<E> {
/**
* Constructor.
@ -39,7 +39,7 @@ abstract class AbstractEmptyIterator {
return false;
}
public Object next() {
public E next() {
throw new NoSuchElementException("Iterator contains no elements");
}
@ -47,7 +47,7 @@ abstract class AbstractEmptyIterator {
return false;
}
public Object previous() {
public E previous() {
throw new NoSuchElementException("Iterator contains no elements");
}
@ -59,11 +59,11 @@ abstract class AbstractEmptyIterator {
return -1;
}
public void add(Object obj) {
public void add(E obj) {
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");
}
@ -71,18 +71,6 @@ abstract class AbstractEmptyIterator {
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() {
// do nothing
}

View File

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

View File

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

View File

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

View File

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

View File

@ -32,18 +32,39 @@ import org.apache.commons.collections.ResettableIterator;
*
* @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.
* @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.
* @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.

View File

@ -20,30 +20,52 @@ import java.util.ListIterator;
import org.apache.commons.collections.ResettableListIterator;
/**
/**
* Provides an implementation of an empty list iterator.
* <p>
* This class provides an implementation of an empty list iterator.
* This class provides for binary compatability between Commons Collections
* 2.1.1 and 3.1 due to issues with <code>IteratorUtils</code>.
* This class provides an implementation of an empty list iterator. This class
* provides for binary compatability between Commons Collections 2.1.1 and 3.1
* due to issues with <code>IteratorUtils</code>.
*
* @since Commons Collections 2.1.1 and 3.1
* @version $Revision$ $Date$
*
* @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.
* @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.
* @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.

View File

@ -27,13 +27,25 @@ import org.apache.commons.collections.ResettableIterator;
*
* @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.
* @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.

View File

@ -27,13 +27,23 @@ import org.apache.commons.collections.ResettableIterator;
*
* @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.
* @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.

View File

@ -27,13 +27,25 @@ import org.apache.commons.collections.ResettableIterator;
*
* @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.
* @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.

View File

@ -39,11 +39,11 @@ import org.apache.commons.collections.ResettableIterator;
*
* @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 Iterator iterator;
private Map.Entry last;
private final Map<K, V> map;
private Iterator<Map.Entry<K, V>> iterator;
private Map.Entry<K, V> last;
private boolean canRemove = false;
/**
@ -51,7 +51,7 @@ public class EntrySetMapIterator implements MapIterator, ResettableIterator {
*
* @param map the map to iterate over
*/
public EntrySetMapIterator(Map map) {
public EntrySetMapIterator(Map<K, V> map) {
super();
this.map = map;
this.iterator = map.entrySet().iterator();
@ -73,8 +73,8 @@ public class EntrySetMapIterator implements MapIterator, ResettableIterator {
* @return the next key in the iteration
* @throws java.util.NoSuchElementException if the iteration is finished
*/
public Object next() {
last = (Map.Entry) iterator.next();
public K next() {
last = (Map.Entry<K, V>) iterator.next();
canRemove = true;
return last.getKey();
}
@ -107,7 +107,7 @@ public class EntrySetMapIterator implements MapIterator, ResettableIterator {
* @return the current key
* @throws IllegalStateException if <code>next()</code> has not yet been called
*/
public Object getKey() {
public K getKey() {
if (last == null) {
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
* @throws IllegalStateException if <code>next()</code> has not yet been called
*/
public Object getValue() {
public V getValue() {
if (last == null) {
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
* last call to <code>next()</code>
*/
public Object setValue(Object value) {
public V setValue(V value) {
if (last == null) {
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() {
if (last != null) {
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:dlr@finemaltcoding.com">Daniel Rall</a>
*/
public class EnumerationIterator implements Iterator {
public class EnumerationIterator<E> implements Iterator<E> {
/** The collection to remove elements from */
private Collection collection;
private Collection<? super E> collection;
/** The enumeration being converted */
private Enumeration enumeration;
private Enumeration<? extends E> enumeration;
/** The last object retrieved */
private Object last;
private E last;
// Constructors
//-----------------------------------------------------------------------
@ -55,7 +55,7 @@ public class EnumerationIterator implements Iterator {
*
* @param enumeration the enumeration to use
*/
public EnumerationIterator(final Enumeration enumeration) {
public EnumerationIterator(final Enumeration<? extends E> enumeration) {
this(enumeration, null);
}
@ -64,9 +64,9 @@ public class EnumerationIterator implements Iterator {
* elements from the specified collection.
*
* @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();
this.enumeration = enumeration;
this.collection = collection;
@ -91,7 +91,7 @@ public class EnumerationIterator implements Iterator {
* @return the next object from the enumeration
* @throws NullPointerException if the enumeration is null
*/
public Object next() {
public E next() {
last = enumeration.nextElement();
return last;
}
@ -125,7 +125,7 @@ public class EnumerationIterator implements Iterator {
*
* @return the underlying enumeration
*/
public Enumeration getEnumeration() {
public Enumeration<? extends E> getEnumeration() {
return enumeration;
}
@ -134,7 +134,7 @@ public class EnumerationIterator implements Iterator {
*
* @param enumeration the new underlying enumeration
*/
public void setEnumeration(final Enumeration enumeration) {
public void setEnumeration(final Enumeration<? extends E> enumeration) {
this.enumeration = enumeration;
}

View File

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

View File

@ -32,19 +32,19 @@ import org.apache.commons.collections.Predicate;
*
* @author Rodney Waldhoff
*/
public class FilterListIterator implements ListIterator {
public class FilterListIterator<E> implements ListIterator<E> {
/** The iterator being used */
private ListIterator iterator;
private ListIterator<? extends E> iterator;
/** The predicate being used */
private Predicate predicate;
private Predicate<? super E> predicate;
/**
* The value of the next (matching) object, when
* {@link #nextObjectSet} is true.
*/
private Object nextObject;
private E nextObject;
/**
* 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
* {@link #previousObjectSet} is true.
*/
private Object previousObject;
private E previousObject;
/**
* Whether or not the {@link #previousObject} has been set
@ -85,7 +85,7 @@ public class FilterListIterator implements ListIterator {
*
* @param iterator the iterator to use
*/
public FilterListIterator(ListIterator iterator ) {
public FilterListIterator(ListIterator<? extends E> iterator ) {
super();
this.iterator = iterator;
}
@ -96,7 +96,7 @@ public class FilterListIterator implements ListIterator {
* @param iterator the iterator 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();
this.iterator = iterator;
this.predicate = predicate;
@ -108,41 +108,33 @@ public class FilterListIterator implements ListIterator {
*
* @param predicate the predicate to use.
*/
public FilterListIterator(Predicate predicate) {
public FilterListIterator(Predicate<? super E> predicate) {
super();
this.predicate = predicate;
}
//-----------------------------------------------------------------------
/** Not supported. */
public void add(Object o) {
public void add(E o) {
throw new UnsupportedOperationException("FilterListIterator.add(Object) is not supported.");
}
public boolean hasNext() {
if(nextObjectSet) {
return true;
} else {
return setNextObject();
}
return nextObjectSet || setNextObject();
}
public boolean hasPrevious() {
if(previousObjectSet) {
return true;
} else {
return setPreviousObject();
}
return previousObjectSet || setPreviousObject();
}
public Object next() {
if(!nextObjectSet) {
if(!setNextObject()) {
public E next() {
if (!nextObjectSet) {
if (!setNextObject()) {
throw new NoSuchElementException();
}
}
nextIndex++;
Object temp = nextObject;
E temp = nextObject;
clearNextObject();
return temp;
}
@ -151,14 +143,14 @@ public class FilterListIterator implements ListIterator {
return nextIndex;
}
public Object previous() {
if(!previousObjectSet) {
if(!setPreviousObject()) {
public E previous() {
if (!previousObjectSet) {
if (!setPreviousObject()) {
throw new NoSuchElementException();
}
}
nextIndex--;
Object temp = previousObject;
E temp = previousObject;
clearPreviousObject();
return temp;
}
@ -173,7 +165,7 @@ public class FilterListIterator implements ListIterator {
}
/** Not supported. */
public void set(Object o) {
public void set(E o) {
throw new UnsupportedOperationException("FilterListIterator.set(Object) is not supported.");
}
@ -183,7 +175,7 @@ public class FilterListIterator implements ListIterator {
*
* @return the iterator.
*/
public ListIterator getListIterator() {
public ListIterator<? extends E> getListIterator() {
return iterator;
}
@ -193,7 +185,7 @@ public class FilterListIterator implements ListIterator {
*
* @param iterator the iterator to use
*/
public void setListIterator(ListIterator iterator) {
public void setListIterator(ListIterator<? extends E> iterator) {
this.iterator = iterator;
}
@ -203,7 +195,7 @@ public class FilterListIterator implements ListIterator {
*
* @return the predicate.
*/
public Predicate getPredicate() {
public Predicate<? super E> getPredicate() {
return predicate;
}
@ -212,7 +204,7 @@ public class FilterListIterator implements ListIterator {
*
* @param predicate the transformer to use
*/
public void setPredicate(Predicate predicate) {
public void setPredicate(Predicate<? super E> predicate) {
this.predicate = predicate;
}
@ -227,18 +219,17 @@ public class FilterListIterator implements ListIterator {
// then we've walked back one step in the
// underlying list (due to a hasPrevious() call)
// so skip ahead one matching object
if(previousObjectSet) {
if (previousObjectSet) {
clearPreviousObject();
if(!setNextObject()) {
if (!setNextObject()) {
return false;
} else {
clearNextObject();
}
clearNextObject();
}
while(iterator.hasNext()) {
Object object = iterator.next();
if(predicate.evaluate(object)) {
while (iterator.hasNext()) {
E object = iterator.next();
if (predicate.evaluate(object)) {
nextObject = object;
nextObjectSet = true;
return true;
@ -257,18 +248,17 @@ public class FilterListIterator implements ListIterator {
// then we've walked back one step in the
// underlying list (due to a hasNext() call)
// so skip ahead one matching object
if(nextObjectSet) {
if (nextObjectSet) {
clearNextObject();
if(!setPreviousObject()) {
if (!setPreviousObject()) {
return false;
} else {
clearPreviousObject();
}
clearPreviousObject();
}
while(iterator.hasPrevious()) {
Object object = iterator.previous();
if(predicate.evaluate(object)) {
while (iterator.hasPrevious()) {
E object = iterator.previous();
if (predicate.evaluate(object)) {
previousObject = object;
previousObjectSet = 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.
* <p>
* This class makes multiple iterators look like one to the caller
* When any method from the Iterator interface is called, the IteratorChain
* will delegate to a single underlying Iterator. The IteratorChain will
* invoke the Iterators in sequence until all Iterators are exhausted.
* This class makes multiple iterators look like one to the caller When any
* method from the Iterator interface is called, the IteratorChain will delegate
* to a single underlying Iterator. The IteratorChain will invoke the Iterators
* in sequence until all Iterators are exhausted.
* <p>
* Under many circumstances, linking Iterators together in this manner is
* more efficient (and convenient) than reading out the contents of each
* Iterator into a List and creating a new Iterator.
* Under many circumstances, linking Iterators together in this manner is more
* efficient (and convenient) than reading out the contents of each Iterator
* into a List and creating a new Iterator.
* <p>
* Calling a method that adds new Iterator<i>after a method in the Iterator
* interface has been called</i> will result in an UnsupportedOperationException.
* Subclasses should <i>take care</i> to not alter the underlying List of Iterators.
* interface has been called</i> will result in an
* UnsupportedOperationException. Subclasses should <i>take care</i> to not
* alter the underlying List of Iterators.
* <p>
* NOTE: As from version 3.0, the IteratorChain may contain no
* iterators. In this case the class will function as an empty iterator.
* NOTE: As from version 3.0, the IteratorChain may contain no iterators. In
* this case the class will function as an empty iterator.
*
* @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 Stephen Colebourne
*/
public class IteratorChain implements Iterator {
public class IteratorChain<E> implements Iterator<E> {
/** 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 */
protected int currentIteratorIndex = 0;
/** The current iterator */
protected Iterator currentIterator = null;
protected Iterator<? extends E> currentIterator = null;
/**
* The "last used" Iterator is the Iterator upon which
* next() or hasNext() was most recently called
* used for the remove() operation only
* The "last used" Iterator is the Iterator upon which next() or hasNext()
* was most recently called used for the remove() operation only
*/
protected Iterator lastUsedIterator = null;
protected Iterator<? extends E> lastUsedIterator = null;
/**
* ComparatorChain is "locked" after the first time
* compare(Object,Object) is called
* ComparatorChain is "locked" after the first time compare(Object,Object)
* is called
*/
protected boolean isLocked = false;
@ -72,8 +77,8 @@ public class IteratorChain implements Iterator {
/**
* Construct an IteratorChain with no Iterators.
* <p>
* You will normally use {@link #addIterator(Iterator)} to add
* some iterators after using this constructor.
* You will normally use {@link #addIterator(Iterator)} to add some
* iterators after using this constructor.
*/
public IteratorChain() {
super();
@ -82,49 +87,47 @@ public class IteratorChain implements Iterator {
/**
* Construct an IteratorChain with a single Iterator.
* <p>
* This method takes one iterator. The newly constructed iterator
* will iterate through that iterator. Thus calling this constructor
* on its own will have no effect other than decorating the input iterator.
* This method takes one iterator. The newly constructed iterator will
* iterate through that iterator. Thus calling this constructor on its own
* will have no effect other than decorating the input iterator.
* <p>
* You will normally use {@link #addIterator(Iterator)} to add
* some more iterators after using this constructor.
*
* @param iterator the first child iterator in the IteratorChain, not null
* You will normally use {@link #addIterator(Iterator)} to add some more
* iterators after using this constructor.
*
* @param iterator the first child iterator in the IteratorChain, not null
* @throws NullPointerException if the iterator is null
*/
public IteratorChain(Iterator iterator) {
public IteratorChain(Iterator<? extends E> iterator) {
super();
addIterator(iterator);
}
/**
* Constructs a new <code>IteratorChain</code> over the two
* given iterators.
* Constructs a new <code>IteratorChain</code> over the two given iterators.
* <p>
* This method takes two iterators. The newly constructed iterator
* will iterate through each one of the input iterators in turn.
*
* @param first the first child iterator in the IteratorChain, not null
* @param second the second child iterator in the IteratorChain, not null
* This method takes two iterators. The newly constructed iterator will
* iterate through each one of the input iterators in turn.
*
* @param first the first 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
*/
public IteratorChain(Iterator first, Iterator second) {
public IteratorChain(Iterator<? extends E> first, Iterator<? extends E> second) {
super();
addIterator(first);
addIterator(second);
}
/**
* Constructs a new <code>IteratorChain</code> over the array
* of iterators.
* Constructs a new <code>IteratorChain</code> over the array of iterators.
* <p>
* This method takes an array of iterators. The newly constructed iterator
* 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
*/
public IteratorChain(Iterator[] iteratorChain) {
public IteratorChain(Iterator<? extends E>[] iteratorChain) {
super();
for (int i = 0; i < iteratorChain.length; i++) {
addIterator(iteratorChain[i]);
@ -132,33 +135,33 @@ public class IteratorChain implements Iterator {
}
/**
* Constructs a new <code>IteratorChain</code> over the collection
* of iterators.
* Constructs a new <code>IteratorChain</code> over the collection of
* iterators.
* <p>
* This method takes a collection of iterators. The newly constructed iterator
* will iterate through each one of the input iterators in turn.
*
* @param iteratorChain the collection of iterators, not null
* This method takes a collection of iterators. The newly constructed
* iterator will iterate through each one of the input iterators in turn.
*
* @param iteratorChain the collection of iterators, not 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();
for (Iterator it = iteratorChain.iterator(); it.hasNext();) {
Iterator item = (Iterator) it.next();
addIterator(item);
for (Iterator<? extends E> iterator : iteratorChain) {
addIterator(iterator);
}
}
//-----------------------------------------------------------------------
/**
* Add an Iterator to the end of the chain
*
*
* @param iterator Iterator to add
* @throws IllegalStateException if I've already started iterating
* @throws NullPointerException if the iterator is null
*/
public void addIterator(Iterator iterator) {
public void addIterator(Iterator<? extends E> iterator) {
checkLocked();
if (iterator == 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
*
* @param index index of the Iterator to replace
* @param iterator Iterator to place at the given index
*
* @param index index of the Iterator to replace
* @param iterator Iterator to place at the given index
* @throws IndexOutOfBoundsException if index &lt; 0 or index &gt; size()
* @throws IllegalStateException if I've already started iterating
* @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();
if (iterator == null) {
throw new NullPointerException("Iterator must not be null");
@ -185,16 +189,16 @@ public class IteratorChain implements Iterator {
/**
* Get the list of Iterators (unmodifiable)
*
*
* @return the unmodifiable list of iterators added
*/
public List getIterators() {
public List<Iterator<? extends E>> getIterators() {
return UnmodifiableList.decorate(iteratorChain);
}
/**
* Number of Iterators in the current IteratorChain.
*
*
* @return Iterator count
*/
public int size() {
@ -203,9 +207,9 @@ public class IteratorChain implements Iterator {
/**
* Determine if modifications can still be made to the IteratorChain.
* IteratorChains cannot be modified once they have executed a method
* from the Iterator interface.
*
* IteratorChains cannot be modified once they have executed a method from
* the Iterator interface.
*
* @return true if IteratorChain cannot be modified, false if it can
*/
public boolean isLocked() {
@ -217,13 +221,14 @@ public class IteratorChain implements Iterator {
*/
private void checkLocked() {
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.
* This must be called from all Iterator interface methods.
* Lock the chain so no more iterators can be added. This must be called
* from all Iterator interface methods.
*/
private void lockChain() {
if (isLocked == false) {
@ -232,31 +237,32 @@ public class IteratorChain implements Iterator {
}
/**
* Updates the current iterator field to ensure that the current Iterator
* is not exhausted
* Updates the current iterator field to ensure that the current Iterator is
* not exhausted
*/
protected void updateCurrentIterator() {
if (currentIterator == null) {
if (iteratorChain.isEmpty()) {
currentIterator = EmptyIterator.INSTANCE;
currentIterator = EmptyIterator.<E> getInstance();
} else {
currentIterator = (Iterator) iteratorChain.get(0);
currentIterator = iteratorChain.get(0);
}
// set last used iterator here, in case the user calls remove
// before calling hasNext() or next() (although they shouldn't)
lastUsedIterator = currentIterator;
}
while (currentIterator.hasNext() == false && currentIteratorIndex < iteratorChain.size() - 1) {
while (currentIterator.hasNext() == false
&& currentIteratorIndex < iteratorChain.size() - 1) {
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 elements remain
*/
public boolean hasNext() {
@ -269,11 +275,12 @@ public class IteratorChain implements Iterator {
/**
* Returns the next Object of 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();
updateCurrentIterator();
lastUsedIterator = currentIterator;
@ -282,18 +289,17 @@ public class IteratorChain implements Iterator {
}
/**
* Removes from the underlying collection the last element
* returned by the Iterator. As with next() and hasNext(),
* this method calls remove() on the underlying Iterator.
* Therefore, this method may throw an
* UnsupportedOperationException if the underlying
* Iterator does not support this method.
*
* @throws UnsupportedOperationException
* if the remove operator is not supported by the underlying Iterator
* @throws IllegalStateException
* if the next method has not yet been called, or the remove method has
* already been called after the last call to the next method.
* Removes from the underlying collection the last element returned by the
* Iterator. As with next() and hasNext(), this method calls remove() on the
* underlying Iterator. Therefore, this method may throw an
* UnsupportedOperationException if the underlying Iterator does not support
* this method.
*
* @throws UnsupportedOperationException if the remove operator is not
* supported by the underlying Iterator
* @throws IllegalStateException if the next method has not yet been called,
* or the remove method has already been called after the last call to the
* next method.
*/
public void remove() {
lockChain();

View File

@ -19,36 +19,35 @@ package org.apache.commons.collections.iterators;
import java.util.Enumeration;
import java.util.Iterator;
/**
* Adapter to make an {@link Iterator Iterator} instance appear to be
* an {@link Enumeration Enumeration} instance.
/**
* Adapter to make an {@link Iterator Iterator} instance appear to be an
* {@link Enumeration Enumeration} instance.
*
* @since Commons Collections 1.0
* @version $Revision$ $Date$
*
* @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. */
private Iterator iterator;
private Iterator<? extends E> iterator;
/**
* Constructs a new <code>IteratorEnumeration</code> that will not
* function until {@link #setIterator(Iterator) setIterator} is
* invoked.
* Constructs a new <code>IteratorEnumeration</code> that will not function
* until {@link #setIterator(Iterator) setIterator} is invoked.
*/
public IteratorEnumeration() {
super();
}
/**
* Constructs a new <code>IteratorEnumeration</code> that will use
* the given iterator.
* Constructs a new <code>IteratorEnumeration</code> that will use the given
* iterator.
*
* @param iterator the iterator to use
* @param iterator the iterator to use
*/
public IteratorEnumeration( Iterator iterator ) {
public IteratorEnumeration(Iterator<? extends E> iterator) {
super();
this.iterator = iterator;
}
@ -57,22 +56,22 @@ public class IteratorEnumeration implements Enumeration {
//-------------------------------------------------------------------------
/**
* Returns true if the underlying iterator has more elements.
*
* @return 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
*/
public boolean hasMoreElements() {
return iterator.hasNext();
}
/**
* Returns 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
* more elements
* Returns 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 more elements
*/
public Object nextElement() {
public E nextElement() {
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;
}
/**
* Sets the underlying iterator.
*
* @param iterator the new underlying iterator
* Sets the underlying iterator.
*
* @param iterator the new underlying iterator
*/
public void setIterator( Iterator iterator ) {
public void setIterator(Iterator<? extends E> 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 Stephen Colebourne
*/
public class LoopingIterator implements ResettableIterator {
public class LoopingIterator<E> implements ResettableIterator<E> {
/** The collection to base the iterator on */
private Collection collection;
private Collection<? extends E> collection;
/** The current iterator */
private Iterator iterator;
private Iterator<? extends E> iterator;
/**
* Constructor that wraps a collection.
@ -54,7 +54,7 @@ public class LoopingIterator implements ResettableIterator {
* @param coll the collection to wrap
* @throws NullPointerException if the collection is null
*/
public LoopingIterator(Collection coll) {
public LoopingIterator(Collection<? extends E> coll) {
if (coll == 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
* at all. Use {@link #hasNext} to avoid this error.
*/
public Object next() {
public E next() {
if (collection.size() == 0) {
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>
*/
public class LoopingListIterator implements ResettableListIterator {
public class LoopingListIterator<E> implements ResettableListIterator<E> {
/** The list to base the iterator on */
private List list;
private List<E> list;
/** The current list iterator */
private ListIterator iterator;
private ListIterator<E> iterator;
/**
* Constructor that wraps a list.
@ -56,7 +56,7 @@ public class LoopingListIterator implements ResettableListIterator {
* @param list the list to wrap
* @throws NullPointerException if the list it null
*/
public LoopingListIterator(List list) {
public LoopingListIterator(List<E> list) {
if (list == 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
* @throws NoSuchElementException if there are no elements in the list
*/
public Object next() {
public E next() {
if (list.isEmpty()) {
throw new NoSuchElementException(
"There are no elements for this iterator to loop on");
@ -113,9 +113,8 @@ public class LoopingListIterator implements ResettableListIterator {
}
if (iterator.hasNext() == false) {
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
* @throws NoSuchElementException if there are no elements in the list
*/
public Object previous() {
public E previous() {
if (list.isEmpty()) {
throw new NoSuchElementException(
"There are no elements for this iterator to loop on");
}
if (iterator.hasPrevious() == false) {
Object result = null;
E result = null;
while (iterator.hasNext()) {
result = iterator.next();
}
iterator.previous();
return result;
} else {
return iterator.previous();
}
return iterator.previous();
}
/**
@ -174,9 +172,8 @@ public class LoopingListIterator implements ResettableListIterator {
}
if (iterator.hasPrevious() == false) {
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
* supported by the iterator implementation of the underlying list
*/
public void add(Object obj) {
public void add(E obj) {
iterator.add(obj);
}
@ -232,7 +229,7 @@ public class LoopingListIterator implements ResettableListIterator {
* @throws UnsupportedOperationException if the set method is not
* supported by the iterator implementation of the underlying list
*/
public void set(Object obj) {
public void set(E obj) {
iterator.set(obj);
}

View File

@ -40,11 +40,11 @@ import org.apache.commons.collections.ResettableIterator;
* @author Stephen Colebourne
* @author Phil Steitz
*/
public class ObjectArrayIterator
implements Iterator, ResettableIterator {
public class ObjectArrayIterator<E>
implements Iterator<E>, ResettableIterator<E> {
/** The array */
protected Object[] array = null;
protected E[] array = null;
/** The start index to loop from */
protected int startIndex = 0;
/** The end index to loop to */
@ -69,7 +69,7 @@ public class ObjectArrayIterator
* @param array the array to iterate over
* @throws NullPointerException if <code>array</code> is <code>null</code>
*/
public ObjectArrayIterator(Object[] array) {
public ObjectArrayIterator(E[] array) {
this(array, 0, array.length);
}
@ -82,7 +82,7 @@ public class ObjectArrayIterator
* @throws NullPointerException if <code>array</code> is <code>null</code>
* @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);
}
@ -97,7 +97,7 @@ public class ObjectArrayIterator
* @throws IllegalArgumentException if end index is before the start
* @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();
if (start < 0) {
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
* have already been returned
*/
public Object next() {
public E next() {
if (hasNext() == false) {
throw new NoSuchElementException();
}
@ -162,7 +162,7 @@ public class ObjectArrayIterator
* the no-arg constructor was used and {@link #setArray} has never
* been called with a valid array.
*/
public Object[] getArray() {
public E[] getArray() {
return this.array;
}
@ -178,7 +178,7 @@ public class ObjectArrayIterator
* @throws IllegalStateException if the <code>array</code> was set in the constructor
* @throws NullPointerException if <code>array</code> is <code>null</code>
*/
public void setArray(Object[] array) {
public void setArray(E[] array) {
if (this.array != null) {
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
* @version $Revision: $ $Date$
*/
public class ReverseListIterator implements ResettableListIterator {
public class ReverseListIterator<E> implements ResettableListIterator<E> {
/** The list being wrapped. */
private final List list;
private final List<E> list;
/** The list iterator being wrapped. */
private ListIterator iterator;
private ListIterator<E> iterator;
/** Flag to indicate if updating is possible at the moment. */
private boolean validForUpdate = true;
@ -53,7 +53,7 @@ public class ReverseListIterator implements ResettableListIterator {
* @param list the list to create a reversed iterator for
* @throws NullPointerException if the list is null
*/
public ReverseListIterator(List list) {
public ReverseListIterator(List<E> list) {
super();
this.list = list;
iterator = list.listIterator(list.size());
@ -75,8 +75,8 @@ public class ReverseListIterator implements ResettableListIterator {
*
* @return the next element in the iterator
*/
public Object next() {
Object obj = iterator.previous();
public E next() {
E obj = iterator.previous();
validForUpdate = true;
return obj;
}
@ -105,8 +105,8 @@ public class ReverseListIterator implements ResettableListIterator {
*
* @return the previous element in the iterator
*/
public Object previous() {
Object obj = iterator.next();
public E previous() {
E obj = iterator.next();
validForUpdate = true;
return obj;
}
@ -140,7 +140,7 @@ public class ReverseListIterator implements ResettableListIterator {
* @throws UnsupportedOperationException if the list is unmodifiable
* @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) {
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 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()
// method call re-enables remove and add
if (validForUpdate == false) {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

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