finish generics (minus one class)

git-svn-id: https://svn.apache.org/repos/asf/commons/proper/collections/branches/collections_jdk5_branch@738956 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Matthew Jason Benson 2009-01-29 18:48:37 +00:00
parent b1311a218c
commit 884baf0ddc
369 changed files with 15699 additions and 14685 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

@ -28,11 +28,12 @@ import org.apache.commons.collections.bag.UnmodifiableBag;
import org.apache.commons.collections.bag.UnmodifiableSortedBag;
/**
* Provides utility methods and decorators for
* {@link Bag} and {@link SortedBag} instances.
*
* Provides utility methods and decorators for {@link Bag} and {@link SortedBag}
* instances.
*
* @since Commons Collections 2.1
* @version $Revision$ $Date$
* @version $Revision$ $Date: 2007-07-13 05:39:24 -0500 (Fri, 13 Jul
* 2007) $
*
* @author Paul Jack
* @author Stephen Colebourne
@ -44,29 +45,29 @@ public class BagUtils {
/**
* An empty unmodifiable bag.
*/
public static final Bag EMPTY_BAG = UnmodifiableBag.decorate(new HashBag());
public static final Bag<Object> EMPTY_BAG = UnmodifiableBag.decorate(new HashBag<Object>());
/**
* An empty unmodifiable sorted bag.
*/
public static final Bag EMPTY_SORTED_BAG = UnmodifiableSortedBag.decorate(new TreeBag());
public static final Bag<Object> EMPTY_SORTED_BAG = UnmodifiableSortedBag.decorate(new TreeBag<Object>());
/**
* Instantiation of BagUtils is not intended or required.
* However, some tools require an instance to operate.
* Instantiation of BagUtils is not intended or required. However, some
* tools require an instance to operate.
*/
public BagUtils() {
}
//-----------------------------------------------------------------------
/**
* Returns a synchronized (thread-safe) bag backed by the given bag.
* In order to guarantee serial access, it is critical that all
* access to the backing bag is accomplished through the returned bag.
* Returns a synchronized (thread-safe) bag backed by the given bag. In
* order to guarantee serial access, it is critical that all access to the
* backing bag is accomplished through the returned bag.
* <p>
* It is imperative that the user manually synchronize on the returned
* bag when iterating over it:
*
* It is imperative that the user manually synchronize on the returned bag
* when iterating over it:
*
* <pre>
* Bag bag = BagUtils.synchronizedBag(new HashBag());
* ...
@ -77,74 +78,73 @@ public class BagUtils {
* }
* }
* </pre>
*
* Failure to follow this advice may result in non-deterministic
* behavior.
*
* @param bag the bag to synchronize, must not be null
*
* Failure to follow this advice may result in non-deterministic behavior.
*
* @param bag the bag to synchronize, must not be null
* @return a synchronized bag backed by that bag
* @throws IllegalArgumentException if the Bag is null
* @throws IllegalArgumentException if the Bag is null
*/
public static <E> Bag<E> synchronizedBag(Bag<E> bag) {
return SynchronizedBag.decorate(bag);
}
/**
* Returns an unmodifiable view of the given bag. Any modification
* attempts to the returned bag will raise an
* {@link UnsupportedOperationException}.
*
* @param bag the bag whose unmodifiable view is to be returned, must not be null
* Returns an unmodifiable view of the given bag. Any modification attempts
* to the returned bag will raise an {@link UnsupportedOperationException}.
*
* @param bag the bag whose unmodifiable view is to be returned, must not be
* null
* @return an unmodifiable view of that bag
* @throws IllegalArgumentException if the Bag is null
* @throws IllegalArgumentException if the Bag is null
*/
public static <E> Bag<E> unmodifiableBag(Bag<E> bag) {
return UnmodifiableBag.decorate(bag);
}
/**
* Returns a predicated (validating) bag backed by the given bag.
* <p>
* Only objects that pass the test in the given predicate can be added to the bag.
* Trying to add an invalid object results in an IllegalArgumentException.
* It is important not to use the original bag after invoking this method,
* as it is a backdoor for adding invalid objects.
*
* @param bag the bag to predicate, must not be null
* @param predicate the predicate for the bag, must not be null
* Only objects that pass the test in the given predicate can be added to
* the bag. Trying to add an invalid object results in an
* IllegalArgumentException. It is important not to use the original bag
* after invoking this method, as it is a backdoor for adding invalid
* objects.
*
* @param bag the bag to predicate, must not be null
* @param predicate the predicate for the bag, must not be null
* @return a predicated bag backed by the given bag
* @throws IllegalArgumentException if the Bag or Predicate is null
* @throws IllegalArgumentException if the Bag or Predicate is null
*/
public static <E> Bag<E> predicatedBag(Bag<E> bag, Predicate<? super E> predicate) {
return PredicatedBag.decorate(bag, predicate);
}
/**
* Returns a transformed bag backed by the given bag.
* <p>
* Each object is passed through the transformer as it is added to the
* Bag. It is important not to use the original bag after invoking this
* method, as it is a backdoor for adding untransformed objects.
*
* @param bag the bag to predicate, must not be null
* @param transformer the transformer for the bag, must not be null
* Each object is passed through the transformer as it is added to the Bag.
* It is important not to use the original bag after invoking this method,
* as it is a backdoor for adding untransformed objects.
*
* @param bag the bag to predicate, must not be null
* @param transformer the transformer for the bag, must not be null
* @return a transformed bag backed by the given bag
* @throws IllegalArgumentException if the Bag or Transformer is null
* @throws IllegalArgumentException if the Bag or Transformer is null
*/
public static Bag transformedBag(Bag bag, Transformer transformer) {
public static <E> Bag<E> transformedBag(Bag<E> bag, Transformer<? super E, ? extends E> transformer) {
return TransformedBag.decorate(bag, transformer);
}
//-----------------------------------------------------------------------
/**
* Returns a synchronized (thread-safe) sorted bag backed by the given
* sorted bag.
* In order to guarantee serial access, it is critical that all
* Returns a synchronized (thread-safe) sorted bag backed by the given
* sorted bag. In order to guarantee serial access, it is critical that all
* access to the backing bag is accomplished through the returned bag.
* <p>
* It is imperative that the user manually synchronize on the returned
* bag when iterating over it:
*
* It is imperative that the user manually synchronize on the returned bag
* when iterating over it:
*
* <pre>
* SortedBag bag = BagUtils.synchronizedSortedBag(new TreeBag());
* ...
@ -155,62 +155,84 @@ public class BagUtils {
* }
* }
* </pre>
*
* Failure to follow this advice may result in non-deterministic
* behavior.
*
* @param bag the bag to synchronize, must not be null
*
* Failure to follow this advice may result in non-deterministic behavior.
*
* @param bag the bag to synchronize, must not be null
* @return a synchronized bag backed by that bag
* @throws IllegalArgumentException if the SortedBag is null
* @throws IllegalArgumentException if the SortedBag is null
*/
public static <E> SortedBag<E> synchronizedSortedBag(SortedBag<E> bag) {
return SynchronizedSortedBag.decorate(bag);
}
/**
* Returns an unmodifiable view of the given sorted bag. Any modification
* attempts to the returned bag will raise an
* Returns an unmodifiable view of the given sorted bag. Any modification
* attempts to the returned bag will raise an
* {@link UnsupportedOperationException}.
*
* @param bag the bag whose unmodifiable view is to be returned, must not be null
*
* @param bag the bag whose unmodifiable view is to be returned, must not be
* null
* @return an unmodifiable view of that bag
* @throws IllegalArgumentException if the SortedBag is null
* @throws IllegalArgumentException if the SortedBag is null
*/
public static <E> SortedBag<E> unmodifiableSortedBag(SortedBag<E> bag) {
return UnmodifiableSortedBag.decorate(bag);
}
/**
* Returns a predicated (validating) sorted bag backed by the given sorted bag.
* Returns a predicated (validating) sorted bag backed by the given sorted
* bag.
* <p>
* Only objects that pass the test in the given predicate can be added to the bag.
* Trying to add an invalid object results in an IllegalArgumentException.
* It is important not to use the original bag after invoking this method,
* as it is a backdoor for adding invalid objects.
*
* @param bag the sorted bag to predicate, must not be null
* @param predicate the predicate for the bag, must not be null
* Only objects that pass the test in the given predicate can be added to
* the bag. Trying to add an invalid object results in an
* IllegalArgumentException. It is important not to use the original bag
* after invoking this method, as it is a backdoor for adding invalid
* objects.
*
* @param bag the sorted bag to predicate, must not be null
* @param predicate the predicate for the bag, must not be null
* @return a predicated bag backed by the given bag
* @throws IllegalArgumentException if the SortedBag or Predicate is null
* @throws IllegalArgumentException if the SortedBag or Predicate is null
*/
public static <E> SortedBag<E> predicatedSortedBag(SortedBag<E> bag, Predicate<? super E> predicate) {
public static <E> SortedBag<E> predicatedSortedBag(SortedBag<E> bag,
Predicate<? super E> predicate) {
return PredicatedSortedBag.decorate(bag, predicate);
}
/**
* Returns a transformed sorted bag backed by the given bag.
* <p>
* Each object is passed through the transformer as it is added to the
* Bag. It is important not to use the original bag after invoking this
* method, as it is a backdoor for adding untransformed objects.
*
* @param bag the bag to predicate, must not be null
* @param transformer the transformer for the bag, must not be null
* Each object is passed through the transformer as it is added to the Bag.
* It is important not to use the original bag after invoking this method,
* as it is a backdoor for adding untransformed objects.
*
* @param bag the bag to predicate, must not be null
* @param transformer the transformer for the bag, must not be null
* @return a transformed bag backed by the given bag
* @throws IllegalArgumentException if the Bag or Transformer is null
* @throws IllegalArgumentException if the Bag or Transformer is null
*/
public static SortedBag transformedSortedBag(SortedBag bag, Transformer transformer) {
public static <E> SortedBag<E> transformedSortedBag(SortedBag<E> bag, Transformer<? super E, ? extends E> transformer) {
return TransformedSortedBag.decorate(bag, transformer);
}
/**
* Get an empty <code>Bag</code>.
* @param <E>
* @return Bag<E>
*/
@SuppressWarnings("unchecked")
public static <E> Bag<E> emptyBag() {
return (Bag<E>) EMPTY_BAG;
}
/**
* Get an empty <code>SortedBag</code>.
* @param <E>
* @return SortedBag<E>
*/
@SuppressWarnings("unchecked")
public static <E> SortedBag<E> emptySortedBag() {
return (SortedBag<E>) EMPTY_SORTED_BAG;
}
}

View File

@ -88,7 +88,7 @@ public interface BidiMap<K, V> extends IterableMap<K, V> {
* @throws NullPointerException (optional) if the map limits the values to
* non-null and null was specified
*/
K getKey(V value);
K getKey(Object value);
/**
* Removes the key-value pair that is currently mapped to the specified
@ -109,7 +109,7 @@ public interface BidiMap<K, V> extends IterableMap<K, V> {
* @throws UnsupportedOperationException if this method is not supported
* by the implementation
*/
K removeValue(V value);
K removeValue(Object value);
/**
* Gets a view of this map where the keys and values are reversed.

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

@ -30,7 +30,7 @@ import java.util.Map;
*
* @author Stephen Colebourne
*/
public interface BoundedMap extends Map {
public interface BoundedMap<K, V> extends Map<K, V> {
/**
* Returns true if this map 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

@ -37,7 +37,7 @@ public class BufferUtils {
/**
* An empty unmodifiable buffer.
*/
public static final Buffer EMPTY_BUFFER = UnmodifiableBuffer.decorate(new ArrayStack(1));
public static final Buffer<Object> EMPTY_BUFFER = UnmodifiableBuffer.decorate(new ArrayStack<Object>(1));
/**
* <code>BufferUtils</code> should not normally be instantiated.
@ -66,7 +66,7 @@ public class BufferUtils {
* @return a synchronized buffer backed by that buffer
* @throws IllegalArgumentException if the Buffer is null
*/
public static Buffer synchronizedBuffer(Buffer buffer) {
public static <E> Buffer<E> synchronizedBuffer(Buffer<E> buffer) {
return SynchronizedBuffer.decorate(buffer);
}
@ -82,7 +82,7 @@ public class BufferUtils {
* @return a blocking buffer backed by that buffer
* @throws IllegalArgumentException if the Buffer is null
*/
public static Buffer blockingBuffer(Buffer buffer) {
public static <E> Buffer<E> blockingBuffer(Buffer<E> buffer) {
return BlockingBuffer.decorate(buffer);
}
@ -100,7 +100,7 @@ public class BufferUtils {
* @throws IllegalArgumentException if the Buffer is null
* @since Commons Collections 3.2
*/
public static Buffer blockingBuffer(Buffer buffer, long timeoutMillis) {
public static <E> Buffer<E> blockingBuffer(Buffer<E> buffer, long timeoutMillis) {
return BlockingBuffer.decorate(buffer, timeoutMillis);
}
@ -117,7 +117,7 @@ public class BufferUtils {
* @throws IllegalArgumentException if the given buffer is null
* @since Commons Collections 3.2
*/
public static Buffer boundedBuffer(Buffer buffer, int maximumSize) {
public static <E> Buffer<E> boundedBuffer(Buffer<E> buffer, int maximumSize) {
return BoundedBuffer.decorate(buffer, maximumSize);
}
@ -135,7 +135,7 @@ public class BufferUtils {
* @throws IllegalArgumentException if the given buffer is null
* @since Commons Collections 3.2
*/
public static Buffer boundedBuffer(Buffer buffer, int maximumSize, long timeoutMillis) {
public static <E> Buffer<E> boundedBuffer(Buffer<E> buffer, int maximumSize, long timeoutMillis) {
return BoundedBuffer.decorate(buffer, maximumSize, timeoutMillis);
}
@ -146,7 +146,7 @@ public class BufferUtils {
* @return an unmodifiable buffer backed by that buffer
* @throws IllegalArgumentException if the Buffer is null
*/
public static Buffer unmodifiableBuffer(Buffer buffer) {
public static <E> Buffer<E> unmodifiableBuffer(Buffer<E> buffer) {
return UnmodifiableBuffer.decorate(buffer);
}
@ -163,7 +163,7 @@ public class BufferUtils {
* @return a predicated buffer
* @throws IllegalArgumentException if the Buffer or Predicate is null
*/
public static Buffer predicatedBuffer(Buffer buffer, Predicate predicate) {
public static <E> Buffer<E> predicatedBuffer(Buffer<E> buffer, Predicate<? super E> predicate) {
return PredicatedBuffer.decorate(buffer, predicate);
}
@ -179,8 +179,17 @@ public class BufferUtils {
* @return a transformed buffer backed by the given buffer
* @throws IllegalArgumentException if the Buffer or Transformer is null
*/
public static Buffer transformedBuffer(Buffer buffer, Transformer transformer) {
public static <E> Buffer<E> transformedBuffer(Buffer<E> buffer, Transformer<? super E, ? extends E> transformer) {
return TransformedBuffer.decorate(buffer, transformer);
}
/**
* Get an empty <code>Buffer</code>.
* @param <E>
* @return Buffer<E>
*/
@SuppressWarnings("unchecked")
public static <E> Buffer<E> emptyBuffer() {
return (Buffer<E>) EMPTY_BUFFER;
}
}

View File

@ -17,7 +17,6 @@
package org.apache.commons.collections;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import org.apache.commons.collections.functors.ChainedClosure;
@ -71,8 +70,8 @@ public class ClosureUtils {
*
* @return the closure
*/
public static Closure exceptionClosure() {
return ExceptionClosure.INSTANCE;
public static <E> Closure<E> exceptionClosure() {
return ExceptionClosure.<E>getInstance();
}
/**
@ -83,8 +82,8 @@ public class ClosureUtils {
*
* @return the closure
*/
public static Closure nopClosure() {
return NOPClosure.INSTANCE;
public static <E> Closure<E> nopClosure() {
return NOPClosure.<E>getInstance();
}
/**
@ -97,7 +96,7 @@ public class ClosureUtils {
* @param transformer the transformer to run each time in the closure, null means nop
* @return the closure
*/
public static Closure asClosure(Transformer transformer) {
public static <E> Closure<E> asClosure(Transformer<? super E, ?> transformer) {
return TransformerClosure.getInstance(transformer);
}
@ -112,7 +111,7 @@ public class ClosureUtils {
* @param closure the closure to call repeatedly
* @return the <code>for</code> closure
*/
public static Closure forClosure(int count, Closure closure) {
public static <E> Closure<E> forClosure(int count, Closure<? super E> closure) {
return ForClosure.getInstance(count, closure);
}
@ -127,8 +126,8 @@ public class ClosureUtils {
* @return the <code>while</code> closure
* @throws IllegalArgumentException if either argument is null
*/
public static Closure whileClosure(Predicate predicate, Closure closure) {
return WhileClosure.getInstance(predicate, closure, false);
public static <E> Closure<E> whileClosure(Predicate<? super E> predicate, Closure<? super E> closure) {
return WhileClosure.<E>getInstance(predicate, closure, false);
}
/**
@ -142,8 +141,8 @@ public class ClosureUtils {
* @return the <code>do-while</code> closure
* @throws IllegalArgumentException if either argument is null
*/
public static Closure doWhileClosure(Closure closure, Predicate predicate) {
return WhileClosure.getInstance(predicate, closure, true);
public static <E> Closure<E> doWhileClosure(Closure<? super E> closure, Predicate<? super E> predicate) {
return WhileClosure.<E>getInstance(predicate, closure, true);
}
/**
@ -157,9 +156,9 @@ public class ClosureUtils {
* @return the <code>invoker</code> closure
* @throws IllegalArgumentException if the method name is null
*/
public static Closure invokerClosure(String methodName) {
public static <E> Closure<E> invokerClosure(String methodName) {
// reuse transformer as it has caching - this is lazy really, should have inner class here
return asClosure(InvokerTransformer.getInstance(methodName));
return asClosure(InvokerTransformer.<E, Object>getInstance(methodName));
}
/**
@ -176,9 +175,9 @@ public class ClosureUtils {
* @throws IllegalArgumentException if the method name is null
* @throws IllegalArgumentException if the paramTypes and args don't match
*/
public static Closure invokerClosure(String methodName, Class[] paramTypes, Object[] args) {
public static <E> Closure<E> invokerClosure(String methodName, Class<?>[] paramTypes, Object[] args) {
// reuse transformer as it has caching - this is lazy really, should have inner class here
return asClosure(InvokerTransformer.getInstance(methodName, paramTypes, args));
return asClosure(InvokerTransformer.<E, Object>getInstance(methodName, paramTypes, args));
}
/**
@ -192,8 +191,8 @@ public class ClosureUtils {
* @return the <code>chained</code> closure
* @throws IllegalArgumentException if either closure is null
*/
public static Closure chainedClosure(Closure closure1, Closure closure2) {
return ChainedClosure.getInstance(closure1, closure2);
public static <E> Closure<E> chainedClosure(Closure<? super E> closure1, Closure<? super E> closure2) {
return ChainedClosure.<E>getInstance(closure1, closure2);
}
/**
@ -207,7 +206,7 @@ public class ClosureUtils {
* @throws IllegalArgumentException if the closures array is null
* @throws IllegalArgumentException if any closure in the array is null
*/
public static Closure chainedClosure(Closure[] closures) {
public static <E> Closure<E> chainedClosure(Closure<? super E>[] closures) {
return ChainedClosure.getInstance(closures);
}
@ -224,7 +223,7 @@ public class ClosureUtils {
* @throws IllegalArgumentException if the closures collection is empty
* @throws IllegalArgumentException if any closure in the collection is null
*/
public static Closure chainedClosure(Collection closures) {
public static <E> Closure<E> chainedClosure(Collection<Closure<E>> closures) {
return ChainedClosure.getInstance(closures);
}
@ -241,8 +240,8 @@ public class ClosureUtils {
* @throws IllegalArgumentException if the closure is null
* @since Commons Collections 3.2
*/
public static Closure ifClosure(Predicate predicate, Closure trueClosure) {
return IfClosure.getInstance(predicate, trueClosure);
public static <E> Closure<E> ifClosure(Predicate<? super E> predicate, Closure<? super E> trueClosure) {
return IfClosure.<E>getInstance(predicate, trueClosure);
}
/**
@ -258,8 +257,8 @@ public class ClosureUtils {
* @throws IllegalArgumentException if the predicate is null
* @throws IllegalArgumentException if either closure is null
*/
public static Closure ifClosure(Predicate predicate, Closure trueClosure, Closure falseClosure) {
return IfClosure.getInstance(predicate, trueClosure, falseClosure);
public static <E> Closure<E> ifClosure(Predicate<? super E> predicate, Closure<? super E> trueClosure, Closure<? super E> falseClosure) {
return IfClosure.<E>getInstance(predicate, trueClosure, falseClosure);
}
/**
@ -279,8 +278,8 @@ public class ClosureUtils {
* @throws IllegalArgumentException if any element in the arrays is null
* @throws IllegalArgumentException if the arrays are different sizes
*/
public static Closure switchClosure(Predicate[] predicates, Closure[] closures) {
return SwitchClosure.getInstance(predicates, closures, null);
public static <E> Closure<E> switchClosure(Predicate<? super E>[] predicates, Closure<? super E>[] closures) {
return SwitchClosure.<E>getInstance(predicates, closures, null);
}
/**
@ -302,8 +301,8 @@ public class ClosureUtils {
* @throws IllegalArgumentException if any element in the arrays is null
* @throws IllegalArgumentException if the arrays are different sizes
*/
public static Closure switchClosure(Predicate[] predicates, Closure[] closures, Closure defaultClosure) {
return SwitchClosure.getInstance(predicates, closures, defaultClosure);
public static <E> Closure<E> switchClosure(Predicate<? super E>[] predicates, Closure<? super E>[] closures, Closure<? super E> defaultClosure) {
return SwitchClosure.<E>getInstance(predicates, closures, defaultClosure);
}
/**
@ -326,7 +325,7 @@ public class ClosureUtils {
* @throws IllegalArgumentException if any closure in the map is null
* @throws ClassCastException if the map elements are of the wrong type
*/
public static Closure switchClosure(Map predicatesAndClosures) {
public static <E> Closure<E> switchClosure(Map<Predicate<E>, Closure<E>> predicatesAndClosures) {
return SwitchClosure.getInstance(predicatesAndClosures);
}
@ -347,24 +346,24 @@ public class ClosureUtils {
* @throws IllegalArgumentException if the map is empty
* @throws IllegalArgumentException if any closure in the map is null
*/
public static Closure switchMapClosure(Map objectsAndClosures) {
Closure[] trs = null;
Predicate[] preds = null;
@SuppressWarnings("unchecked")
public static <E> Closure<E> switchMapClosure(Map<? extends E, Closure<E>> objectsAndClosures) {
Closure<? super E>[] trs = null;
Predicate<E>[] preds = null;
if (objectsAndClosures == null) {
throw new IllegalArgumentException("The object and closure map must not be null");
}
Closure def = (Closure) objectsAndClosures.remove(null);
Closure<? super E> def = objectsAndClosures.remove(null);
int size = objectsAndClosures.size();
trs = new Closure[size];
preds = new Predicate[size];
int i = 0;
for (Iterator it = objectsAndClosures.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
preds[i] = EqualPredicate.equalPredicate(entry.getKey());
trs[i] = (Closure) entry.getValue();
for (Map.Entry<? extends E, Closure<E>> entry : objectsAndClosures.entrySet()) {
preds[i] = EqualPredicate.<E>equalPredicate(entry.getKey());
trs[i] = entry.getValue();
i++;
}
return switchClosure(preds, trs, def);
return ClosureUtils.<E>switchClosure(preds, trs, def);
}
}

View File

@ -63,9 +63,9 @@ public class CollectionUtils {
private static class CardinalityHelper<O> {
final Map<O, Integer> cardinalityA, cardinalityB;
public <I1 extends O, I2 extends O> CardinalityHelper(Iterable<I1> a, Iterable<I2> b) {
cardinalityA = CollectionUtils.<O, I1>getCardinalityMap(a);
cardinalityB = CollectionUtils.<O, I2>getCardinalityMap(b);
public CardinalityHelper(Iterable<? extends O> a, Iterable<? extends O> b) {
cardinalityA = CollectionUtils.<O>getCardinalityMap(a);
cardinalityB = CollectionUtils.<O>getCardinalityMap(b);
}
public final int max(Object obj) {
@ -119,7 +119,6 @@ public class CollectionUtils {
return newList;
}
}
/**
@ -292,9 +291,9 @@ public class CollectionUtils {
* super type of <I>.
* @return the populated cardinality map
*/
public static <O, I extends O> Map<O, Integer> getCardinalityMap(final Iterable<I> coll) {
public static <O> Map<O, Integer> getCardinalityMap(final Iterable<? extends O> coll) {
Map<O, Integer> count = new HashMap<O, Integer>();
for (I obj : coll) {
for (O obj : coll) {
Integer c = count.get(obj);
if (c == null) {
count.put(obj, 1);
@ -490,7 +489,8 @@ public class CollectionUtils {
* @param transformer
* the transformer to perform, may be null
*/
public static <C> void transform(Collection<C> collection, Transformer<? super C, ? extends C> transformer) {
public static <C> void transform(Collection<C> collection,
Transformer<? super C, ? extends C> transformer) {
if (collection != null && transformer != null) {
if (collection instanceof List) {
List<C> list = (List<C>) collection;
@ -567,7 +567,8 @@ public class CollectionUtils {
* @throws NullPointerException
* if the input collection is null
*/
public static <O, I extends O> Collection<O> select(Collection<I> inputCollection, Predicate<? super I> predicate) {
public static <O> Collection<O> select(Collection<? extends O> inputCollection,
Predicate<? super O> predicate) {
return select(inputCollection, predicate, new ArrayList<O>(inputCollection.size()));
}
@ -586,9 +587,10 @@ public class CollectionUtils {
* the collection to output into, may not be null
* @return outputCollection
*/
public static <O, I extends O, R extends Collection<O>> R select(Collection<I> inputCollection, Predicate<? super I> predicate, R outputCollection) {
public static <O, R extends Collection<? super O>> R select(Collection<? extends O> inputCollection,
Predicate<? super O> predicate, R outputCollection) {
if (inputCollection != null && predicate != null) {
for (I item : inputCollection) {
for (O item : inputCollection) {
if (predicate.evaluate(item)) {
outputCollection.add(item);
}
@ -612,7 +614,8 @@ public class CollectionUtils {
* @throws NullPointerException
* if the input collection is null
*/
public static <O, I extends O> Collection<O> selectRejected(Collection<I> inputCollection, Predicate<? super I> predicate) {
public static <O> Collection<O> selectRejected(Collection<? extends O> inputCollection,
Predicate<? super O> predicate) {
return selectRejected(inputCollection, predicate, new ArrayList<O>(inputCollection.size()));
}
@ -631,9 +634,10 @@ public class CollectionUtils {
* the collection to output into, may not be null
* @return outputCollection
*/
public static <O, I extends O, R extends Collection<O>> R selectRejected(Collection<I> inputCollection, Predicate<? super I> predicate, R outputCollection) {
public static <O, R extends Collection<? super O>> R selectRejected(
Collection<? extends O> inputCollection, Predicate<? super O> predicate, R outputCollection) {
if (inputCollection != null && predicate != null) {
for (I item : inputCollection) {
for (O item : inputCollection) {
if (!predicate.evaluate(item)) {
outputCollection.add(item);
}
@ -658,7 +662,8 @@ public class CollectionUtils {
* @throws NullPointerException
* if the input collection is null
*/
public static <I,O> Collection<O> collect(Iterable<I> inputCollection, Transformer<? super I, ? extends O> transformer) {
public static <I, O> Collection<O> collect(Iterable<I> inputCollection,
Transformer<? super I, ? extends O> transformer) {
ArrayList<O> answer = new ArrayList<O>();
collect(inputCollection, transformer, answer);
return answer;
@ -679,7 +684,8 @@ public class CollectionUtils {
* @param <O> the type of object in the output collection
* @return the transformed result (new list)
*/
public static <I,O> Collection<O> collect(Iterator<I> inputIterator, Transformer<? super I, ? extends O> transformer) {
public static <I, O> Collection<O> collect(Iterator<I> inputIterator,
Transformer<? super I, ? extends O> transformer) {
ArrayList<O> answer = new ArrayList<O>();
collect(inputIterator, transformer, answer);
return answer;
@ -701,7 +707,8 @@ public class CollectionUtils {
* @return the outputCollection with the transformed input added
* @throws NullPointerException if the output collection is null
*/
public static <I,O,T extends O, R extends Collection<O>> R collect(Iterable<I> inputCollection, final Transformer<? super I,T> transformer, final R outputCollection) {
public static <I, O, R extends Collection<? super O>> R collect(Iterable<? extends I> inputCollection,
final Transformer<? super I, ? extends O> transformer, final R outputCollection) {
if (inputCollection != null) {
return collect(inputCollection.iterator(), transformer, outputCollection);
}
@ -725,11 +732,12 @@ public class CollectionUtils {
* @throws NullPointerException if the output collection is null
*/
//TODO - deprecate and replace with IteratorIterable
public static <I,O,T extends O, R extends Collection<O>> R collect(Iterator<I> inputIterator, final Transformer<? super I,T> transformer, final R outputCollection) {
public static <I, O, R extends Collection<? super O>> R collect(Iterator<? extends I> inputIterator,
final Transformer<? super I, ? extends O> transformer, final R outputCollection) {
if (inputIterator != null && transformer != null) {
while (inputIterator.hasNext()) {
I item = inputIterator.next();
T value = transformer.transform(item);
O value = transformer.transform(item);
outputCollection.add(value);
}
}
@ -813,7 +821,7 @@ public class CollectionUtils {
* @throws NullPointerException
* if the collection or array is null
*/
public static <C, T extends C> void addAll(Collection<C> collection, T[] elements) {
public static <C> void addAll(Collection<C> collection, C[] elements) {
for (int i = 0, size = elements.length; i < size; i++) {
collection.add(elements[i]);
}
@ -913,13 +921,13 @@ public class CollectionUtils {
throw new IndexOutOfBoundsException("Index cannot be negative: " + i);
}
if (object instanceof Map) {
Map map = (Map) object;
Iterator iterator = map.entrySet().iterator();
Map<?, ?> map = (Map<?, ?>) object;
Iterator<?> iterator = map.entrySet().iterator();
return get(iterator, i);
} else if (object instanceof Object[]) {
return ((Object[]) object)[i];
} else if (object instanceof Iterator) {
Iterator it = (Iterator) object;
Iterator<?> it = (Iterator<?>) object;
while (it.hasNext()) {
i--;
if (i == -1) {
@ -929,10 +937,10 @@ public class CollectionUtils {
}
throw new IndexOutOfBoundsException("Entry does not exist: " + i);
} else if (object instanceof Collection) {
Iterator iterator = ((Collection) object).iterator();
Iterator<?> iterator = ((Collection<?>) object).iterator();
return get(iterator, i);
} else if (object instanceof Enumeration) {
Enumeration it = (Enumeration) object;
Enumeration<?> it = (Enumeration<?>) object;
while (it.hasMoreElements()) {
i--;
if (i == -1) {
@ -987,19 +995,19 @@ public class CollectionUtils {
public static int size(Object object) {
int total = 0;
if (object instanceof Map) {
total = ((Map) object).size();
total = ((Map<?, ?>) object).size();
} else if (object instanceof Collection) {
total = ((Collection) object).size();
total = ((Collection<?>) object).size();
} else if (object instanceof Object[]) {
total = ((Object[]) object).length;
} else if (object instanceof Iterator) {
Iterator it = (Iterator) object;
Iterator<?> it = (Iterator<?>) object;
while (it.hasNext()) {
total++;
it.next();
}
} else if (object instanceof Enumeration) {
Enumeration it = (Enumeration) object;
Enumeration<?> it = (Enumeration<?>) object;
while (it.hasMoreElements()) {
total++;
it.nextElement();
@ -1038,15 +1046,15 @@ public class CollectionUtils {
*/
public static boolean sizeIsEmpty(Object object) {
if (object instanceof Collection) {
return ((Collection) object).isEmpty();
return ((Collection<?>) object).isEmpty();
} else if (object instanceof Map) {
return ((Map) object).isEmpty();
return ((Map<?, ?>) object).isEmpty();
} else if (object instanceof Object[]) {
return ((Object[]) object).length == 0;
} else if (object instanceof Iterator) {
return ((Iterator) object).hasNext() == false;
return ((Iterator<?>) object).hasNext() == false;
} else if (object instanceof Enumeration) {
return ((Enumeration) object).hasMoreElements() == false;
return ((Enumeration<?>) object).hasMoreElements() == false;
} else if (object == null) {
throw new IllegalArgumentException("Unsupported object type: null");
} else {
@ -1068,7 +1076,7 @@ public class CollectionUtils {
* @return true if empty or null
* @since Commons Collections 3.2
*/
public static boolean isEmpty(Collection coll) {
public static boolean isEmpty(Collection<?> coll) {
return (coll == null || coll.isEmpty());
}
@ -1081,7 +1089,7 @@ public class CollectionUtils {
* @return true if non-null and non-empty
* @since Commons Collections 3.2
*/
public static boolean isNotEmpty(Collection coll) {
public static boolean isNotEmpty(Collection<?> coll) {
return !isEmpty(coll);
}
@ -1120,17 +1128,17 @@ public class CollectionUtils {
* @return true if the BoundedCollection is full
* @throws NullPointerException if the collection is null
*/
public static boolean isFull(Collection coll) {
@SuppressWarnings("unchecked")
public static boolean isFull(Collection<?> coll) {
if (coll == null) {
throw new NullPointerException("The collection must not be null");
}
if (coll instanceof BoundedCollection) {
return ((BoundedCollection) coll).isFull();
return ((BoundedCollection<?>) coll).isFull();
}
try {
BoundedCollection bcoll = UnmodifiableBoundedCollection.decorateUsing(coll);
BoundedCollection<?> bcoll = UnmodifiableBoundedCollection.decorateUsing((Collection<Object>) coll);
return bcoll.isFull();
} catch (IllegalArgumentException ex) {
return false;
}
@ -1151,17 +1159,17 @@ public class CollectionUtils {
* @return the maximum size of the BoundedCollection, -1 if no maximum size
* @throws NullPointerException if the collection is null
*/
public static int maxSize(Collection coll) {
@SuppressWarnings("unchecked")
public static int maxSize(Collection<?> coll) {
if (coll == null) {
throw new NullPointerException("The collection must not be null");
}
if (coll instanceof BoundedCollection) {
return ((BoundedCollection) coll).maxSize();
return ((BoundedCollection<?>) coll).maxSize();
}
try {
BoundedCollection bcoll = UnmodifiableBoundedCollection.decorateUsing(coll);
BoundedCollection<?> bcoll = UnmodifiableBoundedCollection.decorateUsing((Collection<Object>) coll);
return bcoll.maxSize();
} catch (IllegalArgumentException ex) {
return -1;
}
@ -1203,7 +1211,7 @@ public class CollectionUtils {
* @throws NullPointerException if either parameter is null
* @since Commons Collections 3.3 (method existed in 3.2 but was completely broken)
*/
public static Collection removeAll(Collection collection, Collection remove) {
public static <E> Collection<E> removeAll(Collection<E> collection, Collection<?> remove) {
return ListUtils.removeAll(collection, remove);
}
@ -1277,7 +1285,7 @@ public class CollectionUtils {
* @return a transformed collection backed by the given collection
* @throws IllegalArgumentException if the Collection or Transformer is null
*/
public static Collection transformedCollection(Collection collection, Transformer transformer) {
public static <E> Collection<E> transformedCollection(Collection<E> collection, Transformer<? super E, ? extends E> transformer) {
return TransformedCollection.decorate(collection, transformer);
}

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

@ -55,8 +55,8 @@ public class FactoryUtils {
*
* @return the factory
*/
public static Factory exceptionFactory() {
return ExceptionFactory.INSTANCE;
public static <T> Factory<T> exceptionFactory() {
return ExceptionFactory.<T>getInstance();
}
/**
@ -68,7 +68,7 @@ public class FactoryUtils {
* @return the factory
*/
public static <T> Factory<T> nullFactory() {
return ConstantFactory.NULL_INSTANCE;
return ConstantFactory.<T>getInstance(null);
}
/**
@ -82,7 +82,7 @@ public class FactoryUtils {
* @param constantToReturn the constant object to return each time in the factory
* @return the <code>constant</code> factory.
*/
public static Factory constantFactory(Object constantToReturn) {
public static <T> Factory<T> constantFactory(T constantToReturn) {
return ConstantFactory.getInstance(constantToReturn);
}
@ -103,8 +103,8 @@ public class FactoryUtils {
* @throws IllegalArgumentException if the prototype is null
* @throws IllegalArgumentException if the prototype cannot be cloned
*/
public static Factory prototypeFactory(Object prototype) {
return PrototypeFactory.getInstance(prototype);
public static <T> Factory<T> prototypeFactory(T prototype) {
return PrototypeFactory.<T>getInstance(prototype);
}
/**
@ -135,7 +135,7 @@ public class FactoryUtils {
* @throws IllegalArgumentException if the paramTypes and args don't match
* @throws IllegalArgumentException if the constructor doesn't exist
*/
public static <T> Factory<T> instantiateFactory(Class<T> classToInstantiate, Class[] paramTypes, Object[] args) {
public static <T> Factory<T> instantiateFactory(Class<T> classToInstantiate, Class<?>[] paramTypes, Object[] args) {
return InstantiateFactory.getInstance(classToInstantiate, paramTypes, args);
}

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

@ -81,26 +81,30 @@ public class IteratorUtils {
* WARNING: This constant is binary incompatible with Commons Collections 2.1 and 2.1.1.
* Use <code>EmptyIterator.INSTANCE</code> for compatability with Commons Collections 2.1.1.
*/
public static final ResettableIterator EMPTY_ITERATOR = EmptyIterator.RESETTABLE_INSTANCE;
public static final ResettableIterator<Object> EMPTY_ITERATOR = EmptyIterator.RESETTABLE_INSTANCE;
/**
* A list iterator over no elements.
* <p>
* WARNING: This constant is binary incompatible with Commons Collections 2.1 and 2.1.1.
* Use <code>EmptyListIterator.INSTANCE</code> for compatability with Commons Collections 2.1.1.
*/
public static final ResettableListIterator EMPTY_LIST_ITERATOR = EmptyListIterator.RESETTABLE_INSTANCE;
public static final ResettableListIterator<Object> EMPTY_LIST_ITERATOR = EmptyListIterator.RESETTABLE_INSTANCE;
/**
* An ordered iterator over no elements.
*/
public static final OrderedIterator EMPTY_ORDERED_ITERATOR = EmptyOrderedIterator.INSTANCE;
public static final OrderedIterator<Object> EMPTY_ORDERED_ITERATOR = EmptyOrderedIterator.INSTANCE;
/**
* A map iterator over no elements.
*/
public static final MapIterator EMPTY_MAP_ITERATOR = EmptyMapIterator.INSTANCE;
public static final MapIterator<Object, Object> EMPTY_MAP_ITERATOR = EmptyMapIterator.INSTANCE;
/**
* An ordered map iterator over no elements.
*/
public static final OrderedMapIterator EMPTY_ORDERED_MAP_ITERATOR = EmptyOrderedMapIterator.INSTANCE;
public static final OrderedMapIterator<Object, Object> EMPTY_ORDERED_MAP_ITERATOR = EmptyOrderedMapIterator.INSTANCE;
/**
* IteratorUtils is not normally instantiated.
@ -121,8 +125,8 @@ public class IteratorUtils {
*
* @return an iterator over nothing
*/
public static ResettableIterator emptyIterator() {
return EMPTY_ITERATOR;
public static <E> ResettableIterator<E> emptyIterator() {
return EmptyIterator.<E>getResettableInstance();
}
/**
@ -136,8 +140,8 @@ public class IteratorUtils {
*
* @return a list iterator over nothing
*/
public static ResettableListIterator emptyListIterator() {
return EMPTY_LIST_ITERATOR;
public static <E> ResettableListIterator<E> emptyListIterator() {
return EmptyListIterator.<E>getResettableInstance();
}
/**
@ -148,8 +152,8 @@ public class IteratorUtils {
*
* @return an ordered iterator over nothing
*/
public static OrderedIterator emptyOrderedIterator() {
return EMPTY_ORDERED_ITERATOR;
public static <E> OrderedIterator<E> emptyOrderedIterator() {
return EmptyOrderedIterator.<E>getInstance();
}
/**
@ -160,8 +164,8 @@ public class IteratorUtils {
*
* @return a map iterator over nothing
*/
public static MapIterator emptyMapIterator() {
return EMPTY_MAP_ITERATOR;
public static <K, V> MapIterator<K, V> emptyMapIterator() {
return EmptyMapIterator.<K, V>getInstance();
}
/**
@ -172,8 +176,8 @@ public class IteratorUtils {
*
* @return a map iterator over nothing
*/
public static OrderedMapIterator emptyOrderedMapIterator() {
return EMPTY_ORDERED_MAP_ITERATOR;
public static <K, V> OrderedMapIterator<K, V> emptyOrderedMapIterator() {
return EmptyOrderedMapIterator.<K, V>getInstance();
}
// Singleton
@ -190,8 +194,8 @@ public class IteratorUtils {
* @param object the single object over which to iterate
* @return a singleton iterator over the object
*/
public static ResettableIterator singletonIterator(Object object) {
return new SingletonIterator(object);
public static <E> ResettableIterator<E> singletonIterator(E object) {
return new SingletonIterator<E>(object);
}
/**
@ -203,8 +207,8 @@ public class IteratorUtils {
* @param object the single object over which to iterate
* @return a singleton list iterator over the object
*/
public static ListIterator singletonListIterator(Object object) {
return new SingletonListIterator(object);
public static <E> ListIterator<E> singletonListIterator(E object) {
return new SingletonListIterator<E>(object);
}
// Arrays
@ -219,8 +223,8 @@ public class IteratorUtils {
* @return an iterator over the array
* @throws NullPointerException if array is null
*/
public static ResettableIterator arrayIterator(Object[] array) {
return new ObjectArrayIterator(array);
public static <E> ResettableIterator<E> arrayIterator(E[] array) {
return new ObjectArrayIterator<E>(array);
}
/**
@ -234,8 +238,8 @@ public class IteratorUtils {
* @throws IllegalArgumentException if the array is not an array
* @throws NullPointerException if array is null
*/
public static ResettableIterator arrayIterator(Object array) {
return new ArrayIterator(array);
public static <E> ResettableIterator<E> arrayIterator(Object array) {
return new ArrayIterator<E>(array);
}
/**
@ -251,8 +255,8 @@ public class IteratorUtils {
* than the length of the array
* @throws NullPointerException if array is null
*/
public static ResettableIterator arrayIterator(Object[] array, int start) {
return new ObjectArrayIterator(array, start);
public static <E> ResettableIterator<E> arrayIterator(E[] array, int start) {
return new ObjectArrayIterator<E>(array, start);
}
/**
@ -269,8 +273,8 @@ public class IteratorUtils {
* than the length of the array
* @throws NullPointerException if array is null
*/
public static ResettableIterator arrayIterator(Object array, int start) {
return new ArrayIterator(array, start);
public static <E> ResettableIterator<E> arrayIterator(Object array, int start) {
return new ArrayIterator<E>(array, start);
}
/**
@ -287,8 +291,8 @@ public class IteratorUtils {
* @throws IllegalArgumentException if end is before start
* @throws NullPointerException if array is null
*/
public static ResettableIterator arrayIterator(Object[] array, int start, int end) {
return new ObjectArrayIterator(array, start, end);
public static <E> ResettableIterator<E> arrayIterator(E[] array, int start, int end) {
return new ObjectArrayIterator<E>(array, start, end);
}
/**
@ -306,8 +310,8 @@ public class IteratorUtils {
* @throws IllegalArgumentException if end is before start
* @throws NullPointerException if array is null
*/
public static ResettableIterator arrayIterator(Object array, int start, int end) {
return new ArrayIterator(array, start, end);
public static <E> ResettableIterator<E> arrayIterator(Object array, int start, int end) {
return new ArrayIterator<E>(array, start, end);
}
//-----------------------------------------------------------------------
@ -318,8 +322,8 @@ public class IteratorUtils {
* @return a list iterator over the array
* @throws NullPointerException if array is null
*/
public static ResettableListIterator arrayListIterator(Object[] array) {
return new ObjectArrayListIterator(array);
public static <E> ResettableListIterator<E> arrayListIterator(E[] array) {
return new ObjectArrayListIterator<E>(array);
}
/**
@ -333,8 +337,8 @@ public class IteratorUtils {
* @throws IllegalArgumentException if the array is not an array
* @throws NullPointerException if array is null
*/
public static ResettableListIterator arrayListIterator(Object array) {
return new ArrayListIterator(array);
public static <E> ResettableListIterator<E> arrayListIterator(Object array) {
return new ArrayListIterator<E>(array);
}
/**
@ -346,8 +350,8 @@ public class IteratorUtils {
* @throws IndexOutOfBoundsException if start is less than zero
* @throws NullPointerException if array is null
*/
public static ResettableListIterator arrayListIterator(Object[] array, int start) {
return new ObjectArrayListIterator(array, start);
public static <E> ResettableListIterator<E> arrayListIterator(E[] array, int start) {
return new ObjectArrayListIterator<E>(array, start);
}
/**
@ -363,8 +367,8 @@ public class IteratorUtils {
* @throws IndexOutOfBoundsException if start is less than zero
* @throws NullPointerException if array is null
*/
public static ResettableListIterator arrayListIterator(Object array, int start) {
return new ArrayListIterator(array, start);
public static <E> ResettableListIterator<E> arrayListIterator(Object array, int start) {
return new ArrayListIterator<E>(array, start);
}
/**
@ -378,8 +382,8 @@ public class IteratorUtils {
* @throws IllegalArgumentException if end is before start
* @throws NullPointerException if array is null
*/
public static ResettableListIterator arrayListIterator(Object[] array, int start, int end) {
return new ObjectArrayListIterator(array, start, end);
public static <E> ResettableListIterator<E> arrayListIterator(E[] array, int start, int end) {
return new ObjectArrayListIterator<E>(array, start, end);
}
/**
@ -397,8 +401,8 @@ public class IteratorUtils {
* @throws IllegalArgumentException if end is before start
* @throws NullPointerException if array is null
*/
public static ResettableListIterator arrayListIterator(Object array, int start, int end) {
return new ArrayListIterator(array, start, end);
public static <E> ResettableListIterator<E> arrayListIterator(Object array, int start, int end) {
return new ArrayListIterator<E>(array, start, end);
}
// Unmodifiable
@ -411,7 +415,7 @@ public class IteratorUtils {
* @param iterator the iterator to make immutable
* @return an immutable version of the iterator
*/
public static Iterator unmodifiableIterator(Iterator iterator) {
public static <E> Iterator<E> unmodifiableIterator(Iterator<E> iterator) {
return UnmodifiableIterator.decorate(iterator);
}
@ -424,7 +428,7 @@ public class IteratorUtils {
* @param listIterator the iterator to make immutable
* @return an immutable version of the iterator
*/
public static ListIterator unmodifiableListIterator(ListIterator listIterator) {
public static <E> ListIterator<E> unmodifiableListIterator(ListIterator<E> listIterator) {
return UnmodifiableListIterator.decorate(listIterator);
}
@ -436,7 +440,7 @@ public class IteratorUtils {
* @param mapIterator the iterator to make immutable
* @return an immutable version of the iterator
*/
public static MapIterator unmodifiableMapIterator(MapIterator mapIterator) {
public static <K, V> MapIterator<K, V> unmodifiableMapIterator(MapIterator<K, V> mapIterator) {
return UnmodifiableMapIterator.decorate(mapIterator);
}
@ -451,8 +455,8 @@ public class IteratorUtils {
* @return a combination iterator over the iterators
* @throws NullPointerException if either iterator is null
*/
public static Iterator chainedIterator(Iterator iterator1, Iterator iterator2) {
return new IteratorChain(iterator1, iterator2);
public static <E> Iterator<E> chainedIterator(Iterator<? extends E> iterator1, Iterator<? extends E> iterator2) {
return new IteratorChain<E>(iterator1, iterator2);
}
/**
@ -463,8 +467,8 @@ public class IteratorUtils {
* @return a combination iterator over the iterators
* @throws NullPointerException if iterators array is null or contains a null
*/
public static Iterator chainedIterator(Iterator[] iterators) {
return new IteratorChain(iterators);
public static <E> Iterator<E> chainedIterator(Iterator<? extends E>[] iterators) {
return new IteratorChain<E>(iterators);
}
/**
@ -476,8 +480,8 @@ public class IteratorUtils {
* @throws NullPointerException if iterators collection is null or contains a null
* @throws ClassCastException if the iterators collection contains the wrong object type
*/
public static Iterator chainedIterator(Collection iterators) {
return new IteratorChain(iterators);
public static <E> Iterator<E> chainedIterator(Collection<Iterator<? extends E>> iterators) {
return new IteratorChain<E>(iterators);
}
// Collated
@ -498,8 +502,8 @@ public class IteratorUtils {
* @return a combination iterator over the iterators
* @throws NullPointerException if either iterator is null
*/
public static Iterator collatedIterator(Comparator comparator, Iterator iterator1, Iterator iterator2) {
return new CollatingIterator(comparator, iterator1, iterator2);
public static <E> Iterator<E> collatedIterator(Comparator<? super E> comparator, Iterator<? extends E> iterator1, Iterator<? extends E> iterator2) {
return new CollatingIterator<E>(comparator, iterator1, iterator2);
}
/**
@ -517,8 +521,8 @@ public class IteratorUtils {
* @return a combination iterator over the iterators
* @throws NullPointerException if iterators array is null or contains a null
*/
public static Iterator collatedIterator(Comparator comparator, Iterator[] iterators) {
return new CollatingIterator(comparator, iterators);
public static <E> Iterator<E> collatedIterator(Comparator<? super E> comparator, Iterator<? extends E>[] iterators) {
return new CollatingIterator<E>(comparator, iterators);
}
/**
@ -537,8 +541,9 @@ public class IteratorUtils {
* @throws NullPointerException if iterators collection is null or contains a null
* @throws ClassCastException if the iterators collection contains the wrong object type
*/
public static Iterator collatedIterator(Comparator comparator, Collection iterators) {
return new CollatingIterator(comparator, iterators);
public static <E> Iterator<E> collatedIterator(Comparator<? super E> comparator,
Collection<Iterator<? extends E>> iterators) {
return new CollatingIterator<E>(comparator, iterators);
}
// Object Graph
@ -596,8 +601,8 @@ public class IteratorUtils {
* @return a new object graph iterator
* @since Commons Collections 3.1
*/
public static Iterator objectGraphIterator(Object root, Transformer transformer) {
return new ObjectGraphIterator(root, transformer);
public static <E> Iterator<E> objectGraphIterator(E root, Transformer<? super E, ? extends E> transformer) {
return new ObjectGraphIterator<E>(root, transformer);
}
// Transformed
@ -613,14 +618,14 @@ public class IteratorUtils {
* @return a new transforming iterator
* @throws NullPointerException if either parameter is null
*/
public static Iterator transformedIterator(Iterator iterator, Transformer transform) {
public static <I, O> Iterator<O> transformedIterator(Iterator<? extends I> iterator, Transformer<? super I, ? extends O> transform) {
if (iterator == null) {
throw new NullPointerException("Iterator must not be null");
}
if (transform == null) {
throw new NullPointerException("Transformer must not be null");
}
return new TransformIterator(iterator, transform);
return new TransformIterator<I, O>(iterator, transform);
}
// Filtered
@ -636,14 +641,14 @@ public class IteratorUtils {
* @return a new filtered iterator
* @throws NullPointerException if either parameter is null
*/
public static Iterator filteredIterator(Iterator iterator, Predicate predicate) {
public static <E> Iterator<E> filteredIterator(Iterator<? extends E> iterator, Predicate<? super E> predicate) {
if (iterator == null) {
throw new NullPointerException("Iterator must not be null");
}
if (predicate == null) {
throw new NullPointerException("Predicate must not be null");
}
return new FilterIterator(iterator, predicate);
return new FilterIterator<E>(iterator, predicate);
}
/**
@ -657,14 +662,14 @@ public class IteratorUtils {
* @return a new filtered iterator
* @throws NullPointerException if either parameter is null
*/
public static ListIterator filteredListIterator(ListIterator listIterator, Predicate predicate) {
public static <E> ListIterator<E> filteredListIterator(ListIterator<? extends E> listIterator, Predicate<? super E> predicate) {
if (listIterator == null) {
throw new NullPointerException("ListIterator must not be null");
}
if (predicate == null) {
throw new NullPointerException("Predicate must not be null");
}
return new FilterListIterator(listIterator, predicate);
return new FilterListIterator<E>(listIterator, predicate);
}
// Looping
@ -680,11 +685,11 @@ public class IteratorUtils {
* @return a new looping iterator
* @throws NullPointerException if the collection is null
*/
public static ResettableIterator loopingIterator(Collection coll) {
public static <E> ResettableIterator<E> loopingIterator(Collection<? extends E> coll) {
if (coll == null) {
throw new NullPointerException("Collection must not be null");
}
return new LoopingIterator(coll);
return new LoopingIterator<E>(coll);
}
/**
@ -698,13 +703,13 @@ public class IteratorUtils {
* @throws NullPointerException if the list is null
* @since Commons Collections 3.2
*/
public static ResettableListIterator loopingListIterator(List list) {
public static <E> ResettableListIterator<E> loopingListIterator(List<E> list) {
if (list == null) {
throw new NullPointerException("List must not be null");
}
return new LoopingListIterator(list);
return new LoopingListIterator<E>(list);
}
// Views
//-----------------------------------------------------------------------
/**
@ -713,11 +718,11 @@ public class IteratorUtils {
* @param enumeration the enumeration to use
* @return a new iterator
*/
public static Iterator asIterator(Enumeration enumeration) {
public static <E> Iterator<E> asIterator(Enumeration<? extends E> enumeration) {
if (enumeration == null) {
throw new NullPointerException("Enumeration must not be null");
}
return new EnumerationIterator(enumeration);
return new EnumerationIterator<E>(enumeration);
}
/**
@ -728,14 +733,14 @@ public class IteratorUtils {
* @param removeCollection the collection to remove elements from
* @return a new iterator
*/
public static Iterator asIterator(Enumeration enumeration, Collection removeCollection) {
public static <E> Iterator<E> asIterator(Enumeration<? extends E> enumeration, Collection<? super E> removeCollection) {
if (enumeration == null) {
throw new NullPointerException("Enumeration must not be null");
}
if (removeCollection == null) {
throw new NullPointerException("Collection must not be null");
}
return new EnumerationIterator(enumeration, removeCollection);
return new EnumerationIterator<E>(enumeration, removeCollection);
}
/**
@ -745,11 +750,11 @@ public class IteratorUtils {
* @return a new enumeration
* @throws NullPointerException if iterator is null
*/
public static Enumeration asEnumeration(Iterator iterator) {
public static <E> Enumeration<E> asEnumeration(Iterator<? extends E> iterator) {
if (iterator == null) {
throw new NullPointerException("Iterator must not be null");
}
return new IteratorEnumeration(iterator);
return new IteratorEnumeration<E>(iterator);
}
/**
@ -762,11 +767,11 @@ public class IteratorUtils {
* @return a new iterator
* @throws NullPointerException if iterator parameter is null
*/
public static ListIterator toListIterator(Iterator iterator) {
public static <E> ListIterator<E> toListIterator(Iterator<? extends E> iterator) {
if (iterator == null) {
throw new NullPointerException("Iterator must not be null");
}
return new ListIteratorWrapper(iterator);
return new ListIteratorWrapper<E>(iterator);
}
/**
@ -779,14 +784,14 @@ public class IteratorUtils {
* @return an array of the iterator contents
* @throws NullPointerException if iterator parameter is null
*/
public static Object[] toArray(Iterator iterator) {
public static Object[] toArray(Iterator<?> iterator) {
if (iterator == null) {
throw new NullPointerException("Iterator must not be null");
}
List list = toList(iterator, 100);
List<?> list = toList(iterator, 100);
return list.toArray();
}
/**
* Gets an array based on an iterator.
* <p>
@ -800,15 +805,16 @@ public class IteratorUtils {
* @throws NullPointerException if arrayClass is null
* @throws ClassCastException if the arrayClass is invalid
*/
public static Object[] toArray(Iterator iterator, Class arrayClass) {
@SuppressWarnings("unchecked")
public static <E> E[] toArray(Iterator<? extends E> iterator, Class<E> arrayClass) {
if (iterator == null) {
throw new NullPointerException("Iterator must not be null");
}
if (arrayClass == null) {
throw new NullPointerException("Array class must not be null");
}
List list = toList(iterator, 100);
return list.toArray((Object[]) Array.newInstance(arrayClass, list.size()));
List<E> list = toList(iterator, 100);
return list.toArray((E[]) Array.newInstance(arrayClass, list.size()));
}
/**
@ -821,10 +827,10 @@ public class IteratorUtils {
* @return a list of the iterator contents
* @throws NullPointerException if iterator parameter is null
*/
public static List toList(Iterator iterator) {
public static <E> List<E> toList(Iterator<? extends E> iterator) {
return toList(iterator, 10);
}
/**
* Gets a list based on an iterator.
* <p>
@ -837,14 +843,14 @@ public class IteratorUtils {
* @throws NullPointerException if iterator parameter is null
* @throws IllegalArgumentException if the size is less than 1
*/
public static List toList(Iterator iterator, int estimatedSize) {
public static <E> List<E> toList(Iterator<? extends E> iterator, int estimatedSize) {
if (iterator == null) {
throw new NullPointerException("Iterator must not be null");
}
if (estimatedSize < 1) {
throw new IllegalArgumentException("Estimated size must be greater than 0");
}
List list = new ArrayList(estimatedSize);
List<E> list = new ArrayList<E>(estimatedSize);
while (iterator.hasNext()) {
list.add(iterator.next());
}
@ -854,7 +860,7 @@ public class IteratorUtils {
/**
* Gets a suitable Iterator for the given object.
* <p>
* This method can handles objects as follows
* This method can handle objects as follows
* <ul>
* <li>null - empty iterator
* <li>Iterator - returned directly
@ -870,45 +876,44 @@ public class IteratorUtils {
* @param obj the object to convert to an iterator
* @return a suitable iterator, never null
*/
public static Iterator getIterator(Object obj) {
@SuppressWarnings("unchecked")
public static Iterator<?> getIterator(Object obj) {
if (obj == null) {
return emptyIterator();
} else if (obj instanceof Iterator) {
return (Iterator) obj;
} else if (obj instanceof Collection) {
return ((Collection) obj).iterator();
} else if (obj instanceof Object[]) {
return new ObjectArrayIterator((Object[]) obj);
} else if (obj instanceof Enumeration) {
return new EnumerationIterator((Enumeration) obj);
} else if (obj instanceof Map) {
return ((Map) obj).values().iterator();
} else if (obj instanceof Dictionary) {
return new EnumerationIterator(((Dictionary) obj).elements());
} else if (obj != null && obj.getClass().isArray()) {
return new ArrayIterator(obj);
} else {
try {
Method method = obj.getClass().getMethod("iterator", (Class[]) null);
if (Iterator.class.isAssignableFrom(method.getReturnType())) {
Iterator it = (Iterator) method.invoke(obj, (Object[]) null);
if (it != null) {
return it;
}
}
} catch (Exception ex) {
// ignore
}
return singletonIterator(obj);
}
if (obj instanceof Iterator) {
return (Iterator) obj;
}
if (obj instanceof Collection) {
return ((Collection) obj).iterator();
}
if (obj instanceof Object[]) {
return new ObjectArrayIterator((Object[]) obj);
}
if (obj instanceof Enumeration) {
return new EnumerationIterator((Enumeration) obj);
}
if (obj instanceof Map) {
return ((Map) obj).values().iterator();
}
if (obj instanceof Dictionary) {
return new EnumerationIterator(((Dictionary) obj).elements());
}
if (obj != null && obj.getClass().isArray()) {
return new ArrayIterator(obj);
}
try {
Method method = obj.getClass().getMethod("iterator", (Class[]) null);
if (Iterator.class.isAssignableFrom(method.getReturnType())) {
Iterator it = (Iterator) method.invoke(obj, (Object[]) null);
if (it != null) {
return it;
}
}
} catch (Exception ex) {
// ignore
}
return singletonIterator(obj);
}
}

View File

@ -49,8 +49,8 @@ public class ListUtils {
* This uses the {@link Collections Collections} implementation
* and is provided for completeness.
*/
public static final List EMPTY_LIST = Collections.EMPTY_LIST;
public static final List<Object> EMPTY_LIST = Collections.<Object>emptyList();
/**
* <code>ListUtils</code> should not normally be instantiated.
*/
@ -67,18 +67,14 @@ public class ListUtils {
* @return the intersection of those two lists
* @throws NullPointerException if either list is null
*/
public static List intersection(final List list1, final List list2) {
final List result = new ArrayList();
final Iterator iterator = list2.iterator();
public static <E> List<E> intersection(final List<? extends E> list1, final List<? extends E> list2) {
final List<E> result = new ArrayList<E>();
while (iterator.hasNext()) {
final Object o = iterator.next();
if (list1.contains(o)) {
result.add(o);
for (E e : list2) {
if (list1.contains(e)) {
result.add(e);
}
}
return result;
}
@ -97,14 +93,11 @@ public class ListUtils {
* @return a new list containing the results
* @throws NullPointerException if either list is null
*/
public static List subtract(final List list1, final List list2) {
final ArrayList result = new ArrayList(list1);
final Iterator iterator = list2.iterator();
while (iterator.hasNext()) {
result.remove(iterator.next());
public static <E> List<E> subtract(final List<E> list1, final List<? extends E> list2) {
final ArrayList<E> result = new ArrayList<E>(list1);
for (E e : list2) {
result.remove(e);
}
return result;
}
@ -117,7 +110,7 @@ public class ListUtils {
* @return a new list containing the sum of those lists
* @throws NullPointerException if either list is null
*/
public static List sum(final List list1, final List list2) {
public static <E> List<E> sum(final List<? extends E> list1, final List<? extends E> list2) {
return subtract(union(list1, list2), intersection(list1, list2));
}
@ -131,8 +124,8 @@ public class ListUtils {
* @return a new list containing the union of those lists
* @throws NullPointerException if either list is null
*/
public static List union(final List list1, final List list2) {
final ArrayList result = new ArrayList(list1);
public static <E> List<E> union(final List<? extends E> list1, final List<? extends E> list2) {
final ArrayList<E> result = new ArrayList<E>(list1);
result.addAll(list2);
return result;
}
@ -166,7 +159,7 @@ public class ListUtils {
* @param list2 the second list, may be null
* @return whether the lists are equal by value comparison
*/
public static boolean isEqualList(final Collection list1, final Collection list2) {
public static boolean isEqualList(final Collection<?> list1, final Collection<?> list2) {
if (list1 == list2) {
return true;
}
@ -174,8 +167,8 @@ public class ListUtils {
return false;
}
Iterator it1 = list1.iterator();
Iterator it2 = list2.iterator();
Iterator<?> it1 = list1.iterator();
Iterator<?> it2 = list2.iterator();
Object obj1 = null;
Object obj2 = null;
@ -306,7 +299,7 @@ public class ListUtils {
* @return an unmodifiable list backed by the given list
* @throws IllegalArgumentException if the list is null
*/
public static <E> List unmodifiableList(List<E> list) {
public static <E> List<E> unmodifiableList(List<E> list) {
return UnmodifiableList.decorate(list);
}
@ -339,7 +332,7 @@ public class ListUtils {
* @return a transformed list backed by the given list
* @throws IllegalArgumentException if the List or Transformer is null
*/
public static List transformedList(List list, Transformer transformer) {
public static <E> List<E> transformedList(List<E> list, Transformer<? super E, ? extends E> transformer) {
return TransformedList.decorate(list, transformer);
}
@ -372,7 +365,7 @@ public class ListUtils {
* @return a lazy list backed by the given list
* @throws IllegalArgumentException if the List or Factory is null
*/
public static List lazyList(List list, Factory factory) {
public static <E> List<E> lazyList(List<E> list, Factory<? extends E> factory) {
return LazyList.decorate(list, factory);
}
@ -386,7 +379,7 @@ public class ListUtils {
* @return a fixed-size list backed by that list
* @throws IllegalArgumentException if the List is null
*/
public static List fixedSizeList(List list) {
public static <E> List<E> fixedSizeList(List<E> list) {
return FixedSizeList.decorate(list);
}

View File

@ -19,6 +19,7 @@ package org.apache.commons.collections;
import java.io.PrintStream;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
@ -91,12 +92,14 @@ public class MapUtils {
* An empty unmodifiable map.
* This was not provided in JDK1.2.
*/
public static final Map EMPTY_MAP = UnmodifiableMap.decorate(new HashMap(1));
public static final Map<Object, Object> EMPTY_MAP = UnmodifiableMap.decorate(new HashMap<Object, Object>(1));
/**
* An empty unmodifiable sorted map.
* This is not provided in the JDK.
*/
public static final SortedMap EMPTY_SORTED_MAP = UnmodifiableSortedMap.decorate(new TreeMap());
public static final SortedMap<Object, Object> EMPTY_SORTED_MAP = UnmodifiableSortedMap.decorate(new TreeMap<Object, Object>());
/**
* String used to indent the verbose and debug Map prints.
*/
@ -107,7 +110,7 @@ public class MapUtils {
*/
public MapUtils() {
}
// Type safe getters
//-------------------------------------------------------------------------
/**
@ -117,7 +120,7 @@ public class MapUtils {
* @param key the key to look up
* @return the value in the Map, <code>null</code> if null map input
*/
public static Object getObject(final Map map, final Object key) {
public static <K, V> V getObject(final Map<? super K, V> map, final K key) {
if (map != null) {
return map.get(key);
}
@ -133,7 +136,7 @@ public class MapUtils {
* @param key the key to look up
* @return the value in the Map as a String, <code>null</code> if null map input
*/
public static String getString(final Map map, final Object key) {
public static <K> String getString(final Map<? super K, ?> map, final K key) {
if (map != null) {
Object answer = map.get(key);
if (answer != null) {
@ -157,17 +160,17 @@ public class MapUtils {
* @param key the key to look up
* @return the value in the Map as a Boolean, <code>null</code> if null map input
*/
public static Boolean getBoolean(final Map map, final Object key) {
public static <K> Boolean getBoolean(final Map<? super K, ?> map, final K key) {
if (map != null) {
Object answer = map.get(key);
if (answer != null) {
if (answer instanceof Boolean) {
return (Boolean) answer;
} else if (answer instanceof String) {
}
if (answer instanceof String) {
return new Boolean((String) answer);
} else if (answer instanceof Number) {
}
if (answer instanceof Number) {
Number n = (Number) answer;
return (n.intValue() != 0) ? Boolean.TRUE : Boolean.FALSE;
}
@ -189,18 +192,17 @@ public class MapUtils {
* @param key the key to look up
* @return the value in the Map as a Number, <code>null</code> if null map input
*/
public static Number getNumber(final Map map, final Object key) {
public static <K> Number getNumber(final Map<? super K, ?> map, final K key) {
if (map != null) {
Object answer = map.get(key);
if (answer != null) {
if (answer instanceof Number) {
return (Number) answer;
} else if (answer instanceof String) {
}
if (answer instanceof String) {
try {
String text = (String) answer;
return NumberFormat.getInstance().parse(text);
} catch (ParseException e) {
logInfo(e);
}
@ -219,11 +221,12 @@ public class MapUtils {
* @param key the key to look up
* @return the value in the Map as a Byte, <code>null</code> if null map input
*/
public static Byte getByte(final Map map, final Object key) {
public static <K> Byte getByte(final Map<? super K, ?> map, final K key) {
Number answer = getNumber(map, key);
if (answer == null) {
return null;
} else if (answer instanceof Byte) {
}
if (answer instanceof Byte) {
return (Byte) answer;
}
return new Byte(answer.byteValue());
@ -238,11 +241,12 @@ public class MapUtils {
* @param key the key to look up
* @return the value in the Map as a Short, <code>null</code> if null map input
*/
public static Short getShort(final Map map, final Object key) {
public static <K> Short getShort(final Map<? super K, ?> map, final K key) {
Number answer = getNumber(map, key);
if (answer == null) {
return null;
} else if (answer instanceof Short) {
}
if (answer instanceof Short) {
return (Short) answer;
}
return new Short(answer.shortValue());
@ -257,11 +261,12 @@ public class MapUtils {
* @param key the key to look up
* @return the value in the Map as a Integer, <code>null</code> if null map input
*/
public static Integer getInteger(final Map map, final Object key) {
public static <K> Integer getInteger(final Map<? super K, ?> map, final K key) {
Number answer = getNumber(map, key);
if (answer == null) {
return null;
} else if (answer instanceof Integer) {
}
if (answer instanceof Integer) {
return (Integer) answer;
}
return new Integer(answer.intValue());
@ -276,11 +281,12 @@ public class MapUtils {
* @param key the key to look up
* @return the value in the Map as a Long, <code>null</code> if null map input
*/
public static Long getLong(final Map map, final Object key) {
public static <K> Long getLong(final Map<? super K, ?> map, final K key) {
Number answer = getNumber(map, key);
if (answer == null) {
return null;
} else if (answer instanceof Long) {
}
if (answer instanceof Long) {
return (Long) answer;
}
return new Long(answer.longValue());
@ -295,11 +301,12 @@ public class MapUtils {
* @param key the key to look up
* @return the value in the Map as a Float, <code>null</code> if null map input
*/
public static Float getFloat(final Map map, final Object key) {
public static <K> Float getFloat(final Map<? super K, ?> map, final K key) {
Number answer = getNumber(map, key);
if (answer == null) {
return null;
} else if (answer instanceof Float) {
}
if (answer instanceof Float) {
return (Float) answer;
}
return new Float(answer.floatValue());
@ -314,11 +321,12 @@ public class MapUtils {
* @param key the key to look up
* @return the value in the Map as a Double, <code>null</code> if null map input
*/
public static Double getDouble(final Map map, final Object key) {
public static <K> Double getDouble(final Map<? super K, ?> map, final K key) {
Number answer = getNumber(map, key);
if (answer == null) {
return null;
} else if (answer instanceof Double) {
}
if (answer instanceof Double) {
return (Double) answer;
}
return new Double(answer.doubleValue());
@ -334,11 +342,11 @@ public class MapUtils {
* @param key the key to look up
* @return the value in the Map as a Map, <code>null</code> if null map input
*/
public static Map getMap(final Map map, final Object key) {
public static <K> Map<?, ?> getMap(final Map<? super K, ?> map, final K key) {
if (map != null) {
Object answer = map.get(key);
if (answer != null && answer instanceof Map) {
return (Map) answer;
return (Map<?, ?>) answer;
}
}
return null;
@ -356,10 +364,10 @@ public class MapUtils {
* @return the value in the map, or defaultValue if the original value
* is null or the map is null
*/
public static Object getObject( Map map, Object key, Object defaultValue ) {
if ( map != null ) {
Object answer = map.get( key );
if ( answer != null ) {
public static <K, V> V getObject(Map<K, V> map, K key, V defaultValue) {
if (map != null) {
V answer = map.get(key);
if (answer != null) {
return answer;
}
}
@ -378,9 +386,9 @@ public class MapUtils {
* original value is null, the map is null or the string conversion
* fails
*/
public static String getString( Map map, Object key, String defaultValue ) {
String answer = getString( map, key );
if ( answer == null ) {
public static <K> String getString(Map<? super K, ?> map, K key, String defaultValue) {
String answer = getString(map, key);
if (answer == null) {
answer = defaultValue;
}
return answer;
@ -398,9 +406,9 @@ public class MapUtils {
* original value is null, the map is null or the boolean conversion
* fails
*/
public static Boolean getBoolean( Map map, Object key, Boolean defaultValue ) {
Boolean answer = getBoolean( map, key );
if ( answer == null ) {
public static <K> Boolean getBoolean(Map<? super K, ?> map, K key, Boolean defaultValue) {
Boolean answer = getBoolean(map, key);
if (answer == null) {
answer = defaultValue;
}
return answer;
@ -418,9 +426,9 @@ public class MapUtils {
* original value is null, the map is null or the number conversion
* fails
*/
public static Number getNumber( Map map, Object key, Number defaultValue ) {
Number answer = getNumber( map, key );
if ( answer == null ) {
public static <K> Number getNumber(Map<? super K, ?> map, K key, Number defaultValue) {
Number answer = getNumber(map, key);
if (answer == null) {
answer = defaultValue;
}
return answer;
@ -438,9 +446,9 @@ public class MapUtils {
* original value is null, the map is null or the number conversion
* fails
*/
public static Byte getByte( Map map, Object key, Byte defaultValue ) {
Byte answer = getByte( map, key );
if ( answer == null ) {
public static <K> Byte getByte(Map<? super K, ?> map, K key, Byte defaultValue) {
Byte answer = getByte(map, key);
if (answer == null) {
answer = defaultValue;
}
return answer;
@ -458,9 +466,9 @@ public class MapUtils {
* original value is null, the map is null or the number conversion
* fails
*/
public static Short getShort( Map map, Object key, Short defaultValue ) {
Short answer = getShort( map, key );
if ( answer == null ) {
public static <K> Short getShort(Map<? super K, ?> map, K key, Short defaultValue) {
Short answer = getShort(map, key);
if (answer == null) {
answer = defaultValue;
}
return answer;
@ -478,9 +486,9 @@ public class MapUtils {
* original value is null, the map is null or the number conversion
* fails
*/
public static Integer getInteger( Map map, Object key, Integer defaultValue ) {
Integer answer = getInteger( map, key );
if ( answer == null ) {
public static <K> Integer getInteger(Map<? super K, ?> map, K key, Integer defaultValue) {
Integer answer = getInteger(map, key);
if (answer == null) {
answer = defaultValue;
}
return answer;
@ -498,9 +506,9 @@ public class MapUtils {
* original value is null, the map is null or the number conversion
* fails
*/
public static Long getLong( Map map, Object key, Long defaultValue ) {
Long answer = getLong( map, key );
if ( answer == null ) {
public static <K> Long getLong(Map<? super K, ?> map, K key, Long defaultValue) {
Long answer = getLong(map, key);
if (answer == null) {
answer = defaultValue;
}
return answer;
@ -518,9 +526,9 @@ public class MapUtils {
* original value is null, the map is null or the number conversion
* fails
*/
public static Float getFloat( Map map, Object key, Float defaultValue ) {
Float answer = getFloat( map, key );
if ( answer == null ) {
public static <K> Float getFloat(Map<? super K, ?> map, K key, Float defaultValue) {
Float answer = getFloat(map, key);
if (answer == null) {
answer = defaultValue;
}
return answer;
@ -538,9 +546,9 @@ public class MapUtils {
* original value is null, the map is null or the number conversion
* fails
*/
public static Double getDouble( Map map, Object key, Double defaultValue ) {
Double answer = getDouble( map, key );
if ( answer == null ) {
public static <K> Double getDouble(Map<? super K, ?> map, K key, Double defaultValue) {
Double answer = getDouble(map, key);
if (answer == null) {
answer = defaultValue;
}
return answer;
@ -558,14 +566,13 @@ public class MapUtils {
* original value is null, the map is null or the map conversion
* fails
*/
public static Map getMap( Map map, Object key, Map defaultValue ) {
Map answer = getMap( map, key );
if ( answer == null ) {
public static <K> Map<?, ?> getMap(Map<? super K, ?> map, K key, Map<?, ?> defaultValue) {
Map<?, ?> answer = getMap(map, key);
if (answer == null) {
answer = defaultValue;
}
return answer;
}
// Type safe primitive getters
//-------------------------------------------------------------------------
@ -583,12 +590,8 @@ public class MapUtils {
* @param key the key to look up
* @return the value in the Map as a Boolean, <code>false</code> if null map input
*/
public static boolean getBooleanValue(final Map map, final Object key) {
Boolean booleanObject = getBoolean(map, key);
if (booleanObject == null) {
return false;
}
return booleanObject.booleanValue();
public static <K> boolean getBooleanValue(final Map<? super K, ?> map, final K key) {
return Boolean.TRUE.equals(getBoolean(map, key));
}
/**
@ -600,7 +603,7 @@ public class MapUtils {
* @param key the key to look up
* @return the value in the Map as a byte, <code>0</code> if null map input
*/
public static byte getByteValue(final Map map, final Object key) {
public static <K> byte getByteValue(final Map<? super K, ?> map, final K key) {
Byte byteObject = getByte(map, key);
if (byteObject == null) {
return 0;
@ -617,7 +620,7 @@ public class MapUtils {
* @param key the key to look up
* @return the value in the Map as a short, <code>0</code> if null map input
*/
public static short getShortValue(final Map map, final Object key) {
public static <K> short getShortValue(final Map<? super K, ?> map, final K key) {
Short shortObject = getShort(map, key);
if (shortObject == null) {
return 0;
@ -634,7 +637,7 @@ public class MapUtils {
* @param key the key to look up
* @return the value in the Map as an int, <code>0</code> if null map input
*/
public static int getIntValue(final Map map, final Object key) {
public static <K> int getIntValue(final Map<? super K, ?> map, final K key) {
Integer integerObject = getInteger(map, key);
if (integerObject == null) {
return 0;
@ -651,7 +654,7 @@ public class MapUtils {
* @param key the key to look up
* @return the value in the Map as a long, <code>0L</code> if null map input
*/
public static long getLongValue(final Map map, final Object key) {
public static <K> long getLongValue(final Map<? super K, ?> map, final K key) {
Long longObject = getLong(map, key);
if (longObject == null) {
return 0L;
@ -668,7 +671,7 @@ public class MapUtils {
* @param key the key to look up
* @return the value in the Map as a float, <code>0.0F</code> if null map input
*/
public static float getFloatValue(final Map map, final Object key) {
public static <K> float getFloatValue(final Map<? super K, ?> map, final K key) {
Float floatObject = getFloat(map, key);
if (floatObject == null) {
return 0f;
@ -685,7 +688,7 @@ public class MapUtils {
* @param key the key to look up
* @return the value in the Map as a double, <code>0.0</code> if null map input
*/
public static double getDoubleValue(final Map map, final Object key) {
public static <K> double getDoubleValue(final Map<? super K, ?> map, final K key) {
Double doubleObject = getDouble(map, key);
if (doubleObject == null) {
return 0d;
@ -712,7 +715,7 @@ public class MapUtils {
* conversion fails
* @return the value in the Map as a Boolean, <code>defaultValue</code> if null map input
*/
public static boolean getBooleanValue(final Map map, final Object key, boolean defaultValue) {
public static <K> boolean getBooleanValue(final Map<? super K, ?> map, final K key, boolean defaultValue) {
Boolean booleanObject = getBoolean(map, key);
if (booleanObject == null) {
return defaultValue;
@ -732,7 +735,7 @@ public class MapUtils {
* conversion fails
* @return the value in the Map as a byte, <code>defaultValue</code> if null map input
*/
public static byte getByteValue(final Map map, final Object key, byte defaultValue) {
public static <K> byte getByteValue(final Map<? super K, ?> map, final K key, byte defaultValue) {
Byte byteObject = getByte(map, key);
if (byteObject == null) {
return defaultValue;
@ -752,7 +755,7 @@ public class MapUtils {
* conversion fails
* @return the value in the Map as a short, <code>defaultValue</code> if null map input
*/
public static short getShortValue(final Map map, final Object key, short defaultValue) {
public static <K> short getShortValue(final Map<? super K, ?> map, final K key, short defaultValue) {
Short shortObject = getShort(map, key);
if (shortObject == null) {
return defaultValue;
@ -772,7 +775,7 @@ public class MapUtils {
* conversion fails
* @return the value in the Map as an int, <code>defaultValue</code> if null map input
*/
public static int getIntValue(final Map map, final Object key, int defaultValue) {
public static <K> int getIntValue(final Map<? super K, ?> map, final K key, int defaultValue) {
Integer integerObject = getInteger(map, key);
if (integerObject == null) {
return defaultValue;
@ -792,7 +795,7 @@ public class MapUtils {
* conversion fails
* @return the value in the Map as a long, <code>defaultValue</code> if null map input
*/
public static long getLongValue(final Map map, final Object key, long defaultValue) {
public static <K> long getLongValue(final Map<? super K, ?> map, final K key, long defaultValue) {
Long longObject = getLong(map, key);
if (longObject == null) {
return defaultValue;
@ -812,7 +815,7 @@ public class MapUtils {
* conversion fails
* @return the value in the Map as a float, <code>defaultValue</code> if null map input
*/
public static float getFloatValue(final Map map, final Object key, float defaultValue) {
public static <K> float getFloatValue(final Map<? super K, ?> map, final K key, float defaultValue) {
Float floatObject = getFloat(map, key);
if (floatObject == null) {
return defaultValue;
@ -832,7 +835,7 @@ public class MapUtils {
* conversion fails
* @return the value in the Map as a double, <code>defaultValue</code> if null map input
*/
public static double getDoubleValue(final Map map, final Object key, double defaultValue) {
public static <K> double getDoubleValue(final Map<? super K, ?> map, final K key, double defaultValue) {
Double doubleObject = getDouble(map, key);
if (doubleObject == null) {
return defaultValue;
@ -849,11 +852,11 @@ public class MapUtils {
* @param map the map to convert to a Properties object, may not be null
* @return the properties object
*/
public static Properties toProperties(final Map map) {
public static <K, V> Properties toProperties(final Map<K, V> map) {
Properties answer = new Properties();
if (map != null) {
for (Iterator iter = map.entrySet().iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
for (Iterator<Map.Entry<K, V>> iter = map.entrySet().iterator(); iter.hasNext();) {
Map.Entry<?, ?> entry = iter.next();
Object key = entry.getKey();
Object value = entry.getValue();
answer.put(key, value);
@ -869,16 +872,16 @@ public class MapUtils {
* @return the hashmap containing the data
* @throws NullPointerException if the bundle is null
*/
public static Map toMap(final ResourceBundle resourceBundle) {
Enumeration enumeration = resourceBundle.getKeys();
Map map = new HashMap();
public static Map<String, Object> toMap(final ResourceBundle resourceBundle) {
Enumeration<String> enumeration = resourceBundle.getKeys();
Map<String, Object> map = new HashMap<String, Object>();
while (enumeration.hasMoreElements()) {
String key = (String) enumeration.nextElement();
Object value = resourceBundle.getObject(key);
map.put(key, value);
}
return map;
}
@ -905,9 +908,9 @@ public class MapUtils {
public static void verbosePrint(
final PrintStream out,
final Object label,
final Map map) {
final Map<?, ?> map) {
verbosePrintInternal(out, label, map, new ArrayStack(), false);
verbosePrintInternal(out, label, map, new ArrayStack<Map<?, ?>>(), false);
}
/**
@ -931,9 +934,9 @@ public class MapUtils {
public static void debugPrint(
final PrintStream out,
final Object label,
final Map map) {
final Map<?, ?> map) {
verbosePrintInternal(out, label, map, new ArrayStack(), true);
verbosePrintInternal(out, label, map, new ArrayStack<Map<?, ?>>(), true);
}
// Implementation methods
@ -975,8 +978,8 @@ public class MapUtils {
private static void verbosePrintInternal(
final PrintStream out,
final Object label,
final Map map,
final ArrayStack lineage,
final Map<?, ?> map,
final ArrayStack<Map<?, ?>> lineage,
final boolean debug) {
printIndent(out, lineage.size());
@ -999,15 +1002,14 @@ public class MapUtils {
lineage.push(map);
for (Iterator it = map.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
for (Map.Entry<?, ?> entry : map.entrySet()) {
Object childKey = entry.getKey();
Object childValue = entry.getValue();
if (childValue instanceof Map && !lineage.contains(childValue)) {
verbosePrintInternal(
out,
(childKey == null ? "null" : childKey),
(Map) childValue,
(Map<?, ?>) childValue,
lineage,
debug);
} else {
@ -1026,7 +1028,7 @@ public class MapUtils {
+ (lineage.size() - 1 - lineageIndex - 1)
+ "] Map)");
}
if (debug && childValue != null) {
out.print(' ');
out.println(childValue.getClass().getName());
@ -1035,7 +1037,7 @@ public class MapUtils {
}
}
}
lineage.pop();
printIndent(out, lineage.size());
@ -1052,7 +1054,7 @@ public class MapUtils {
out.print(INDENT_STRING);
}
}
// Misc
//-----------------------------------------------------------------------
/**
@ -1068,15 +1070,15 @@ public class MapUtils {
* @return a new HashMap containing the inverted data
* @throws NullPointerException if the map is null
*/
public static Map invertMap(Map map) {
Map out = new HashMap(map.size());
for (Iterator it = map.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
public static <K, V> Map<V, K> invertMap(Map<K, V> map) {
Map<V, K> out = new HashMap<V, K>(map.size());
for (Iterator<Map.Entry<K, V>> it = map.entrySet().iterator(); it.hasNext();) {
Map.Entry<K, V> entry = it.next();
out.put(entry.getValue(), entry.getKey());
}
return out;
}
//-----------------------------------------------------------------------
/**
* Protects against adding null values to a map.
@ -1089,18 +1091,16 @@ public class MapUtils {
* which should be held in the same way in the map.
* <p>
* Keys are not validated.
* Note that this method can be used to circumvent the map's
* value type at runtime.
*
* @param map the map to add to, may not be null
* @param key the key
* @param value the value, null converted to ""
* @throws NullPointerException if the map is null
*/
public static void safeAddToMap(Map map, Object key, Object value) throws NullPointerException {
if (value == null) {
map.put(key, "");
} else {
map.put(key, value);
}
public static <K> void safeAddToMap(Map<? super K, Object> map, K key, Object value) throws NullPointerException {
map.put(key, value == null ? "" : value);
}
//-----------------------------------------------------------------------
@ -1151,7 +1151,8 @@ public class MapUtils {
* @throws ClassCastException if the array contents is mixed
* @since Commons Collections 3.2
*/
public static Map putAll(Map map, Object[] array) {
@SuppressWarnings("unchecked")
public static <K, V> Map<K, V> putAll(Map<K, V> map, Object[] array) {
map.size(); // force NPE
if (array == null || array.length == 0) {
return map;
@ -1159,12 +1160,12 @@ public class MapUtils {
Object obj = array[0];
if (obj instanceof Map.Entry) {
for (int i = 0; i < array.length; i++) {
Map.Entry entry = (Map.Entry) array[i];
Map.Entry<K, V> entry = (Map.Entry<K, V>) array[i];
map.put(entry.getKey(), entry.getValue());
}
} else if (obj instanceof KeyValue) {
for (int i = 0; i < array.length; i++) {
KeyValue keyval = (KeyValue) array[i];
KeyValue<K, V> keyval = (KeyValue<K, V>) array[i];
map.put(keyval.getKey(), keyval.getValue());
}
} else if (obj instanceof Object[]) {
@ -1173,11 +1174,11 @@ public class MapUtils {
if (sub == null || sub.length < 2) {
throw new IllegalArgumentException("Invalid array element: " + i);
}
map.put(sub[0], sub[1]);
map.put((K) sub[0], (V) sub[1]);
}
} else {
for (int i = 0; i < array.length - 1;) {
map.put(array[i++], array[i++]);
map.put((K) array[i++], (V) array[i++]);
}
}
return map;
@ -1193,6 +1194,7 @@ public class MapUtils {
* @return true if empty or null
* @since Commons Collections 3.2
*/
@SuppressWarnings("unchecked")
public static boolean isEmpty(Map map) {
return (map == null || map.isEmpty());
}
@ -1206,6 +1208,7 @@ public class MapUtils {
* @return true if non-null and non-empty
* @since Commons Collections 3.2
*/
@SuppressWarnings("unchecked")
public static boolean isNotEmpty(Map map) {
return !MapUtils.isEmpty(map);
}
@ -1235,7 +1238,7 @@ public class MapUtils {
* @return a synchronized map backed by the given map
* @throws IllegalArgumentException if the map is null
*/
public static Map synchronizedMap(Map map) {
public static <K, V> Map<K, V> synchronizedMap(Map<K, V> map) {
return Collections.synchronizedMap(map);
}
@ -1248,7 +1251,7 @@ public class MapUtils {
* @return an unmodifiable map backed by the given map
* @throws IllegalArgumentException if the map is null
*/
public static Map unmodifiableMap(Map map) {
public static <K, V> Map<K, V> unmodifiableMap(Map<K, V> map) {
return UnmodifiableMap.decorate(map);
}
@ -1267,7 +1270,7 @@ public class MapUtils {
* @return a predicated map backed by the given map
* @throws IllegalArgumentException if the Map is null
*/
public static Map predicatedMap(Map map, Predicate keyPred, Predicate valuePred) {
public static <K, V> Map<K, V> predicatedMap(Map<K, V> map, Predicate<? super K> keyPred, Predicate<? super V> valuePred) {
return PredicatedMap.decorate(map, keyPred, valuePred);
}
@ -1292,7 +1295,9 @@ public class MapUtils {
* @return a transformed map backed by the given map
* @throws IllegalArgumentException if the Map is null
*/
public static Map transformedMap(Map map, Transformer keyTransformer, Transformer valueTransformer) {
public static <K, V> Map<K, V> transformedMap(Map<K, V> map,
Transformer<? super K, ? extends K> keyTransformer,
Transformer<? super V, ? extends V> valueTransformer) {
return TransformedMap.decorate(map, keyTransformer, valueTransformer);
}
@ -1306,7 +1311,7 @@ public class MapUtils {
* @return a fixed-size map backed by that map
* @throws IllegalArgumentException if the Map is null
*/
public static Map fixedSizeMap(Map map) {
public static <K, V> Map<K, V> fixedSizeMap(Map<K, V> map) {
return FixedSizeMap.decorate(map);
}
@ -1338,8 +1343,8 @@ public class MapUtils {
* @return a lazy map backed by the given map
* @throws IllegalArgumentException if the Map or Factory is null
*/
public static Map lazyMap(Map map, Factory factory) {
return LazyMap.decorate(map, factory);
public static <K, V> Map<K, V> lazyMap(Map<K, V> map, Factory<? extends V> factory) {
return LazyMap.getLazyMap(map, factory);
}
/**
@ -1377,8 +1382,8 @@ public class MapUtils {
* @return a lazy map backed by the given map
* @throws IllegalArgumentException if the Map or Transformer is null
*/
public static Map lazyMap(Map map, Transformer transformerFactory) {
return LazyMap.decorate(map, transformerFactory);
public static <K, V> Map<K, V> lazyMap(Map<K, V> map, Transformer<? super K, ? extends V> transformerFactory) {
return LazyMap.getLazyMap(map, transformerFactory);
}
/**
@ -1392,7 +1397,7 @@ public class MapUtils {
* @return an ordered map backed by the given map
* @throws IllegalArgumentException if the Map is null
*/
public static Map orderedMap(Map map) {
public static <K, V> Map<K, V> orderedMap(Map<K, V> map) {
return ListOrderedMap.decorate(map);
}
@ -1405,8 +1410,8 @@ public class MapUtils {
* @see MultiValueMap
* @since Commons Collections 3.2
*/
public static Map multiValueMap(Map map) {
return MultiValueMap.decorate(map);
public static <K, V> MultiValueMap<K, V> multiValueMap(Map<K, ? super Collection<V>> map) {
return MultiValueMap.<K, V>decorate(map);
}
/**
@ -1420,7 +1425,7 @@ public class MapUtils {
* @see MultiValueMap
* @since Commons Collections 3.2
*/
public static Map multiValueMap(Map map, Class collectionClass) {
public static <K, V, C extends Collection<V>> MultiValueMap<K, V> multiValueMap(Map<K, C> map, Class<C> collectionClass) {
return MultiValueMap.decorate(map, collectionClass);
}
@ -1435,7 +1440,7 @@ public class MapUtils {
* @see MultiValueMap
* @since Commons Collections 3.2
*/
public static Map multiValueMap(Map map, Factory collectionFactory) {
public static <K, V, C extends Collection<V>> MultiValueMap<K, V> multiValueMap(Map<K, C> map, Factory<C> collectionFactory) {
return MultiValueMap.decorate(map, collectionFactory);
}
@ -1464,7 +1469,7 @@ public class MapUtils {
* @return a synchronized map backed by the given map
* @throws IllegalArgumentException if the map is null
*/
public static Map synchronizedSortedMap(SortedMap map) {
public static <K, V> SortedMap<K, V> synchronizedSortedMap(SortedMap<K, V> map) {
return Collections.synchronizedSortedMap(map);
}
@ -1477,7 +1482,7 @@ public class MapUtils {
* @return an unmodifiable map backed by the given map
* @throws IllegalArgumentException if the map is null
*/
public static Map unmodifiableSortedMap(SortedMap map) {
public static <K, V> SortedMap<K, V> unmodifiableSortedMap(SortedMap<K, V> map) {
return UnmodifiableSortedMap.decorate(map);
}
@ -1496,7 +1501,8 @@ public class MapUtils {
* @return a predicated map backed by the given map
* @throws IllegalArgumentException if the SortedMap is null
*/
public static SortedMap predicatedSortedMap(SortedMap map, Predicate keyPred, Predicate valuePred) {
public static <K, V> SortedMap<K, V> predicatedSortedMap(SortedMap<K, V> map,
Predicate<? super K> keyPred, Predicate<? super V> valuePred) {
return PredicatedSortedMap.decorate(map, keyPred, valuePred);
}
@ -1521,7 +1527,9 @@ public class MapUtils {
* @return a transformed map backed by the given map
* @throws IllegalArgumentException if the SortedMap is null
*/
public static SortedMap transformedSortedMap(SortedMap map, Transformer keyTransformer, Transformer valueTransformer) {
public static <K, V> SortedMap<K, V> transformedSortedMap(SortedMap<K, V> map,
Transformer<? super K, ? extends K> keyTransformer,
Transformer<? super V, ? extends V> valueTransformer) {
return TransformedSortedMap.decorate(map, keyTransformer, valueTransformer);
}
@ -1535,7 +1543,7 @@ public class MapUtils {
* @return a fixed-size map backed by that map
* @throws IllegalArgumentException if the SortedMap is null
*/
public static SortedMap fixedSizeSortedMap(SortedMap map) {
public static <K, V> SortedMap<K, V> fixedSizeSortedMap(SortedMap<K, V> map) {
return FixedSizeSortedMap.decorate(map);
}
@ -1568,8 +1576,9 @@ public class MapUtils {
* @return a lazy map backed by the given map
* @throws IllegalArgumentException if the SortedMap or Factory is null
*/
public static SortedMap lazySortedMap(SortedMap map, Factory factory) {
return LazySortedMap.decorate(map, factory);
public static <K, V> SortedMap<K, V> lazySortedMap(SortedMap<K, V> map,
Factory<? extends V> factory) {
return LazySortedMap.getLazySortedMap(map, factory);
}
/**
@ -1607,8 +1616,9 @@ public class MapUtils {
* @return a lazy map backed by the given map
* @throws IllegalArgumentException if the Map or Transformer is null
*/
public static SortedMap lazySortedMap(SortedMap map, Transformer transformerFactory) {
return LazySortedMap.decorate(map, transformerFactory);
public static <K, V> SortedMap<K, V> lazySortedMap(SortedMap<K, V> map,
Transformer<? super K, ? extends V> transformerFactory) {
return LazySortedMap.getLazySortedMap(map, transformerFactory);
}
}

View File

@ -47,7 +47,7 @@ import java.util.Map;
* @author James Strachan
* @author Stephen Colebourne
*/
public interface MultiMap extends Map {
public interface MultiMap<K, V> extends Map<K, Object> {
/**
* Removes a specific value from map.
@ -66,7 +66,7 @@ public interface MultiMap extends Map {
* @throws ClassCastException if the key or value is of an invalid type
* @throws NullPointerException if the key or value is null and null is invalid
*/
public Object remove(Object key, Object item);
public V remove(K key, V item);
//-----------------------------------------------------------------------
/**
@ -98,7 +98,7 @@ public interface MultiMap extends Map {
* @throws ClassCastException if the key is of an invalid type
* @throws NullPointerException if the key is null and null keys are invalid
*/
Object get(Object key);
Object get(K key);
/**
* Checks whether the map contains the value specified.
@ -129,7 +129,7 @@ public interface MultiMap extends Map {
* @throws NullPointerException if the key or value is null and null is invalid
* @throws IllegalArgumentException if the key or value is invalid
*/
Object put(Object key, Object value);
Object put(K key, Object value);
/**
* Removes all values associated with the specified key.
@ -144,7 +144,7 @@ public interface MultiMap extends Map {
* @throws ClassCastException if the key is of an invalid type
* @throws NullPointerException if the key is null and null keys are invalid
*/
Object remove(Object key);
Object remove(K key);
/**
* Gets a collection containing all the values in the map.
@ -155,6 +155,6 @@ public interface MultiMap extends Map {
*
* @return a collection view of the values contained in this map
*/
Collection values();
Collection<Object> values();
}

View File

@ -47,20 +47,6 @@ public interface OrderedBidiMap<K, V> extends BidiMap<K, V>, OrderedMap<K, V> {
*
* @return an inverted bidirectional map
*/
public BidiMap<V, K> inverseBidiMap();
/**
* Gets a view of this map where the keys and values are reversed.
* <p>
* Changes to one map will be visible in the other and vice versa.
* This enables both directions of the map to be accessed equally.
* <p>
* Implementations should seek to avoid creating a new object every time this
* method is called. See <code>AbstractMap.values()</code> etc. Calling this
* method on the inverse map should return the original.
*
* @return an inverted bidirectional map
*/
public OrderedBidiMap<V, K> inverseOrderedBidiMap();
public OrderedBidiMap<V, K> inverseBidiMap();
}

View File

@ -37,7 +37,7 @@ public interface OrderedMap<K, V> extends IterableMap<K, V> {
*
* @return a map iterator
*/
OrderedMapIterator<K, V> orderedMapIterator();
OrderedMapIterator<K, V> mapIterator();
/**
* Gets the first key currently in this map.

View File

@ -5,9 +5,9 @@
* 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.
@ -16,9 +16,6 @@
*/
package org.apache.commons.collections;
import static org.apache.commons.collections.functors.AllPredicate.allPredicate;
import static org.apache.commons.collections.functors.TruePredicate.truePredicate;
import java.util.Collection;
import org.apache.commons.collections.functors.AllPredicate;
@ -71,7 +68,7 @@ import org.apache.commons.collections.functors.UniquePredicate;
*
* @since Commons Collections 3.0
* @version $Revision$ $Date$
*
*
* @author Stephen Colebourne
* @author Ola Berg
*/
@ -87,23 +84,23 @@ public class PredicateUtils {
// Simple predicates
//-----------------------------------------------------------------------------
/**
/**
* Gets a Predicate that always throws an exception.
* This could be useful during testing as a placeholder.
*
* @see org.apache.commons.collections.functors.ExceptionPredicate
*
*
* @return the predicate
*/
public static Predicate exceptionPredicate() {
return ExceptionPredicate.INSTANCE;
public static <T> Predicate<T> exceptionPredicate() {
return ExceptionPredicate.<T>getInstance();
}
/**
* Gets a Predicate that always returns true.
*
*
* @see org.apache.commons.collections.functors.TruePredicate
*
*
* @return the predicate
* @deprecated use {@link TruePredicate#truePredicate()} instead.
*/
@ -114,20 +111,21 @@ public class PredicateUtils {
/**
* Gets a Predicate that always returns false.
*
*
* @see org.apache.commons.collections.functors.FalsePredicate
*
*
* @return the predicate
* @deprecated use {@link FalsePredicate#()} instead.
*/
public static Predicate falsePredicate() {
return FalsePredicate.INSTANCE;
public static <T> Predicate<T> falsePredicate() {
return FalsePredicate.<T>getInstance();
}
/**
* Gets a Predicate that checks if the input object passed in is null.
*
*
* @see org.apache.commons.collections.functors.NullPredicate
*
*
* @return the predicate
* @deprecated use {@link NullPredicate#nullPredicate()} instead
*/
@ -138,21 +136,21 @@ public class PredicateUtils {
/**
* Gets a Predicate that checks if the input object passed in is not null.
*
*
* @see org.apache.commons.collections.functors.NotNullPredicate
*
*
* @return the predicate
*/
public static Predicate notNullPredicate() {
return NotNullPredicate.INSTANCE;
public static <T> Predicate<T> notNullPredicate() {
return NotNullPredicate.<T>getInstance();
}
/**
* Creates a Predicate that checks if the input object is equal to the
* specified object using equals().
*
*
* @see org.apache.commons.collections.functors.EqualPredicate
*
*
* @param value the value to compare against
* @return the predicate
* @deprecated use {@link EqualPredicate#equalPredicate(Object)} instead.
@ -165,82 +163,82 @@ public class PredicateUtils {
/**
* Creates a Predicate that checks if the input object is equal to the
* specified object by identity.
*
*
* @see org.apache.commons.collections.functors.IdentityPredicate
*
*
* @param value the value to compare against
* @return the predicate
*/
public static Predicate identityPredicate(Object value) {
return IdentityPredicate.getInstance(value);
public static <T> Predicate<T> identityPredicate(T value) {
return IdentityPredicate.<T>getInstance(value);
}
/**
* Creates a Predicate that checks if the object passed in is of
* a particular type, using instanceof. A <code>null</code> input
* object will return <code>false</code>.
*
*
* @see org.apache.commons.collections.functors.InstanceofPredicate
*
*
* @param type the type to check for, may not be null
* @return the predicate
* @throws IllegalArgumentException if the class is null
*/
public static Predicate instanceofPredicate(Class type) {
public static Predicate<Object> instanceofPredicate(Class<?> type) {
return InstanceofPredicate.getInstance(type);
}
/**
* Creates a Predicate that returns true the first time an object is
* encountered, and false if the same object is received
* encountered, and false if the same object is received
* again. The comparison is by equals(). A <code>null</code> input object
* is accepted and will return true the first time, and false subsequently
* as well.
*
*
* @see org.apache.commons.collections.functors.UniquePredicate
*
*
* @return the predicate
*/
public static Predicate uniquePredicate() {
public static <T> Predicate<T> uniquePredicate() {
// must return new instance each time
return UniquePredicate.getInstance();
return UniquePredicate.<T>getInstance();
}
/**
* Creates a Predicate that invokes a method on the input object.
* The method must return either a boolean or a non-null Boolean,
* and have no parameters. If the input object is null, a
* and have no parameters. If the input object is null, a
* PredicateException is thrown.
* <p>
* For example, <code>PredicateUtils.invokerPredicate("isEmpty");</code>
* will call the <code>isEmpty</code> method on the input object to
* will call the <code>isEmpty</code> method on the input object to
* determine the predicate result.
*
*
* @see org.apache.commons.collections.functors.InvokerTransformer
* @see org.apache.commons.collections.functors.TransformerPredicate
*
*
* @param methodName the method name to call on the input object, may not be null
* @return the predicate
* @throws IllegalArgumentException if the methodName is null.
*/
public static Predicate invokerPredicate(String methodName){
public static <T> Predicate<T> invokerPredicate(String methodName){
// reuse transformer as it has caching - this is lazy really, should have inner class here
return asPredicate(InvokerTransformer.getInstance(methodName));
return asPredicate(InvokerTransformer.<Object, Boolean>getInstance(methodName));
}
/**
* Creates a Predicate that invokes a method on the input object.
* The method must return either a boolean or a non-null Boolean,
* and have no parameters. If the input object is null, a
* and have no parameters. If the input object is null, a
* PredicateException is thrown.
* <p>
* For example, <code>PredicateUtils.invokerPredicate("isEmpty");</code>
* will call the <code>isEmpty</code> method on the input object to
* will call the <code>isEmpty</code> method on the input object to
* determine the predicate result.
*
*
* @see org.apache.commons.collections.functors.InvokerTransformer
* @see org.apache.commons.collections.functors.TransformerPredicate
*
*
* @param methodName the method name to call on the input object, may not be null
* @param paramTypes the parameter types
* @param args the arguments
@ -248,9 +246,9 @@ public class PredicateUtils {
* @throws IllegalArgumentException if the method name is null
* @throws IllegalArgumentException if the paramTypes and args don't match
*/
public static Predicate invokerPredicate(String methodName, Class[] paramTypes, Object[] args){
public static <T> Predicate<T> invokerPredicate(String methodName, Class<?>[] paramTypes, Object[] args){
// reuse transformer as it has caching - this is lazy really, should have inner class here
return asPredicate(InvokerTransformer.getInstance(methodName, paramTypes, args));
return asPredicate(InvokerTransformer.<Object, Boolean>getInstance(methodName, paramTypes, args));
}
// Boolean combinations
@ -259,25 +257,25 @@ public class PredicateUtils {
/**
* Create a new Predicate that returns true only if both of the specified
* predicates are true.
*
*
* @see org.apache.commons.collections.functors.AndPredicate
*
*
* @param predicate1 the first predicate, may not be null
* @param predicate2 the second predicate, may not be null
* @return the <code>and</code> predicate
* @throws IllegalArgumentException if either predicate is null
*/
public static Predicate andPredicate(Predicate predicate1, Predicate predicate2) {
return AndPredicate.getInstance(predicate1, predicate2);
public static <T> Predicate<T> andPredicate(Predicate<? super T> predicate1, Predicate<? super T> predicate2) {
return AndPredicate.<T>getInstance(predicate1, predicate2);
}
/**
* Create a new Predicate that returns true only if all of the specified
* predicates are true.
* If the array of predicates is empty, then this predicate returns true.
*
*
* @see org.apache.commons.collections.functors.AllPredicate
*
*
* @param predicates an array of predicates to check, may not be null
* @return the <code>all</code> predicate
* @throws IllegalArgumentException if the predicates array is null
@ -293,48 +291,46 @@ public class PredicateUtils {
* Create a new Predicate that returns true only if all of the specified
* predicates are true. The predicates are checked in iterator order.
* If the collection of predicates is empty, then this predicate returns true.
*
*
* @see org.apache.commons.collections.functors.AllPredicate
*
*
* @param predicates a collection of predicates to check, may not be null
* @return the <code>all</code> predicate
* @throws IllegalArgumentException if the predicates collection is null
* @throws IllegalArgumentException if any predicate in the collection is null
* @deprecated use {@link AllPredicate#allPredicate(Collection))} instead.
*/
@Deprecated
public static <T> Predicate<T> allPredicate(Collection<Predicate<? super T>> predicates) {
public static <T> Predicate<T> allPredicate(Collection<? extends Predicate<T>> predicates) {
return AllPredicate.allPredicate(predicates);
}
/**
* Create a new Predicate that returns true if either of the specified
* predicates are true.
*
*
* @see org.apache.commons.collections.functors.OrPredicate
*
*
* @param predicate1 the first predicate, may not be null
* @param predicate2 the second predicate, may not be null
* @return the <code>or</code> predicate
* @throws IllegalArgumentException if either predicate is null
*/
public static Predicate orPredicate(Predicate predicate1, Predicate predicate2) {
return OrPredicate.getInstance(predicate1, predicate2);
public static <T> Predicate<T> orPredicate(Predicate<? super T> predicate1, Predicate<? super T> predicate2) {
return OrPredicate.<T>getInstance(predicate1, predicate2);
}
/**
* Create a new Predicate that returns true if any of the specified
* predicates are true.
* If the array of predicates is empty, then this predicate returns false.
*
*
* @see org.apache.commons.collections.functors.AnyPredicate
*
*
* @param predicates an array of predicates to check, may not be null
* @return the <code>any</code> predicate
* @throws IllegalArgumentException if the predicates array is null
* @throws IllegalArgumentException if any predicate in the array is null
*/
public static Predicate anyPredicate(Predicate[] predicates) {
public static <T> Predicate<T> anyPredicate(Predicate<? super T>[] predicates) {
return AnyPredicate.getInstance(predicates);
}
@ -342,30 +338,31 @@ public class PredicateUtils {
* Create a new Predicate that returns true if any of the specified
* predicates are true. The predicates are checked in iterator order.
* If the collection of predicates is empty, then this predicate returns false.
*
*
* @see org.apache.commons.collections.functors.AnyPredicate
*
*
* @param predicates a collection of predicates to check, may not be null
* @return the <code>any</code> predicate
* @throws IllegalArgumentException if the predicates collection is null
* @throws IllegalArgumentException if any predicate in the collection is null
*/
public static Predicate anyPredicate(Collection predicates) {
public static <T> Predicate<T> anyPredicate(Collection<? extends Predicate<T>> predicates) {
return AnyPredicate.getInstance(predicates);
}
/**
* Create a new Predicate that returns true if one, but not both, of the
* specified predicates are true.
*
* specified predicates are true. XOR
*
* @see org.apache.commons.collections.functors.OnePredicate
*
*
* @param predicate1 the first predicate, may not be null
* @param predicate2 the second predicate, may not be null
* @return the <code>either</code> predicate
* @throws IllegalArgumentException if either predicate is null
*/
public static Predicate eitherPredicate(Predicate predicate1, Predicate predicate2) {
@SuppressWarnings("unchecked")
public static <T> Predicate<T> eitherPredicate(Predicate<? super T> predicate1, Predicate<? super T> predicate2) {
return onePredicate(new Predicate[] { predicate1, predicate2 });
}
@ -373,15 +370,15 @@ public class PredicateUtils {
* Create a new Predicate that returns true if only one of the specified
* predicates are true.
* If the array of predicates is empty, then this predicate returns false.
*
*
* @see org.apache.commons.collections.functors.OnePredicate
*
*
* @param predicates an array of predicates to check, may not be null
* @return the <code>one</code> predicate
* @throws IllegalArgumentException if the predicates array is null
* @throws IllegalArgumentException if any predicate in the array is null
*/
public static Predicate onePredicate(Predicate[] predicates) {
public static <T> Predicate<T> onePredicate(Predicate<? super T>[] predicates) {
return OnePredicate.getInstance(predicates);
}
@ -389,30 +386,31 @@ public class PredicateUtils {
* Create a new Predicate that returns true if only one of the specified
* predicates are true. The predicates are checked in iterator order.
* If the collection of predicates is empty, then this predicate returns false.
*
*
* @see org.apache.commons.collections.functors.OnePredicate
*
*
* @param predicates a collection of predicates to check, may not be null
* @return the <code>one</code> predicate
* @throws IllegalArgumentException if the predicates collection is null
* @throws IllegalArgumentException if any predicate in the collection is null
*/
public static Predicate onePredicate(Collection predicates) {
public static <T> Predicate<T> onePredicate(Collection<Predicate<T>> predicates) {
return OnePredicate.getInstance(predicates);
}
/**
* Create a new Predicate that returns true if neither of the specified
* Create a new Predicate that returns true if neither of the specified
* predicates are true.
*
*
* @see org.apache.commons.collections.functors.NonePredicate
*
*
* @param predicate1 the first predicate, may not be null
* @param predicate2 the second predicate, may not be null
* @return the <code>neither</code> predicate
* @throws IllegalArgumentException if either predicate is null
*/
public static Predicate neitherPredicate(Predicate predicate1, Predicate predicate2) {
@SuppressWarnings("unchecked")
public static <T> Predicate<T> neitherPredicate(Predicate<? super T> predicate1, Predicate<? super T> predicate2) {
return nonePredicate(new Predicate[] { predicate1, predicate2 });
}
@ -420,15 +418,15 @@ public class PredicateUtils {
* Create a new Predicate that returns true if none of the specified
* predicates are true.
* If the array of predicates is empty, then this predicate returns true.
*
*
* @see org.apache.commons.collections.functors.NonePredicate
*
*
* @param predicates an array of predicates to check, may not be null
* @return the <code>none</code> predicate
* @throws IllegalArgumentException if the predicates array is null
* @throws IllegalArgumentException if any predicate in the array is null
*/
public static Predicate nonePredicate(Predicate[] predicates) {
public static <T> Predicate<T> nonePredicate(Predicate<? super T>[] predicates) {
return NonePredicate.getInstance(predicates);
}
@ -436,29 +434,29 @@ public class PredicateUtils {
* Create a new Predicate that returns true if none of the specified
* predicates are true. The predicates are checked in iterator order.
* If the collection of predicates is empty, then this predicate returns true.
*
*
* @see org.apache.commons.collections.functors.NonePredicate
*
*
* @param predicates a collection of predicates to check, may not be null
* @return the <code>none</code> predicate
* @throws IllegalArgumentException if the predicates collection is null
* @throws IllegalArgumentException if any predicate in the collection is null
*/
public static Predicate nonePredicate(Collection predicates) {
public static <T> Predicate<T> nonePredicate(Collection<? extends Predicate<T>> predicates) {
return NonePredicate.getInstance(predicates);
}
/**
* Create a new Predicate that returns true if the specified predicate
* returns false and vice versa.
*
*
* @see org.apache.commons.collections.functors.NotPredicate
*
*
* @param predicate the predicate to not
* @return the <code>not</code> predicate
* @throws IllegalArgumentException if the predicate is null
*/
public static Predicate notPredicate(Predicate predicate) {
public static <T> Predicate<T> notPredicate(Predicate<? super T> predicate) {
return NotPredicate.getInstance(predicate);
}
@ -469,14 +467,14 @@ public class PredicateUtils {
* Create a new Predicate that wraps a Transformer. The Transformer must
* return either Boolean.TRUE or Boolean.FALSE otherwise a PredicateException
* will be thrown.
*
*
* @see org.apache.commons.collections.functors.TransformerPredicate
*
*
* @param transformer the transformer to wrap, may not be null
* @return the transformer wrapping predicate
* @throws IllegalArgumentException if the transformer is null
*/
public static Predicate asPredicate(Transformer transformer) {
public static <T> Predicate<T> asPredicate(Transformer<? super T, Boolean> transformer) {
return TransformerPredicate.getInstance(transformer);
}
@ -484,17 +482,17 @@ public class PredicateUtils {
//-----------------------------------------------------------------------------
/**
* Gets a Predicate that throws an exception if the input object is null,
* otherwise it calls the specified Predicate. This allows null handling
* Gets a Predicate that throws an exception if the input object is null,
* otherwise it calls the specified Predicate. This allows null handling
* behaviour to be added to Predicates that don't support nulls.
*
*
* @see org.apache.commons.collections.functors.NullIsExceptionPredicate
*
*
* @param predicate the predicate to wrap, may not be null
* @return the predicate
* @throws IllegalArgumentException if the predicate is null.
*/
public static Predicate nullIsExceptionPredicate(Predicate predicate){
public static <T> Predicate<T> nullIsExceptionPredicate(Predicate<? super T> predicate){
return NullIsExceptionPredicate.getInstance(predicate);
}
@ -502,14 +500,14 @@ public class PredicateUtils {
* Gets a Predicate that returns false if the input object is null, otherwise
* it calls the specified Predicate. This allows null handling behaviour to
* be added to Predicates that don't support nulls.
*
*
* @see org.apache.commons.collections.functors.NullIsFalsePredicate
*
*
* @param predicate the predicate to wrap, may not be null
* @return the predicate
* @throws IllegalArgumentException if the predicate is null.
*/
public static Predicate nullIsFalsePredicate(Predicate predicate){
public static <T> Predicate<T> nullIsFalsePredicate(Predicate<? super T> predicate){
return NullIsFalsePredicate.getInstance(predicate);
}
@ -517,14 +515,14 @@ public class PredicateUtils {
* Gets a Predicate that returns true if the input object is null, otherwise
* it calls the specified Predicate. This allows null handling behaviour to
* be added to Predicates that don't support nulls.
*
*
* @see org.apache.commons.collections.functors.NullIsTruePredicate
*
*
* @param predicate the predicate to wrap, may not be null
* @return the predicate
* @throws IllegalArgumentException if the predicate is null.
*/
public static Predicate nullIsTruePredicate(Predicate predicate){
public static <T> Predicate<T> nullIsTruePredicate(Predicate<? super T> predicate){
return NullIsTruePredicate.getInstance(predicate);
}
@ -533,17 +531,18 @@ public class PredicateUtils {
/**
* Creates a predicate that transforms the input object before passing it
* to the predicate.
*
*
* @see org.apache.commons.collections.functors.TransformedPredicate
*
*
* @param transformer the transformer to call first
* @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
* @since Commons Collections 3.1
*/
public static Predicate transformedPredicate(Transformer transformer, Predicate predicate) {
return TransformedPredicate.getInstance(transformer, predicate);
public static <T> Predicate<T> transformedPredicate(
Transformer<? super T, ? extends T> transformer, Predicate<? super T> predicate) {
return TransformedPredicate.<T>getInstance(transformer, predicate);
}
}

View File

@ -18,7 +18,6 @@ package org.apache.commons.collections;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
@ -52,12 +51,32 @@ public class SetUtils {
* This uses the {@link Collections} implementation
* and is provided for completeness.
*/
public static final Set EMPTY_SET = Collections.EMPTY_SET;
public static final Set<?> EMPTY_SET = Collections.EMPTY_SET;
/**
* Get a typed empty unmodifiable Set.
* @param <E>
* @return Set<E>
*/
public static <E> Set<E> emptySet() {
return Collections.<E>emptySet();
}
/**
* An empty unmodifiable sorted set.
* This is not provided in the JDK.
*/
public static final SortedSet EMPTY_SORTED_SET = UnmodifiableSortedSet.decorate(new TreeSet());
public static final SortedSet<?> EMPTY_SORTED_SET = UnmodifiableSortedSet.decorate(new TreeSet<Object>());
/**
* Get a typed empty unmodifiable sorted set.
* @param <E>
* @return SortedSet<E>
*/
@SuppressWarnings("unchecked")
public static <E> SortedSet<E> emptySortedSet() {
return (SortedSet<E>) EMPTY_SORTED_SET;
}
/**
* <code>SetUtils</code> should not normally be instantiated.
@ -94,7 +113,7 @@ public class SetUtils {
* @param set2 the second set, may be null
* @return whether the sets are equal by value comparison
*/
public static boolean isEqualSet(final Collection set1, final Collection set2) {
public static boolean isEqualSet(final Collection<?> set1, final Collection<?> set2) {
if (set1 == set2) {
return true;
}
@ -167,7 +186,7 @@ public class SetUtils {
* @return an unmodifiable set backed by the given set
* @throws IllegalArgumentException if the set is null
*/
public static Set unmodifiableSet(Set set) {
public static <E> Set<E> unmodifiableSet(Set<E> set) {
return UnmodifiableSet.decorate(set);
}
@ -200,7 +219,7 @@ public class SetUtils {
* @return a transformed set backed by the given set
* @throws IllegalArgumentException if the Set or Transformer is null
*/
public static Set transformedSet(Set set, Transformer transformer) {
public static <E> Set<E> transformedSet(Set<E> set, Transformer<? super E, ? extends E> transformer) {
return TransformedSet.decorate(set, transformer);
}
@ -215,7 +234,7 @@ public class SetUtils {
* @return an ordered set backed by the given set
* @throws IllegalArgumentException if the Set is null
*/
public static Set orderedSet(Set set) {
public static <E> Set<E> orderedSet(Set<E> set) {
return ListOrderedSet.decorate(set);
}
@ -288,7 +307,7 @@ public class SetUtils {
* @return a transformed set backed by the given set
* @throws IllegalArgumentException if the Set or Transformer is null
*/
public static SortedSet transformedSortedSet(SortedSet set, Transformer transformer) {
public static <E> SortedSet<E> transformedSortedSet(SortedSet<E> set, Transformer<? super E, ? extends E> transformer) {
return TransformedSortedSet.decorate(set, transformer);
}

View File

@ -16,6 +16,7 @@
*/
package org.apache.commons.collections;
import java.util.Comparator;
import java.util.SortedMap;
/**
@ -49,23 +50,11 @@ public interface SortedBidiMap<K, V> extends OrderedBidiMap<K, V>, SortedMap<K,
*
* @return an inverted bidirectional map
*/
public BidiMap<V, K> inverseBidiMap();
public SortedBidiMap<V, K> inverseBidiMap();
/**
* Gets a view of this map where the keys and values are reversed.
* <p>
* Changes to one map will be visible in the other and vice versa.
* This enables both directions of the map to be accessed as a <code>SortedMap</code>.
* <p>
* Implementations should seek to avoid creating a new object every time this
* method is called. See <code>AbstractMap.values()</code> etc. Calling this
* method on the inverse map should return the original.
* <p>
* The inverse map returned by <code>inverseBidiMap()</code> should be the
* same object as returned by this method.
*
* @return an inverted bidirectional map
* Get the comparator used for the values in the value-to-key map aspect.
* @return Comparator<? super V>
*/
public SortedBidiMap<V, K> inverseSortedBidiMap();
public Comparator<? super V> valueComparator();
}

View File

@ -17,7 +17,6 @@
package org.apache.commons.collections;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import org.apache.commons.collections.functors.ChainedTransformer;
@ -80,8 +79,8 @@ public class TransformerUtils {
*
* @return the transformer
*/
public static Transformer exceptionTransformer() {
return ExceptionTransformer.INSTANCE;
public static <I, O> Transformer<I, O> exceptionTransformer() {
return ExceptionTransformer.<I, O>getInstance();
}
/**
@ -91,8 +90,8 @@ public class TransformerUtils {
*
* @return the transformer
*/
public static Transformer nullTransformer() {
return ConstantTransformer.NULL_INSTANCE;
public static <I, O> Transformer<I, O> nullTransformer() {
return ConstantTransformer.<I, O>getNullInstance();
}
/**
@ -104,8 +103,8 @@ public class TransformerUtils {
*
* @return the transformer
*/
public static Transformer nopTransformer() {
return NOPTransformer.INSTANCE;
public static <T> Transformer<T, T> nopTransformer() {
return NOPTransformer.<T>getInstance();
}
/**
@ -122,8 +121,8 @@ public class TransformerUtils {
*
* @return the transformer
*/
public static Transformer cloneTransformer() {
return CloneTransformer.INSTANCE;
public static <T> Transformer<T, T> cloneTransformer() {
return CloneTransformer.<T>getInstance();
}
/**
@ -135,7 +134,7 @@ public class TransformerUtils {
* @param constantToReturn the constant object to return each time in the transformer
* @return the transformer.
*/
public static Transformer constantTransformer(Object constantToReturn) {
public static <I, O> Transformer<I, O> constantTransformer(O constantToReturn) {
return ConstantTransformer.getInstance(constantToReturn);
}
@ -149,7 +148,7 @@ public class TransformerUtils {
* @return the transformer
* @throws IllegalArgumentException if the closure is null
*/
public static Transformer asTransformer(Closure closure) {
public static <T> Transformer<T, T> asTransformer(Closure<? super T> closure) {
return ClosureTransformer.getInstance(closure);
}
@ -163,7 +162,7 @@ public class TransformerUtils {
* @return the transformer
* @throws IllegalArgumentException if the predicate is null
*/
public static Transformer asTransformer(Predicate predicate) {
public static <T> Transformer<T, Boolean> asTransformer(Predicate<? super T> predicate) {
return PredicateTransformer.getInstance(predicate);
}
@ -177,7 +176,7 @@ public class TransformerUtils {
* @return the transformer
* @throws IllegalArgumentException if the factory is null
*/
public static Transformer asTransformer(Factory factory) {
public static <I, O> Transformer<I, O> asTransformer(Factory<? extends O> factory) {
return FactoryTransformer.getInstance(factory);
}
@ -192,8 +191,10 @@ public class TransformerUtils {
* @return the transformer
* @throws IllegalArgumentException if either transformer is null
*/
public static Transformer chainedTransformer(Transformer transformer1, Transformer transformer2) {
return ChainedTransformer.getInstance(transformer1, transformer2);
public static <T> Transformer<T, T> chainedTransformer(
Transformer<? super T, ? extends T> transformer1,
Transformer<? super T, ? extends T> transformer2) {
return ChainedTransformer.<T>getInstance(transformer1, transformer2);
}
/**
@ -207,7 +208,7 @@ public class TransformerUtils {
* @throws IllegalArgumentException if the transformers array is null
* @throws IllegalArgumentException if any transformer in the array is null
*/
public static Transformer chainedTransformer(Transformer[] transformers) {
public static <T> Transformer<T, T> chainedTransformer(Transformer<? super T, ? extends T>[] transformers) {
return ChainedTransformer.getInstance(transformers);
}
@ -223,7 +224,8 @@ public class TransformerUtils {
* @throws IllegalArgumentException if the transformers collection is null
* @throws IllegalArgumentException if any transformer in the collection is null
*/
public static Transformer chainedTransformer(Collection transformers) {
public static <T> Transformer<T, T> chainedTransformer(
Collection<? extends Transformer<T, T>> transformers) {
return ChainedTransformer.getInstance(transformers);
}
@ -240,8 +242,12 @@ public class TransformerUtils {
* @throws IllegalArgumentException if the predicate is null
* @throws IllegalArgumentException if either transformer is null
*/
public static Transformer switchTransformer(Predicate predicate, Transformer trueTransformer, Transformer falseTransformer) {
return SwitchTransformer.getInstance(new Predicate[] { predicate }, new Transformer[] { trueTransformer }, falseTransformer);
@SuppressWarnings("unchecked")
public static <I, O> Transformer<I, O> switchTransformer(Predicate<? super I> predicate,
Transformer<? super I, ? extends O> trueTransformer,
Transformer<? super I, ? extends O> falseTransformer) {
return SwitchTransformer.getInstance(new Predicate[] { predicate },
new Transformer[] { trueTransformer }, falseTransformer);
}
/**
@ -260,8 +266,9 @@ public class TransformerUtils {
* @throws IllegalArgumentException if any element in the arrays is null
* @throws IllegalArgumentException if the arrays are different sizes
*/
public static Transformer switchTransformer(Predicate[] predicates, Transformer[] transformers) {
return SwitchTransformer.getInstance(predicates, transformers, null);
public static <I, O> Transformer<I, O> switchTransformer(Predicate<? super I>[] predicates,
Transformer<? super I, ? extends O>[] transformers) {
return SwitchTransformer.<I, O>getInstance(predicates, transformers, null);
}
/**
@ -282,8 +289,10 @@ public class TransformerUtils {
* @throws IllegalArgumentException if any element in the arrays is null
* @throws IllegalArgumentException if the arrays are different sizes
*/
public static Transformer switchTransformer(Predicate[] predicates, Transformer[] transformers, Transformer defaultTransformer) {
return SwitchTransformer.getInstance(predicates, transformers, defaultTransformer);
public static <I, O> Transformer<I, O> switchTransformer(Predicate<? super I>[] predicates,
Transformer<? super I, ? extends O>[] transformers,
Transformer<? super I, ? extends O> defaultTransformer) {
return SwitchTransformer.<I, O>getInstance(predicates, transformers, defaultTransformer);
}
/**
@ -307,8 +316,9 @@ public class TransformerUtils {
* @throws IllegalArgumentException if any transformer in the map is null
* @throws ClassCastException if the map elements are of the wrong type
*/
public static Transformer switchTransformer(Map predicatesAndTransformers) {
return SwitchTransformer.getInstance(predicatesAndTransformers);
public static <I, O> Transformer<I, O> switchTransformer(
Map<Predicate<I>, Transformer<I, O>> predicatesAndTransformers) {
return SwitchTransformer.<I, O>getInstance(predicatesAndTransformers);
}
/**
@ -328,24 +338,23 @@ public class TransformerUtils {
* @throws IllegalArgumentException if the map is empty
* @throws IllegalArgumentException if any transformer in the map is null
*/
public static Transformer switchMapTransformer(Map objectsAndTransformers) {
Transformer[] trs = null;
Predicate[] preds = null;
@SuppressWarnings("unchecked")
public static <I, O> Transformer<I, O> switchMapTransformer(Map<I, Transformer<I, O>> objectsAndTransformers) {
Transformer<? super I, ? extends O>[] trs = null;
Predicate<I>[] preds = null;
if (objectsAndTransformers == null) {
throw new IllegalArgumentException("The object and transformer map must not be null");
}
Transformer def = (Transformer) objectsAndTransformers.remove(null);
Transformer<? super I, ? extends O> def = objectsAndTransformers.remove(null);
int size = objectsAndTransformers.size();
trs = new Transformer[size];
preds = new Predicate[size];
int i = 0;
for (Iterator it = objectsAndTransformers.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
preds[i] = EqualPredicate.equalPredicate(entry.getKey());
trs[i] = (Transformer) entry.getValue();
i++;
for (Map.Entry<I, Transformer<I, O>> entry : objectsAndTransformers.entrySet()) {
preds[i] = EqualPredicate.<I>equalPredicate(entry.getKey());
trs[i++] = entry.getValue();
}
return switchTransformer(preds, trs, def);
return TransformerUtils.<I, O>switchTransformer(preds, trs, def);
}
/**
@ -355,8 +364,8 @@ public class TransformerUtils {
*
* @return the transformer
*/
public static Transformer instantiateTransformer() {
return InstantiateTransformer.NO_ARG_INSTANCE;
public static <T> Transformer<Class<? extends T>, T> instantiateTransformer() {
return InstantiateTransformer.<T>getInstance();
}
/**
@ -371,8 +380,9 @@ public class TransformerUtils {
* @return the transformer
* @throws IllegalArgumentException if the paramTypes and args don't match
*/
public static Transformer instantiateTransformer(Class[] paramTypes, Object[] args) {
return InstantiateTransformer.getInstance(paramTypes, args);
public static <T> Transformer<Class<? extends T>, T> instantiateTransformer(
Class<?>[] paramTypes, Object[] args) {
return InstantiateTransformer.<T>getInstance(paramTypes, args);
}
/**
@ -385,7 +395,7 @@ public class TransformerUtils {
* @return the transformer
* @throws IllegalArgumentException if the map is null
*/
public static Transformer mapTransformer(Map map) {
public static <I, O> Transformer<I, O> mapTransformer(Map<? super I, ? extends O> map) {
return MapTransformer.getInstance(map);
}
@ -404,8 +414,8 @@ public class TransformerUtils {
* @return the transformer
* @throws IllegalArgumentException if the methodName is null.
*/
public static Transformer invokerTransformer(String methodName){
return InvokerTransformer.getInstance(methodName, null, null);
public static <I, O> Transformer<I, O> invokerTransformer(String methodName){
return InvokerTransformer.<I, O>getInstance(methodName, null, null);
}
/**
@ -422,8 +432,8 @@ public class TransformerUtils {
* @throws IllegalArgumentException if the method name is null
* @throws IllegalArgumentException if the paramTypes and args don't match
*/
public static Transformer invokerTransformer(String methodName, Class[] paramTypes, Object[] args){
return InvokerTransformer.getInstance(methodName, paramTypes, args);
public static <I, O> Transformer<I, O> invokerTransformer(String methodName, Class<?>[] paramTypes, Object[] args){
return InvokerTransformer.<I, O>getInstance(methodName, paramTypes, args);
}
/**
@ -435,8 +445,8 @@ public class TransformerUtils {
*
* @return the transformer
*/
public static Transformer stringValueTransformer() {
return StringValueTransformer.INSTANCE;
public static <T> Transformer<T, String> stringValueTransformer() {
return StringValueTransformer.<T>getInstance();
}
}

View File

@ -34,6 +34,9 @@ import org.apache.commons.collections.collection.AbstractCollectionDecorator;
public abstract class AbstractBagDecorator<E>
extends AbstractCollectionDecorator<E> implements Bag<E> {
/** Serialization version */
private static final long serialVersionUID = -3768146017343785417L;
/**
* Constructor only used in deserialization, do not use otherwise.
* @since Commons Collections 3.1

View File

@ -33,12 +33,13 @@ 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$
* @version $Revision$ $Date: 2006-10-27 19:52:37 -0500 (Fri, 27 Oct
* 2006) $
*
* @author Chuck Burdick
* @author Michael A. Smith
@ -46,16 +47,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 +67,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 +99,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 +107,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 +125,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 +136,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 +167,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 +190,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 +204,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 +224,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 +237,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 +300,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 +317,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 +341,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 +360,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 +409,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 +429,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 +451,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 +491,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 +522,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 +538,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 +553,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 +582,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 +596,5 @@ public abstract class AbstractMapBag implements Bag {
buf.append(']');
return buf.toString();
}
}

View File

@ -33,6 +33,9 @@ import org.apache.commons.collections.SortedBag;
public abstract class AbstractSortedBagDecorator<E>
extends AbstractBagDecorator<E> implements SortedBag<E> {
/** Serialization version */
private static final long serialVersionUID = -8223473624050467718L;
/**
* Constructor only used in deserialization, do not use otherwise.
* @since Commons Collections 3.1

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

@ -115,6 +115,9 @@ public class SynchronizedBag<E>
* Synchronized Set for the Bag class.
*/
class SynchronizedBagSet extends SynchronizedSet<E> {
/** Serialization version */
private static final long serialVersionUID = 2990565892366827855L;
/**
* Constructor.
* @param set the set to decorate

View File

@ -48,8 +48,8 @@ public class SynchronizedSortedBag<E>
* @return a new synchronized SortedBag
* @throws IllegalArgumentException if bag is null
*/
public static <T> SortedBag<T> decorate(SortedBag<T> bag) {
return new SynchronizedSortedBag<T>(bag);
public static <E> SortedBag<E> decorate(SortedBag<E> bag) {
return new SynchronizedSortedBag<E>(bag);
}
//-----------------------------------------------------------------------

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;
@ -55,8 +55,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);
}
//-----------------------------------------------------------------------
@ -70,7 +70,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);
}
@ -79,8 +79,8 @@ public class TransformedBag
*
* @return the decorated bag
*/
protected Bag getBag() {
return (Bag) collection;
protected Bag<E> getBag() {
return (Bag<E>) collection;
}
//-----------------------------------------------------------------------
@ -93,14 +93,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;
@ -53,8 +53,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);
}
//-----------------------------------------------------------------------
@ -68,7 +68,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);
}
@ -77,20 +77,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,63 +34,72 @@ 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$
* @version $Revision$ $Date: 2006-10-27 19:52:37 -0500 (Fri, 27 Oct
* 2006) $
*
* @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 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();
}
//-----------------------------------------------------------------------
@ -106,10 +115,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

@ -39,8 +39,8 @@ import org.apache.commons.collections.set.UnmodifiableSet;
*
* @author Stephen Colebourne
*/
public final class UnmodifiableBag
extends AbstractBagDecorator implements Unmodifiable, Serializable {
public final class UnmodifiableBag<E>
extends AbstractBagDecorator<E> implements Unmodifiable, Serializable {
/** Serialization version */
private static final long serialVersionUID = -1873799975157099624L;
@ -54,11 +54,11 @@ public final class UnmodifiableBag
* @return an unmodifiable Bag
* @throws IllegalArgumentException if bag is null
*/
public static Bag decorate(Bag bag) {
public static <E> Bag<E> decorate(Bag<E> bag) {
if (bag instanceof Unmodifiable) {
return bag;
}
return new UnmodifiableBag(bag);
return new UnmodifiableBag<E>(bag);
}
//-----------------------------------------------------------------------
@ -68,7 +68,7 @@ public final class UnmodifiableBag
* @param bag the bag to decorate, must not be null
* @throws IllegalArgumentException if bag is null
*/
private UnmodifiableBag(Bag bag) {
private UnmodifiableBag(Bag<E> bag) {
super(bag);
}
@ -91,21 +91,22 @@ public final class UnmodifiableBag
* @throws IOException
* @throws ClassNotFoundException
*/
@SuppressWarnings("unchecked")
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
collection = (Collection) in.readObject();
collection = (Collection<E>) in.readObject();
}
//-----------------------------------------------------------------------
public Iterator iterator() {
return UnmodifiableIterator.decorate(decorated().iterator());
public Iterator<E> iterator() {
return UnmodifiableIterator.<E>decorate(decorated().iterator());
}
public boolean add(Object object) {
public boolean add(E object) {
throw new UnsupportedOperationException();
}
public boolean addAll(Collection coll) {
public boolean addAll(Collection<? extends E> coll) {
throw new UnsupportedOperationException();
}
@ -117,16 +118,16 @@ public final class UnmodifiableBag
throw new UnsupportedOperationException();
}
public boolean removeAll(Collection coll) {
public boolean removeAll(Collection<?> coll) {
throw new UnsupportedOperationException();
}
public boolean retainAll(Collection coll) {
public boolean retainAll(Collection<?> coll) {
throw new UnsupportedOperationException();
}
//-----------------------------------------------------------------------
public boolean add(Object object, int count) {
public boolean add(E object, int count) {
throw new UnsupportedOperationException();
}
@ -134,9 +135,9 @@ public final class UnmodifiableBag
throw new UnsupportedOperationException();
}
public Set uniqueSet() {
Set set = decorated().uniqueSet();
return UnmodifiableSet.decorate(set);
public Set<E> uniqueSet() {
Set<E> set = decorated().uniqueSet();
return UnmodifiableSet.<E>decorate(set);
}
}

View File

@ -54,11 +54,11 @@ public final class UnmodifiableSortedBag<E>
* @return an unmodifiable SortedBag
* @throws IllegalArgumentException if bag is null
*/
public static <T> SortedBag<T> decorate(SortedBag<T> bag) {
public static <E> SortedBag<E> decorate(SortedBag<E> bag) {
if (bag instanceof Unmodifiable) {
return bag;
}
return new UnmodifiableSortedBag<T>(bag);
return new UnmodifiableSortedBag<E>(bag);
}
//-----------------------------------------------------------------------
@ -91,13 +91,14 @@ public final class UnmodifiableSortedBag<E>
* @throws IOException
* @throws ClassNotFoundException
*/
@SuppressWarnings("unchecked")
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
collection = (Collection<E>) in.readObject();
}
//-----------------------------------------------------------------------
public Iterator iterator() {
public Iterator<E> iterator() {
return UnmodifiableIterator.decorate(decorated().iterator());
}

View File

@ -37,9 +37,8 @@ import org.apache.commons.collections.map.AbstractMapDecorator;
*
* @author Stephen Colebourne
*/
public abstract class AbstractBidiMapDecorator
extends AbstractMapDecorator
implements BidiMap {
public abstract class AbstractBidiMapDecorator<K, V> extends AbstractMapDecorator<K, V> implements
BidiMap<K, V> {
/**
* Constructor that wraps (not copies).
@ -47,7 +46,7 @@ public abstract class AbstractBidiMapDecorator
* @param map the map to decorate, must not be null
* @throws IllegalArgumentException if the collection is null
*/
protected AbstractBidiMapDecorator(BidiMap map) {
protected AbstractBidiMapDecorator(BidiMap<K, V> map) {
super(map);
}
@ -55,35 +54,25 @@ public abstract class AbstractBidiMapDecorator
* Gets the map being decorated.
*
* @return the decorated map
* @deprecated use decorated()
*/
protected BidiMap getBidiMap() {
return decorated();
}
/**
* Gets the map being decorated.
*
* @return the decorated map
*/
protected BidiMap decorated() {
return (BidiMap) super.decorated();
protected BidiMap<K, V> decorated() {
return (BidiMap<K, V>) super.decorated();
}
//-----------------------------------------------------------------------
public MapIterator mapIterator() {
public MapIterator<K, V> mapIterator() {
return decorated().mapIterator();
}
public Object getKey(Object value) {
public K getKey(Object value) {
return decorated().getKey(value);
}
public Object removeValue(Object value) {
public K removeValue(Object value) {
return decorated().removeValue(value);
}
public BidiMap inverseBidiMap() {
public BidiMap<V, K> inverseBidiMap() {
return decorated().inverseBidiMap();
}

View File

@ -5,9 +5,9 @@
* 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.
@ -33,38 +33,46 @@ import org.apache.commons.collections.keyvalue.AbstractMapEntryDecorator;
* <p>
* An implementation can be written simply by implementing the
* <code>createMap</code> method.
*
*
* @see DualHashBidiMap
* @see DualTreeBidiMap
* @since Commons Collections 3.0
* @version $Id$
*
*
* @author Matthew Hawthorne
* @author Stephen Colebourne
*/
public abstract class AbstractDualBidiMap implements BidiMap {
public abstract class AbstractDualBidiMap<K, V> implements BidiMap<K, V> {
/**
* Delegate map array. The first map contains standard entries, and the
* second contains inverses.
* Normal delegate map.
*/
protected transient final Map[] maps = new Map[2];
protected transient Map<K, V> normalMap;
/**
* Reverse delegate map.
*/
protected transient Map<V, K> reverseMap;
/**
* Inverse view of this map.
*/
protected transient BidiMap inverseBidiMap = null;
protected transient BidiMap<V, K> inverseBidiMap = null;
/**
* View of the keys.
*/
protected transient Set keySet = null;
protected transient Set<K> keySet = null;
/**
* View of the values.
*/
protected transient Collection values = null;
protected transient Collection<V> values = null;
/**
* View of the entries.
*/
protected transient Set entrySet = null;
protected transient Set<Map.Entry<K, V>> entrySet = null;
/**
* Creates an empty map, initialised by <code>createMap</code>.
@ -86,18 +94,18 @@ public abstract class AbstractDualBidiMap implements BidiMap {
* Neither map is validated, so nulls may be passed in.
* If you choose to do this then the subclass constructor must populate
* the <code>maps[]</code> instance variable itself.
*
*
* @param normalMap the normal direction map
* @param reverseMap the reverse direction map
* @since Commons Collections 3.1
*/
protected AbstractDualBidiMap(Map normalMap, Map reverseMap) {
protected AbstractDualBidiMap(Map<K, V> normalMap, Map<V, K> reverseMap) {
super();
maps[0] = normalMap;
maps[1] = reverseMap;
this.normalMap = normalMap;
this.reverseMap = reverseMap;
}
/**
/**
* Constructs a map that decorates the specified maps,
* used by the subclass <code>createBidiMap</code> implementation.
*
@ -105,90 +113,89 @@ public abstract class AbstractDualBidiMap implements BidiMap {
* @param reverseMap the reverse direction map
* @param inverseBidiMap the inverse BidiMap
*/
protected AbstractDualBidiMap(Map normalMap, Map reverseMap, BidiMap inverseBidiMap) {
protected AbstractDualBidiMap(Map<K, V> normalMap, Map<V, K> reverseMap, BidiMap<V, K> inverseBidiMap) {
super();
maps[0] = normalMap;
maps[1] = reverseMap;
this.normalMap = normalMap;
this.reverseMap = reverseMap;
this.inverseBidiMap = inverseBidiMap;
}
/**
* Creates a new instance of the subclass.
*
*
* @param normalMap the normal direction map
* @param reverseMap the reverse direction map
* @param inverseMap this map, which is the inverse in the new map
* @return the inverse map
*/
protected abstract BidiMap createBidiMap(Map normalMap, Map reverseMap, BidiMap inverseMap);
protected abstract BidiMap<V, K> createBidiMap(Map<V, K> normalMap, Map<K, V> reverseMap, BidiMap<K, V> inverseMap);
// Map delegation
//-----------------------------------------------------------------------
public Object get(Object key) {
return maps[0].get(key);
public V get(Object key) {
return normalMap.get(key);
}
public int size() {
return maps[0].size();
return normalMap.size();
}
public boolean isEmpty() {
return maps[0].isEmpty();
return normalMap.isEmpty();
}
public boolean containsKey(Object key) {
return maps[0].containsKey(key);
return normalMap.containsKey(key);
}
public boolean equals(Object obj) {
return maps[0].equals(obj);
return normalMap.equals(obj);
}
public int hashCode() {
return maps[0].hashCode();
return normalMap.hashCode();
}
public String toString() {
return maps[0].toString();
return normalMap.toString();
}
// BidiMap changes
//-----------------------------------------------------------------------
public Object put(Object key, Object value) {
if (maps[0].containsKey(key)) {
maps[1].remove(maps[0].get(key));
public V put(K key, V value) {
if (normalMap.containsKey(key)) {
reverseMap.remove(normalMap.get(key));
}
if (maps[1].containsKey(value)) {
maps[0].remove(maps[1].get(value));
if (reverseMap.containsKey(value)) {
normalMap.remove(reverseMap.get(value));
}
final Object obj = maps[0].put(key, value);
maps[1].put(value, key);
final V obj = normalMap.put(key, value);
reverseMap.put(value, key);
return obj;
}
public void putAll(Map map) {
for (Iterator it = map.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
public void putAll(Map<? extends K, ? extends V> map) {
for (Map.Entry<? extends K, ? extends V> entry : map.entrySet()) {
put(entry.getKey(), entry.getValue());
}
}
public Object remove(Object key) {
Object value = null;
if (maps[0].containsKey(key)) {
value = maps[0].remove(key);
maps[1].remove(value);
public V remove(Object key) {
V value = null;
if (normalMap.containsKey(key)) {
value = normalMap.remove(key);
reverseMap.remove(value);
}
return value;
}
public void clear() {
maps[0].clear();
maps[1].clear();
normalMap.clear();
reverseMap.clear();
}
public boolean containsValue(Object value) {
return maps[1].containsKey(value);
return reverseMap.containsKey(value);
}
// BidiMap
@ -201,45 +208,45 @@ public abstract class AbstractDualBidiMap implements BidiMap {
* The setValue() methods only allow a new value to be set.
* If the value being set is already in the map, an IllegalArgumentException
* is thrown (as setValue cannot change the size of the map).
*
*
* @return a map iterator
*/
public MapIterator mapIterator() {
return new BidiMapIterator(this);
}
public Object getKey(Object value) {
return maps[1].get(value);
public MapIterator<K, V> mapIterator() {
return new BidiMapIterator<K, V>(this);
}
public Object removeValue(Object value) {
Object key = null;
if (maps[1].containsKey(value)) {
key = maps[1].remove(value);
maps[0].remove(key);
public K getKey(Object value) {
return reverseMap.get(value);
}
public K removeValue(Object value) {
K key = null;
if (reverseMap.containsKey(value)) {
key = reverseMap.remove(value);
normalMap.remove(key);
}
return key;
}
public BidiMap inverseBidiMap() {
public BidiMap<V, K> inverseBidiMap() {
if (inverseBidiMap == null) {
inverseBidiMap = createBidiMap(maps[1], maps[0], this);
inverseBidiMap = createBidiMap(reverseMap, normalMap, this);
}
return inverseBidiMap;
}
// Map views
//-----------------------------------------------------------------------
/**
* Gets a keySet view of the map.
* Changes made on the view are reflected in the map.
* The set supports remove and clear but not add.
*
*
* @return the keySet view
*/
public Set keySet() {
public Set<K> keySet() {
if (keySet == null) {
keySet = new KeySet(this);
keySet = new KeySet<K>(this);
}
return keySet;
}
@ -247,24 +254,24 @@ public abstract class AbstractDualBidiMap implements BidiMap {
/**
* Creates a key set iterator.
* Subclasses can override this to return iterators with different properties.
*
*
* @param iterator the iterator to decorate
* @return the keySet iterator
*/
protected Iterator createKeySetIterator(Iterator iterator) {
return new KeySetIterator(iterator, this);
protected Iterator<K> createKeySetIterator(Iterator<K> iterator) {
return new KeySetIterator<K>(iterator, this);
}
/**
* Gets a values view of the map.
* Changes made on the view are reflected in the map.
* The set supports remove and clear but not add.
*
*
* @return the values view
*/
public Collection values() {
public Collection<V> values() {
if (values == null) {
values = new Values(this);
values = new Values<V>(this);
}
return values;
}
@ -272,12 +279,12 @@ public abstract class AbstractDualBidiMap implements BidiMap {
/**
* Creates a values iterator.
* Subclasses can override this to return iterators with different properties.
*
*
* @param iterator the iterator to decorate
* @return the values iterator
*/
protected Iterator createValuesIterator(Iterator iterator) {
return new ValuesIterator(iterator, this);
protected Iterator<V> createValuesIterator(Iterator<V> iterator) {
return new ValuesIterator<V>(iterator, this);
}
/**
@ -288,53 +295,54 @@ public abstract class AbstractDualBidiMap implements BidiMap {
* The Map Entry setValue() method only allow a new value to be set.
* If the value being set is already in the map, an IllegalArgumentException
* is thrown (as setValue cannot change the size of the map).
*
*
* @return the entrySet view
*/
public Set entrySet() {
public Set<Map.Entry<K, V>> entrySet() {
if (entrySet == null) {
entrySet = new EntrySet(this);
entrySet = new EntrySet<K, V>(this);
}
return entrySet;
}
/**
* Creates an entry set iterator.
* Subclasses can override this to return iterators with different properties.
*
*
* @param iterator the iterator to decorate
* @return the entrySet iterator
*/
protected Iterator createEntrySetIterator(Iterator iterator) {
return new EntrySetIterator(iterator, this);
protected Iterator<Map.Entry<K, V>> createEntrySetIterator(Iterator<Map.Entry<K, V>> iterator) {
return new EntrySetIterator<K, V>(iterator, this);
}
//-----------------------------------------------------------------------
/**
* Inner class View.
*/
protected static abstract class View extends AbstractCollectionDecorator {
@SuppressWarnings("serial")
protected static abstract class View<K, V, E> extends AbstractCollectionDecorator<E> {
/** The parent map */
protected final AbstractDualBidiMap parent;
protected final AbstractDualBidiMap<K, V> parent;
/**
* Constructs a new view of the BidiMap.
*
*
* @param coll the collection view being decorated
* @param parent the parent BidiMap
*/
protected View(Collection coll, AbstractDualBidiMap parent) {
protected View(Collection<E> coll, AbstractDualBidiMap<K, V> parent) {
super(coll);
this.parent = parent;
}
public boolean removeAll(Collection coll) {
public boolean removeAll(Collection<?> coll) {
if (parent.isEmpty() || coll.isEmpty()) {
return false;
}
boolean modified = false;
Iterator it = iterator();
Iterator<E> it = iterator();
while (it.hasNext()) {
if (coll.contains(it.next())) {
it.remove();
@ -344,7 +352,7 @@ public abstract class AbstractDualBidiMap implements BidiMap {
return modified;
}
public boolean retainAll(Collection coll) {
public boolean retainAll(Collection<?> coll) {
if (parent.isEmpty()) {
return false;
}
@ -353,7 +361,7 @@ public abstract class AbstractDualBidiMap implements BidiMap {
return true;
}
boolean modified = false;
Iterator it = iterator();
Iterator<E> it = iterator();
while (it.hasNext()) {
if (coll.contains(it.next()) == false) {
it.remove();
@ -362,80 +370,86 @@ public abstract class AbstractDualBidiMap implements BidiMap {
}
return modified;
}
public void clear() {
parent.clear();
}
}
//-----------------------------------------------------------------------
/**
* Inner class KeySet.
*/
protected static class KeySet extends View implements Set {
protected static class KeySet<K> extends View<K, Object, K> implements Set<K> {
/** Serialization version */
private static final long serialVersionUID = -7107935777385040694L;
/**
* Constructs a new view of the BidiMap.
*
*
* @param parent the parent BidiMap
*/
protected KeySet(AbstractDualBidiMap parent) {
super(parent.maps[0].keySet(), parent);
@SuppressWarnings("unchecked")
protected KeySet(AbstractDualBidiMap<K, ?> parent) {
super(parent.normalMap.keySet(), (AbstractDualBidiMap<K, Object>) parent);
}
public Iterator iterator() {
public Iterator<K> iterator() {
return parent.createKeySetIterator(super.iterator());
}
public boolean contains(Object key) {
return parent.maps[0].containsKey(key);
return parent.normalMap.containsKey(key);
}
public boolean remove(Object key) {
if (parent.maps[0].containsKey(key)) {
Object value = parent.maps[0].remove(key);
parent.maps[1].remove(value);
if (parent.normalMap.containsKey(key)) {
Object value = parent.normalMap.remove(key);
parent.reverseMap.remove(value);
return true;
}
return false;
}
}
/**
* Inner class KeySetIterator.
*/
protected static class KeySetIterator extends AbstractIteratorDecorator {
protected static class KeySetIterator<K> extends AbstractIteratorDecorator<K> {
/** The parent map */
protected final AbstractDualBidiMap parent;
protected final AbstractDualBidiMap<K, ?> parent;
/** The last returned key */
protected Object lastKey = null;
protected K lastKey = null;
/** Whether remove is allowed at present */
protected boolean canRemove = false;
/**
* Constructor.
* @param iterator the iterator to decorate
* @param parent the parent map
*/
protected KeySetIterator(Iterator iterator, AbstractDualBidiMap parent) {
protected KeySetIterator(Iterator<K> iterator, AbstractDualBidiMap<K, ?> parent) {
super(iterator);
this.parent = parent;
}
public Object next() {
public K next() {
lastKey = super.next();
canRemove = true;
return lastKey;
}
public void remove() {
if (canRemove == false) {
throw new IllegalStateException("Iterator remove() can only be called once after next()");
}
Object value = parent.maps[0].get(lastKey);
Object value = parent.normalMap.get(lastKey);
super.remove();
parent.maps[1].remove(value);
parent.reverseMap.remove(value);
lastKey = null;
canRemove = false;
}
@ -445,69 +459,76 @@ public abstract class AbstractDualBidiMap implements BidiMap {
/**
* Inner class Values.
*/
protected static class Values extends View implements Set {
protected static class Values<V> extends View<Object, V, V> implements Set<V> {
/** Serialization version */
private static final long serialVersionUID = 4023777119829639864L;
/**
* Constructs a new view of the BidiMap.
*
*
* @param parent the parent BidiMap
*/
protected Values(AbstractDualBidiMap parent) {
super(parent.maps[0].values(), parent);
@SuppressWarnings("unchecked")
protected Values(AbstractDualBidiMap<?, V> parent) {
super(parent.normalMap.values(), (AbstractDualBidiMap<Object, V>) parent);
}
public Iterator iterator() {
public Iterator<V> iterator() {
return parent.createValuesIterator(super.iterator());
}
public boolean contains(Object value) {
return parent.maps[1].containsKey(value);
return parent.reverseMap.containsKey(value);
}
public boolean remove(Object value) {
if (parent.maps[1].containsKey(value)) {
Object key = parent.maps[1].remove(value);
parent.maps[0].remove(key);
if (parent.reverseMap.containsKey(value)) {
Object key = parent.reverseMap.remove(value);
parent.normalMap.remove(key);
return true;
}
return false;
}
}
/**
* Inner class ValuesIterator.
*/
protected static class ValuesIterator extends AbstractIteratorDecorator {
protected static class ValuesIterator<V> extends AbstractIteratorDecorator<V> {
/** The parent map */
protected final AbstractDualBidiMap parent;
protected final AbstractDualBidiMap<Object, V> parent;
/** The last returned value */
protected Object lastValue = null;
protected V lastValue = null;
/** Whether remove is allowed at present */
protected boolean canRemove = false;
/**
* Constructor.
* @param iterator the iterator to decorate
* @param parent the parent map
*/
protected ValuesIterator(Iterator iterator, AbstractDualBidiMap parent) {
@SuppressWarnings("unchecked")
protected ValuesIterator(Iterator<V> iterator, AbstractDualBidiMap<?, V> parent) {
super(iterator);
this.parent = parent;
this.parent = (AbstractDualBidiMap<Object, V>) parent;
}
public Object next() {
public V next() {
lastValue = super.next();
canRemove = true;
return lastValue;
}
public void remove() {
if (canRemove == false) {
throw new IllegalStateException("Iterator remove() can only be called once after next()");
}
super.remove(); // removes from maps[0]
parent.maps[1].remove(lastValue);
parent.reverseMap.remove(lastValue);
lastValue = null;
canRemove = false;
}
@ -517,67 +538,72 @@ public abstract class AbstractDualBidiMap implements BidiMap {
/**
* Inner class EntrySet.
*/
protected static class EntrySet extends View implements Set {
protected static class EntrySet<K, V> extends View<K, V, Map.Entry<K, V>> implements Set<Map.Entry<K, V>> {
/** Serialization version */
private static final long serialVersionUID = 4040410962603292348L;
/**
* Constructs a new view of the BidiMap.
*
*
* @param parent the parent BidiMap
*/
protected EntrySet(AbstractDualBidiMap parent) {
super(parent.maps[0].entrySet(), parent);
protected EntrySet(AbstractDualBidiMap<K, V> parent) {
super(parent.normalMap.entrySet(), parent);
}
public Iterator iterator() {
public Iterator<Map.Entry<K, V>> iterator() {
return parent.createEntrySetIterator(super.iterator());
}
public boolean remove(Object obj) {
if (obj instanceof Map.Entry == false) {
return false;
}
Map.Entry entry = (Map.Entry) obj;
Map.Entry<?, ?> entry = (Map.Entry<?, ?>) obj;
Object key = entry.getKey();
if (parent.containsKey(key)) {
Object value = parent.maps[0].get(key);
V value = parent.normalMap.get(key);
if (value == null ? entry.getValue() == null : value.equals(entry.getValue())) {
parent.maps[0].remove(key);
parent.maps[1].remove(value);
parent.normalMap.remove(key);
parent.reverseMap.remove(value);
return true;
}
}
return false;
}
}
/**
* Inner class EntrySetIterator.
*/
protected static class EntrySetIterator extends AbstractIteratorDecorator {
protected static class EntrySetIterator<K, V> extends AbstractIteratorDecorator<Map.Entry<K, V>> {
/** The parent map */
protected final AbstractDualBidiMap parent;
protected final AbstractDualBidiMap<K, V> parent;
/** The last returned entry */
protected Map.Entry last = null;
protected Map.Entry<K, V> last = null;
/** Whether remove is allowed at present */
protected boolean canRemove = false;
/**
* Constructor.
* @param iterator the iterator to decorate
* @param parent the parent map
*/
protected EntrySetIterator(Iterator iterator, AbstractDualBidiMap parent) {
protected EntrySetIterator(Iterator<Map.Entry<K, V>> iterator, AbstractDualBidiMap<K, V> parent) {
super(iterator);
this.parent = parent;
}
public Object next() {
last = new MapEntry((Map.Entry) super.next(), parent);
public Map.Entry<K, V> next() {
last = new MapEntry<K, V>(super.next(), parent);
canRemove = true;
return last;
}
public void remove() {
if (canRemove == false) {
throw new IllegalStateException("Iterator remove() can only be called once after next()");
@ -585,7 +611,7 @@ public abstract class AbstractDualBidiMap implements BidiMap {
// store value as remove may change the entry in the decorator (eg.TreeMap)
Object value = last.getValue();
super.remove();
parent.maps[1].remove(value);
parent.reverseMap.remove(value);
last = null;
canRemove = false;
}
@ -594,117 +620,119 @@ public abstract class AbstractDualBidiMap implements BidiMap {
/**
* Inner class MapEntry.
*/
protected static class MapEntry extends AbstractMapEntryDecorator {
protected static class MapEntry<K, V> extends AbstractMapEntryDecorator<K, V> {
/** The parent map */
protected final AbstractDualBidiMap<K, V> parent;
/** The parent map */
protected final AbstractDualBidiMap parent;
/**
* Constructor.
* @param entry the entry to decorate
* @param parent the parent map
*/
protected MapEntry(Map.Entry entry, AbstractDualBidiMap parent) {
protected MapEntry(Map.Entry<K, V> entry, AbstractDualBidiMap<K, V> parent) {
super(entry);
this.parent = parent;
}
public Object setValue(Object value) {
Object key = MapEntry.this.getKey();
if (parent.maps[1].containsKey(value) &&
parent.maps[1].get(value) != key) {
public V setValue(V value) {
K key = MapEntry.this.getKey();
if (parent.reverseMap.containsKey(value) &&
parent.reverseMap.get(value) != key) {
throw new IllegalArgumentException("Cannot use setValue() when the object being set is already in the map");
}
parent.put(key, value);
final Object oldValue = super.setValue(value);
final V oldValue = super.setValue(value);
return oldValue;
}
}
/**
* Inner class MapIterator.
*/
protected static class BidiMapIterator implements MapIterator, ResettableIterator {
protected static class BidiMapIterator<K, V> implements MapIterator<K, V>, ResettableIterator<K> {
/** The parent map */
protected final AbstractDualBidiMap parent;
protected final AbstractDualBidiMap<K, V> parent;
/** The iterator being wrapped */
protected Iterator iterator;
protected Iterator<Map.Entry<K, V>> iterator;
/** The last returned entry */
protected Map.Entry last = null;
protected Map.Entry<K, V> last = null;
/** Whether remove is allowed at present */
protected boolean canRemove = false;
/**
* Constructor.
* @param parent the parent map
*/
protected BidiMapIterator(AbstractDualBidiMap parent) {
protected BidiMapIterator(AbstractDualBidiMap<K, V> parent) {
super();
this.parent = parent;
this.iterator = parent.maps[0].entrySet().iterator();
this.iterator = parent.normalMap.entrySet().iterator();
}
public boolean hasNext() {
return iterator.hasNext();
}
public Object next() {
last = (Map.Entry) iterator.next();
public K next() {
last = iterator.next();
canRemove = true;
return last.getKey();
}
public void remove() {
if (canRemove == false) {
throw new IllegalStateException("Iterator remove() can only be called once after next()");
}
// store value as remove may change the entry in the decorator (eg.TreeMap)
Object value = last.getValue();
V value = last.getValue();
iterator.remove();
parent.maps[1].remove(value);
parent.reverseMap.remove(value);
last = null;
canRemove = false;
}
public Object getKey() {
public K getKey() {
if (last == null) {
throw new IllegalStateException("Iterator getKey() can only be called after next() and before remove()");
}
return last.getKey();
}
public Object getValue() {
public V getValue() {
if (last == null) {
throw new IllegalStateException("Iterator getValue() can only be called after next() and before remove()");
}
return last.getValue();
}
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()");
}
if (parent.maps[1].containsKey(value) &&
parent.maps[1].get(value) != last.getKey()) {
if (parent.reverseMap.containsKey(value) &&
parent.reverseMap.get(value) != last.getKey()) {
throw new IllegalArgumentException("Cannot use setValue() when the object being set is already in the map");
}
return parent.put(last.getKey(), value);
}
public void reset() {
iterator = parent.maps[0].entrySet().iterator();
iterator = parent.normalMap.entrySet().iterator();
last = null;
canRemove = false;
}
public String toString() {
if (last != null) {
return "MapIterator[" + getKey() + "=" + getValue() + "]";
} else {
return "MapIterator[]";
}
return "MapIterator[]";
}
}
}

View File

@ -36,9 +36,9 @@ import org.apache.commons.collections.OrderedMapIterator;
*
* @author Stephen Colebourne
*/
public abstract class AbstractOrderedBidiMapDecorator
extends AbstractBidiMapDecorator
implements OrderedBidiMap {
public abstract class AbstractOrderedBidiMapDecorator<K, V>
extends AbstractBidiMapDecorator<K, V>
implements OrderedBidiMap<K, V> {
/**
* Constructor that wraps (not copies).
@ -46,7 +46,7 @@ public abstract class AbstractOrderedBidiMapDecorator
* @param map the map to decorate, must not be null
* @throws IllegalArgumentException if the collection is null
*/
protected AbstractOrderedBidiMapDecorator(OrderedBidiMap map) {
protected AbstractOrderedBidiMapDecorator(OrderedBidiMap<K, V> map) {
super(map);
}
@ -54,44 +54,35 @@ public abstract class AbstractOrderedBidiMapDecorator
* Gets the map being decorated.
*
* @return the decorated map
* @deprecated use decorated()
*/
protected OrderedBidiMap getOrderedBidiMap() {
return decorated();
}
/**
* Gets the map being decorated.
*
* @return the decorated map
*/
protected OrderedBidiMap decorated() {
return (OrderedBidiMap) super.decorated();
protected OrderedBidiMap<K, V> decorated() {
return (OrderedBidiMap<K, V>) super.decorated();
}
//-----------------------------------------------------------------------
public OrderedMapIterator orderedMapIterator() {
return decorated().orderedMapIterator();
public OrderedMapIterator<K, V> mapIterator() {
return decorated().mapIterator();
}
public Object firstKey() {
public K firstKey() {
return decorated().firstKey();
}
public Object lastKey() {
public K lastKey() {
return decorated().lastKey();
}
public Object nextKey(Object key) {
public K nextKey(K key) {
return decorated().nextKey(key);
}
public Object previousKey(Object key) {
public K previousKey(K key) {
return decorated().previousKey(key);
}
public OrderedBidiMap inverseOrderedBidiMap() {
return decorated().inverseOrderedBidiMap();
@Override
public OrderedBidiMap<V, K> inverseBidiMap() {
return decorated().inverseBidiMap();
}
}

View File

@ -38,9 +38,8 @@ import org.apache.commons.collections.SortedBidiMap;
*
* @author Stephen Colebourne
*/
public abstract class AbstractSortedBidiMapDecorator
extends AbstractOrderedBidiMapDecorator
implements SortedBidiMap {
public abstract class AbstractSortedBidiMapDecorator<K, V> extends
AbstractOrderedBidiMapDecorator<K, V> implements SortedBidiMap<K, V> {
/**
* Constructor that wraps (not copies).
@ -48,7 +47,7 @@ public abstract class AbstractSortedBidiMapDecorator
* @param map the map to decorate, must not be null
* @throws IllegalArgumentException if the collection is null
*/
public AbstractSortedBidiMapDecorator(SortedBidiMap map) {
public AbstractSortedBidiMapDecorator(SortedBidiMap<K, V> map) {
super(map);
}
@ -56,39 +55,34 @@ public abstract class AbstractSortedBidiMapDecorator
* Gets the map being decorated.
*
* @return the decorated map
* @deprecated use decorated()
*/
protected SortedBidiMap getSortedBidiMap() {
return decorated();
}
/**
* Gets the map being decorated.
*
* @return the decorated map
*/
protected SortedBidiMap decorated() {
return (SortedBidiMap) super.decorated();
protected SortedBidiMap<K, V> decorated() {
return (SortedBidiMap<K, V>) super.decorated();
}
//-----------------------------------------------------------------------
public SortedBidiMap inverseSortedBidiMap() {
return getSortedBidiMap().inverseSortedBidiMap();
@Override
public SortedBidiMap<V, K> inverseBidiMap() {
return decorated().inverseBidiMap();
}
public Comparator comparator() {
public Comparator<? super K> comparator() {
return decorated().comparator();
}
public SortedMap subMap(Object fromKey, Object toKey) {
public Comparator<? super V> valueComparator() {
return decorated().valueComparator();
}
public SortedMap<K, V> subMap(K fromKey, K toKey) {
return decorated().subMap(fromKey, toKey);
}
public SortedMap headMap(Object toKey) {
public SortedMap<K, V> headMap(K toKey) {
return decorated().headMap(toKey);
}
public SortedMap tailMap(Object fromKey) {
public SortedMap<K, V> tailMap(K fromKey) {
return decorated().tailMap(fromKey);
}

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

@ -5,9 +5,9 @@
* 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.
@ -48,97 +48,110 @@ import org.apache.commons.collections.map.AbstractSortedMapDecorator;
* <p>
* NOTE: From Commons Collections 3.1, all subclasses will use <code>TreeMap</code>
* and the flawed <code>createMap</code> method is ignored.
*
*
* @since Commons Collections 3.0
* @version $Id$
*
*
* @author Matthew Hawthorne
* @author Stephen Colebourne
*/
public class DualTreeBidiMap
extends AbstractDualBidiMap implements SortedBidiMap, Serializable {
public class DualTreeBidiMap<K, V> extends AbstractDualBidiMap<K, V> implements
SortedBidiMap<K, V>, Serializable {
/** Ensure serialization compatibility */
private static final long serialVersionUID = 721969328361809L;
/** The comparator to use */
protected final Comparator comparator;
/** The key comparator to use */
protected final Comparator<? super K> comparator;
/** The value comparator to use */
protected final Comparator<? super V> valueComparator;
/**
* Creates an empty <code>DualTreeBidiMap</code>
*/
public DualTreeBidiMap() {
super(new TreeMap(), new TreeMap());
super(new TreeMap<K, V>(), new TreeMap<V, K>());
this.comparator = null;
this.valueComparator = null;
}
/**
/**
* Constructs a <code>DualTreeBidiMap</code> and copies the mappings from
* specified <code>Map</code>.
* specified <code>Map</code>.
*
* @param map the map whose mappings are to be placed in this map
*/
public DualTreeBidiMap(Map map) {
super(new TreeMap(), new TreeMap());
public DualTreeBidiMap(Map<K, V> map) {
super(new TreeMap<K, V>(), new TreeMap<V, K>());
putAll(map);
this.comparator = null;
this.valueComparator = null;
}
/**
/**
* Constructs a <code>DualTreeBidiMap</code> using the specified Comparator.
*
* @param comparator the Comparator
* @param keyComparator the Comparator
*/
public DualTreeBidiMap(Comparator comparator) {
super(new TreeMap(comparator), new TreeMap(comparator));
this.comparator = comparator;
public DualTreeBidiMap(Comparator<? super K> keyComparator, Comparator<? super V> valueComparator) {
super(new TreeMap<K, V>(keyComparator), new TreeMap<V, K>(valueComparator));
this.comparator = keyComparator;
this.valueComparator = valueComparator;
}
/**
/**
* Constructs a <code>DualTreeBidiMap</code> that decorates the specified maps.
*
* @param normalMap the normal direction map
* @param reverseMap the reverse direction map
* @param inverseBidiMap the inverse BidiMap
*/
protected DualTreeBidiMap(Map normalMap, Map reverseMap, BidiMap inverseBidiMap) {
protected DualTreeBidiMap(Map<K, V> normalMap, Map<V, K> reverseMap, BidiMap<V, K> inverseBidiMap) {
super(normalMap, reverseMap, inverseBidiMap);
this.comparator = ((SortedMap) normalMap).comparator();
this.comparator = ((SortedMap<K, V>) normalMap).comparator();
this.valueComparator = ((SortedMap<V, K>) reverseMap).comparator();
}
/**
* Creates a new instance of this object.
*
*
* @param normalMap the normal direction map
* @param reverseMap the reverse direction map
* @param inverseMap the inverse BidiMap
* @return new bidi map
*/
protected BidiMap createBidiMap(Map normalMap, Map reverseMap, BidiMap inverseMap) {
return new DualTreeBidiMap(normalMap, reverseMap, inverseMap);
protected DualTreeBidiMap<V, K> createBidiMap(Map<V, K> normalMap, Map<K, V> reverseMap, BidiMap<K, V> inverseMap) {
return new DualTreeBidiMap<V, K>(normalMap, reverseMap, inverseMap);
}
//-----------------------------------------------------------------------
public Comparator comparator() {
return ((SortedMap) maps[0]).comparator();
public Comparator<? super K> comparator() {
return ((SortedMap<K, V>) normalMap).comparator();
}
public Object firstKey() {
return ((SortedMap) maps[0]).firstKey();
public Comparator<? super V> valueComparator() {
return ((SortedMap<V, K>) reverseMap).comparator();
}
public Object lastKey() {
return ((SortedMap) maps[0]).lastKey();
public K firstKey() {
return ((SortedMap<K, V>) normalMap).firstKey();
}
public Object nextKey(Object key) {
public K lastKey() {
return ((SortedMap<K, V>) normalMap).lastKey();
}
public K nextKey(K key) {
if (isEmpty()) {
return null;
}
if (maps[0] instanceof OrderedMap) {
return ((OrderedMap) maps[0]).nextKey(key);
if (normalMap instanceof OrderedMap) {
return ((OrderedMap<K, ?>) normalMap).nextKey(key);
}
SortedMap sm = (SortedMap) maps[0];
Iterator it = sm.tailMap(key).keySet().iterator();
SortedMap<K, V> sm = (SortedMap<K, V>) normalMap;
Iterator<K> it = sm.tailMap(key).keySet().iterator();
it.next();
if (it.hasNext()) {
return it.next();
@ -146,15 +159,15 @@ public class DualTreeBidiMap
return null;
}
public Object previousKey(Object key) {
public K previousKey(K key) {
if (isEmpty()) {
return null;
}
if (maps[0] instanceof OrderedMap) {
return ((OrderedMap) maps[0]).previousKey(key);
if (normalMap instanceof OrderedMap) {
return ((OrderedMap<K, V>) normalMap).previousKey(key);
}
SortedMap sm = (SortedMap) maps[0];
SortedMap hm = sm.headMap(key);
SortedMap<K, V> sm = (SortedMap<K, V>) normalMap;
SortedMap<K, V> hm = sm.headMap(key);
if (hm.isEmpty()) {
return null;
}
@ -167,81 +180,94 @@ public class DualTreeBidiMap
* <p>
* This implementation copies the elements to an ArrayList in order to
* provide the forward/backward behaviour.
*
*
* @return a new ordered map iterator
*/
public OrderedMapIterator orderedMapIterator() {
return new BidiOrderedMapIterator(this);
public OrderedMapIterator<K, V> mapIterator() {
return new BidiOrderedMapIterator<K, V>(this);
}
public SortedBidiMap inverseSortedBidiMap() {
return (SortedBidiMap) inverseBidiMap();
public SortedBidiMap<V, K> inverseSortedBidiMap() {
return (SortedBidiMap<V, K>) inverseBidiMap();
}
public OrderedBidiMap inverseOrderedBidiMap() {
return (OrderedBidiMap) inverseBidiMap();
public OrderedBidiMap<V, K> inverseOrderedBidiMap() {
return (OrderedBidiMap<V, K>) inverseBidiMap();
}
//-----------------------------------------------------------------------
public SortedMap headMap(Object toKey) {
SortedMap sub = ((SortedMap) maps[0]).headMap(toKey);
return new ViewMap(this, sub);
public SortedMap<K, V> headMap(K toKey) {
SortedMap<K, V> sub = ((SortedMap<K, V>) normalMap).headMap(toKey);
return new ViewMap<K, V>(this, sub);
}
public SortedMap tailMap(Object fromKey) {
SortedMap sub = ((SortedMap) maps[0]).tailMap(fromKey);
return new ViewMap(this, sub);
public SortedMap<K, V> tailMap(K fromKey) {
SortedMap<K, V> sub = ((SortedMap<K, V>) normalMap).tailMap(fromKey);
return new ViewMap<K, V>(this, sub);
}
public SortedMap subMap(Object fromKey, Object toKey) {
SortedMap sub = ((SortedMap) maps[0]).subMap(fromKey, toKey);
return new ViewMap(this, sub);
public SortedMap<K, V> subMap(K fromKey, K toKey) {
SortedMap<K, V> sub = ((SortedMap<K, V>) normalMap).subMap(fromKey, toKey);
return new ViewMap<K, V>(this, sub);
}
/**
* {@inheritDoc}
*/
@Override
public SortedBidiMap<V, K> inverseBidiMap() {
return (SortedBidiMap<V, K>) super.inverseBidiMap();
}
//-----------------------------------------------------------------------
/**
* Internal sorted map view.
*/
protected static class ViewMap extends AbstractSortedMapDecorator {
protected static class ViewMap<K, V> extends AbstractSortedMapDecorator<K, V> {
/** The parent bidi map. */
final DualTreeBidiMap bidi;
final DualTreeBidiMap<K, V> bidi;
/**
* Constructor.
* @param bidi the parent bidi map
* @param sm the subMap sorted map
*/
protected ViewMap(DualTreeBidiMap bidi, SortedMap sm) {
protected ViewMap(DualTreeBidiMap<K, V> bidi, SortedMap<K, V> sm) {
// the implementation is not great here...
// use the maps[0] as the filtered map, but maps[1] as the full map
// use the normalMap as the filtered map, but reverseMap as the full map
// this forces containsValue and clear to be overridden
super((SortedMap) bidi.createBidiMap(sm, bidi.maps[1], bidi.inverseBidiMap));
this.bidi = (DualTreeBidiMap) map;
super(new DualTreeBidiMap<K, V>(sm, bidi.reverseMap, bidi.inverseBidiMap));
this.bidi = (DualTreeBidiMap<K, V>) decorated();
}
public boolean containsValue(Object value) {
// override as default implementation jumps to [1]
return bidi.maps[0].containsValue(value);
// override as default implementation uses reverseMap
return decorated().normalMap.containsValue(value);
}
public void clear() {
// override as default implementation jumps to [1]
for (Iterator it = keySet().iterator(); it.hasNext();) {
// override as default implementation uses reverseMap
for (Iterator<K> it = keySet().iterator(); it.hasNext();) {
it.next();
it.remove();
}
}
public SortedMap headMap(Object toKey) {
return new ViewMap(bidi, super.headMap(toKey));
public SortedMap<K, V> headMap(K toKey) {
return new ViewMap<K, V>(decorated(), super.headMap(toKey));
}
public SortedMap tailMap(Object fromKey) {
return new ViewMap(bidi, super.tailMap(fromKey));
public SortedMap<K, V> tailMap(K fromKey) {
return new ViewMap<K, V>(decorated(), super.tailMap(fromKey));
}
public SortedMap subMap(Object fromKey, Object toKey) {
return new ViewMap(bidi, super.subMap(fromKey, toKey));
public SortedMap<K, V> subMap(K fromKey, K toKey) {
return new ViewMap<K, V>(decorated(), super.subMap(fromKey, toKey));
}
@Override
protected DualTreeBidiMap<K, V> decorated() {
return (DualTreeBidiMap<K, V>) super.decorated();
}
}
@ -249,99 +275,101 @@ public class DualTreeBidiMap
/**
* Inner class MapIterator.
*/
protected static class BidiOrderedMapIterator implements OrderedMapIterator, ResettableIterator {
protected static class BidiOrderedMapIterator<K, V> implements OrderedMapIterator<K, V>, ResettableIterator<K> {
/** The parent map */
protected final AbstractDualBidiMap parent;
protected final AbstractDualBidiMap<K, V> parent;
/** The iterator being decorated */
protected ListIterator iterator;
protected ListIterator<Map.Entry<K, V>> iterator;
/** The last returned entry */
private Map.Entry last = null;
private Map.Entry<K, V> last = null;
/**
* Constructor.
* @param parent the parent map
*/
protected BidiOrderedMapIterator(AbstractDualBidiMap parent) {
protected BidiOrderedMapIterator(AbstractDualBidiMap<K, V> parent) {
super();
this.parent = parent;
iterator = new ArrayList(parent.entrySet()).listIterator();
iterator = new ArrayList<Map.Entry<K, V>>(parent.entrySet()).listIterator();
}
public boolean hasNext() {
return iterator.hasNext();
}
public Object next() {
last = (Map.Entry) iterator.next();
public K next() {
last = iterator.next();
return last.getKey();
}
public boolean hasPrevious() {
return iterator.hasPrevious();
}
public Object previous() {
last = (Map.Entry) iterator.previous();
public K previous() {
last = iterator.previous();
return last.getKey();
}
public void remove() {
iterator.remove();
parent.remove(last.getKey());
last = null;
}
public Object getKey() {
public K getKey() {
if (last == null) {
throw new IllegalStateException("Iterator getKey() can only be called after next() and before remove()");
}
return last.getKey();
}
public Object getValue() {
public V getValue() {
if (last == null) {
throw new IllegalStateException("Iterator getValue() can only be called after next() and before remove()");
}
return last.getValue();
}
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()");
}
if (parent.maps[1].containsKey(value) &&
parent.maps[1].get(value) != last.getKey()) {
if (parent.reverseMap.containsKey(value) &&
parent.reverseMap.get(value) != last.getKey()) {
throw new IllegalArgumentException("Cannot use setValue() when the object being set is already in the map");
}
return parent.put(last.getKey(), value);
}
public void reset() {
iterator = new ArrayList(parent.entrySet()).listIterator();
iterator = new ArrayList<Map.Entry<K, V>>(parent.entrySet()).listIterator();
last = null;
}
public String toString() {
if (last != null) {
return "MapIterator[" + getKey() + "=" + getValue() + "]";
} else {
return "MapIterator[]";
}
return "MapIterator[]";
}
}
// 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 TreeMap(comparator);
maps[1] = new TreeMap(comparator);
normalMap = new TreeMap(comparator);
reverseMap = new TreeMap(comparator);
Map map = (Map) in.readObject();
putAll(map);
}

View File

@ -5,9 +5,9 @@
* 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.
@ -33,39 +33,39 @@ import org.apache.commons.collections.set.UnmodifiableSet;
*
* @since Commons Collections 3.0
* @version $Revision$ $Date$
*
*
* @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);
}
@ -74,49 +74,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

@ -5,9 +5,9 @@
* 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.
@ -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;
@ -35,39 +33,39 @@ import org.apache.commons.collections.set.UnmodifiableSet;
*
* @since Commons Collections 3.0
* @version $Revision$ $Date$
*
*
* @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);
}
@ -76,55 +74,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

@ -5,9 +5,9 @@
* 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.
@ -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;
@ -38,39 +35,39 @@ import org.apache.commons.collections.set.UnmodifiableSet;
*
* @since Commons Collections 3.0
* @version $Revision$ $Date$
*
*
* @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);
}
@ -79,77 +76,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

@ -30,9 +30,11 @@ import org.apache.commons.collections.collection.AbstractCollectionDecorator;
*
* @author Stephen Colebourne
*/
public abstract class AbstractBufferDecorator<E>
extends AbstractCollectionDecorator<E>
implements Buffer<E> {
public abstract class AbstractBufferDecorator<E> extends AbstractCollectionDecorator<E> implements
Buffer<E> {
/** Serialization version */
private static final long serialVersionUID = -2629815475789577029L;
/**
* Constructor only used in deserialization, do not use otherwise.

View File

@ -45,7 +45,7 @@ import org.apache.commons.collections.iterators.AbstractIteratorDecorator;
* @version $Revision$ $Date$
* @since Commons Collections 3.2
*/
public class BoundedBuffer extends SynchronizedBuffer implements BoundedCollection {
public class BoundedBuffer<E> extends SynchronizedBuffer<E> implements BoundedCollection<E> {
/** The serialization version. */
private static final long serialVersionUID = 1536432911093974264L;
@ -67,8 +67,8 @@ public class BoundedBuffer extends SynchronizedBuffer implements BoundedCollecti
* @throws IllegalArgumentException if the buffer is null
* @throws IllegalArgumentException if the maximum size is zero or less
*/
public static BoundedBuffer decorate(Buffer buffer, int maximumSize) {
return new BoundedBuffer(buffer, maximumSize, 0L);
public static <E> BoundedBuffer<E> decorate(Buffer<E> buffer, int maximumSize) {
return new BoundedBuffer<E>(buffer, maximumSize, 0L);
}
/**
@ -82,8 +82,8 @@ public class BoundedBuffer extends SynchronizedBuffer implements BoundedCollecti
* @throws IllegalArgumentException if the buffer is null
* @throws IllegalArgumentException if the maximum size is zero or less
*/
public static BoundedBuffer decorate(Buffer buffer, int maximumSize, long timeout) {
return new BoundedBuffer(buffer, maximumSize, timeout);
public static <E> BoundedBuffer<E> decorate(Buffer<E> buffer, int maximumSize, long timeout) {
return new BoundedBuffer<E>(buffer, maximumSize, timeout);
}
//-----------------------------------------------------------------------
@ -97,7 +97,7 @@ public class BoundedBuffer extends SynchronizedBuffer implements BoundedCollecti
* @throws IllegalArgumentException if the buffer is null
* @throws IllegalArgumentException if the maximum size is zero or less
*/
protected BoundedBuffer(Buffer buffer, int maximumSize, long timeout) {
protected BoundedBuffer(Buffer<E> buffer, int maximumSize, long timeout) {
super(buffer);
if (maximumSize < 1) {
throw new IllegalArgumentException();
@ -107,29 +107,29 @@ public class BoundedBuffer extends SynchronizedBuffer implements BoundedCollecti
}
//-----------------------------------------------------------------------
public Object remove() {
public E remove() {
synchronized (lock) {
Object returnValue = decorated().remove();
E returnValue = decorated().remove();
lock.notifyAll();
return returnValue;
}
}
public boolean add(Object o) {
public boolean add(E o) {
synchronized (lock) {
timeoutWait(1);
return decorated().add(o);
}
}
public boolean addAll(final Collection c) {
public boolean addAll(final Collection<? extends E> c) {
synchronized (lock) {
timeoutWait(c.size());
return decorated().addAll(c);
}
}
public Iterator iterator() {
public Iterator<E> iterator() {
return new NotifyingIterator(collection.iterator());
}
@ -178,9 +178,9 @@ public class BoundedBuffer extends SynchronizedBuffer implements BoundedCollecti
/**
* BoundedBuffer iterator.
*/
private class NotifyingIterator extends AbstractIteratorDecorator {
private class NotifyingIterator extends AbstractIteratorDecorator<E> {
public NotifyingIterator(Iterator it) {
public NotifyingIterator(Iterator<E> it) {
super(it);
}

View File

@ -5,9 +5,9 @@
* 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.
@ -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>
@ -55,37 +55,37 @@ import org.apache.commons.collections.BufferUnderflowException;
*
* @since Commons Collections 3.0 (previously in main package v2.1)
* @version $Revision$ $Date$
*
*
* @author Avalon
* @author Berin Loritsch
* @author Paul Jack
* @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

@ -5,9 +5,9 @@
* 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.
@ -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>
@ -39,14 +39,14 @@ import java.util.Collection;
* This buffer prevents null objects from being added.
* <p>
* This class is Serializable from Commons Collections 3.1.
*
*
* @since Commons Collections 3.0
* @version $Revision$ $Date$
*
*
* @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;
@ -51,8 +51,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);
}
//-----------------------------------------------------------------------
@ -66,7 +66,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);
}
@ -75,16 +75,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

@ -5,9 +5,9 @@
* 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.
@ -50,7 +50,7 @@ import org.apache.commons.collections.BufferUnderflowException;
* This buffer prevents null objects from being added.
* <p>
* This class is Serializable from Commons Collections 3.1.
*
*
* @since Commons Collections 3.0 (previously in main package v2.1)
* @version $Revision$ $Date$
*
@ -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,31 +111,32 @@ public class UnboundedFifoBuffer extends AbstractCollection implements Buffer, S
//-----------------------------------------------------------------------
/**
* 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();
int size = in.readInt();
buffer = new Object[size + 1];
buffer = (E[]) new Object[size + 1];
for (int i = 0; i < size; i++) {
buffer[i] = in.readObject();
buffer[i] = (E) in.readObject();
}
head = 0;
tail = size;
@ -172,14 +176,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;) {
@ -205,7 +210,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");
}
@ -219,12 +224,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);
@ -234,7 +239,7 @@ public class UnboundedFifoBuffer extends AbstractCollection implements Buffer, S
/**
* Increments the internal index.
*
*
* @param index the index to increment
* @return the updated index
*/
@ -248,7 +253,7 @@ public class UnboundedFifoBuffer extends AbstractCollection implements Buffer, S
/**
* Decrements the internal index.
*
*
* @param index the index to decrement
* @return the updated index
*/
@ -265,8 +270,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;
@ -276,7 +281,7 @@ public class UnboundedFifoBuffer extends AbstractCollection implements Buffer, S
}
public Object next() {
public E next() {
if (!hasNext()) {
throw new NoSuchElementException();
}

View File

@ -37,8 +37,8 @@ import org.apache.commons.collections.iterators.UnmodifiableIterator;
*
* @author Stephen Colebourne
*/
public final class UnmodifiableBuffer
extends AbstractBufferDecorator
public final class UnmodifiableBuffer<E>
extends AbstractBufferDecorator<E>
implements Unmodifiable, Serializable {
/** Serialization version */
@ -53,11 +53,11 @@ public final class UnmodifiableBuffer
* @return an unmodifiable Buffer
* @throws IllegalArgumentException if buffer is null
*/
public static Buffer decorate(Buffer buffer) {
public static <E> Buffer<E> decorate(Buffer<E> buffer) {
if (buffer instanceof Unmodifiable) {
return buffer;
}
return new UnmodifiableBuffer(buffer);
return new UnmodifiableBuffer<E>(buffer);
}
//-----------------------------------------------------------------------
@ -67,7 +67,7 @@ public final class UnmodifiableBuffer
* @param buffer the buffer to decorate, must not be null
* @throws IllegalArgumentException if buffer is null
*/
private UnmodifiableBuffer(Buffer buffer) {
private UnmodifiableBuffer(Buffer<E> buffer) {
super(buffer);
}
@ -90,13 +90,14 @@ public final class UnmodifiableBuffer
* @throws IOException
* @throws ClassNotFoundException
*/
@SuppressWarnings("unchecked")
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
collection = (Collection) in.readObject();
collection = (Collection<E>) in.readObject();
}
//-----------------------------------------------------------------------
public Iterator iterator() {
public Iterator<E> iterator() {
return UnmodifiableIterator.decorate(decorated().iterator());
}
@ -104,7 +105,7 @@ public final class UnmodifiableBuffer
throw new UnsupportedOperationException();
}
public boolean addAll(Collection coll) {
public boolean addAll(Collection<? extends E> coll) {
throw new UnsupportedOperationException();
}
@ -116,16 +117,16 @@ public final class UnmodifiableBuffer
throw new UnsupportedOperationException();
}
public boolean removeAll(Collection coll) {
public boolean removeAll(Collection<?> coll) {
throw new UnsupportedOperationException();
}
public boolean retainAll(Collection coll) {
public boolean retainAll(Collection<?> coll) {
throw new UnsupportedOperationException();
}
//-----------------------------------------------------------------------
public Object remove() {
public E remove() {
throw new UnsupportedOperationException();
}

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

@ -5,9 +5,9 @@
* 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.
@ -31,7 +31,7 @@ import org.apache.commons.collections.list.UnmodifiableList;
* Decorates a collection of other collections to provide a single unified view.
* <p>
* Changes made to this collection will actually be made on the decorated collection.
* Add and remove operations require the use of a pluggable strategy. If no
* Add and remove operations require the use of a pluggable strategy. If no
* strategy is provided then add and remove are unsupported.
*
* @param <E> the type of the elements in the collection
@ -46,6 +46,7 @@ public class CompositeCollection<E> implements Collection<E> {
/** CollectionMutator to handle changes to the collection */
protected CollectionMutator<E> mutator;
/** Collections in the composite */
protected List<Collection<E>> all = new ArrayList<Collection<E>>();
@ -79,7 +80,7 @@ public class CompositeCollection<E> implements Collection<E> {
/**
* Create a Composite Collection with an array of collections.
*
*
* @param compositeCollections the collections to composite
*/
public CompositeCollection(Collection<E>[] compositeCollections) {
@ -89,7 +90,7 @@ public class CompositeCollection<E> implements Collection<E> {
// /**
// * Create a Composite Collection extracting the collections from an iterable.
// *
// *
// * @param compositeCollections the collections to composite
// */
// public CompositeCollection(Iterable<Collection<E>> compositeCollections) {
@ -121,7 +122,7 @@ public class CompositeCollection<E> implements Collection<E> {
* @return true if all of the contained collections are empty
*/
public boolean isEmpty() {
for (Collection<E> item : all) {
for (Collection<? extends E> item : all) {
if (item.isEmpty() == false) {
return false;
}
@ -138,7 +139,7 @@ public class CompositeCollection<E> implements Collection<E> {
* @return true if obj is contained in any of the contained collections
*/
public boolean contains(Object obj) {
for (Collection<E> item : all) {
for (Collection<? extends E> item : all) {
if (item.contains(obj)) {
return true;
}
@ -158,10 +159,10 @@ public class CompositeCollection<E> implements Collection<E> {
*/
public Iterator<E> iterator() {
if (all.isEmpty()) {
return EmptyIterator.INSTANCE;
return EmptyIterator.<E>getInstance();
}
IteratorChain chain = new IteratorChain();
for (Collection<E> item : all) {
IteratorChain<E> chain = new IteratorChain<E>();
for (Collection<? extends E> item : all) {
chain.addIterator(item.iterator());
}
return chain;
@ -197,11 +198,11 @@ public class CompositeCollection<E> implements Collection<E> {
} else {
result = (Object[]) Array.newInstance(array.getClass().getComponentType(), size);
}
int offset = 0;
for (Collection<E> item : all) {
for (Iterator<E> it = item.iterator(); it.hasNext();) {
result[offset++] = it.next();
for (Collection<? extends E> item : all) {
for (E e : item) {
result[offset++] = e;
}
}
if (result.length > size) {
@ -301,7 +302,7 @@ public class CompositeCollection<E> implements Collection<E> {
return false;
}
boolean changed = false;
for (Collection<E> item : all) {
for (Collection<? extends E> item : all) {
changed |= item.removeAll(coll);
}
return changed;
@ -319,7 +320,7 @@ public class CompositeCollection<E> implements Collection<E> {
*/
public boolean retainAll(final Collection<?> coll) {
boolean changed = false;
for (Collection<E> item : all) {
for (Collection<? extends E> item : all) {
changed |= item.retainAll(coll);
}
return changed;
@ -333,7 +334,7 @@ public class CompositeCollection<E> implements Collection<E> {
* @throws UnsupportedOperationException if clear is unsupported
*/
public void clear() {
for (Collection<E> coll : all) {
for (Collection<? extends E> coll : all) {
coll.clear();
}
}
@ -413,18 +414,26 @@ public class CompositeCollection<E> implements Collection<E> {
*
* @return Unmodifiable list of all collections in this composite.
*/
public List<Collection<E>> getCollections() {
public List<? extends Collection<E>> getCollections() {
return UnmodifiableList.decorate(all);
}
/**
* Get the collection mutator to be used for this CompositeCollection.
* @return CollectionMutator<E>
*/
protected CollectionMutator<E> getMutator() {
return mutator;
}
//-----------------------------------------------------------------------
/**
* Pluggable strategy to handle changes to the composite.
*
*
* @param <E> the element being held in the collection
*/
public interface CollectionMutator<E> {
/**
* Called when an object is to be added to the composite.
*
@ -438,7 +447,7 @@ public class CompositeCollection<E> implements Collection<E> {
* @throws IllegalArgumentException if the object cannot be added
*/
public boolean add(CompositeCollection<E> composite, List<Collection<E>> collections, E obj);
/**
* Called when a collection is to be added to the composite.
*
@ -452,7 +461,7 @@ public class CompositeCollection<E> implements Collection<E> {
* @throws IllegalArgumentException if the object cannot be added
*/
public boolean addAll(CompositeCollection<E> composite, List<Collection<E>> collections, Collection<? extends E> coll);
/**
* Called when an object is to be removed to the composite.
*
@ -466,7 +475,7 @@ public class CompositeCollection<E> implements Collection<E> {
* @throws IllegalArgumentException if the object cannot be removed
*/
public boolean remove(CompositeCollection<E> composite, List<Collection<E>> collections, Object obj);
}
}

View File

@ -44,7 +44,7 @@ public class TransformedCollection<E> extends AbstractCollectionDecorator<E> {
private static final long serialVersionUID = 8692300188161871514L;
/** The transformer to use */
protected final Transformer<E, E> transformer;
protected final Transformer<? super E, ? extends E> transformer;
/**
* Factory method to create a transforming collection.
@ -57,8 +57,8 @@ public class TransformedCollection<E> extends AbstractCollectionDecorator<E> {
* @return a new transformed collection
* @throws IllegalArgumentException if collection or transformer is null
*/
public static Collection decorate(Collection coll, Transformer transformer) {
return new TransformedCollection(coll, transformer);
public static <E> Collection<E> decorate(Collection<E> coll, Transformer<? super E, ? extends E> transformer) {
return new TransformedCollection<E>(coll, transformer);
}
//-----------------------------------------------------------------------
@ -72,7 +72,7 @@ public class TransformedCollection<E> extends AbstractCollectionDecorator<E> {
* @param transformer the transformer to use for conversion, must not be null
* @throws IllegalArgumentException if collection or transformer is null
*/
protected TransformedCollection(Collection coll, Transformer transformer) {
protected TransformedCollection(Collection<E> coll, Transformer<? super E, ? extends E> transformer) {
super(coll);
if (transformer == null) {
throw new IllegalArgumentException("Transformer must not be null");
@ -88,8 +88,8 @@ public class TransformedCollection<E> extends AbstractCollectionDecorator<E> {
* @param object the object to transform
* @return a transformed object
*/
protected E transform(Object object) {
return transformer.transform((E) object);
protected E transform(E object) {
return transformer.transform(object);
}
/**
@ -100,20 +100,20 @@ public class TransformedCollection<E> extends AbstractCollectionDecorator<E> {
* @param coll the collection to transform
* @return a transformed object
*/
protected Collection transform(Collection coll) {
List list = new ArrayList(coll.size());
for (Object item : coll) {
protected Collection<E> transform(Collection<? extends E> coll) {
List<E> list = new ArrayList<E>(coll.size());
for (E item : coll) {
list.add(transform(item));
}
return list;
}
//-----------------------------------------------------------------------
public boolean add(Object object) {
public boolean add(E object) {
return decorated().add(transform(object));
}
public boolean addAll(Collection coll) {
public boolean addAll(Collection<? extends E> coll) {
return decorated().addAll(transform(coll));
}

View File

@ -5,9 +5,9 @@
* 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.
@ -23,11 +23,11 @@ import org.apache.commons.collections.BoundedCollection;
import org.apache.commons.collections.iterators.UnmodifiableIterator;
/**
* <code>UnmodifiableBoundedCollection</code> decorates another
* <code>UnmodifiableBoundedCollection</code> decorates another
* <code>BoundedCollection</code> to ensure it can't be altered.
* <p>
* If a BoundedCollection is first wrapped in some other collection decorator,
* such as synchronized or predicated, the BoundedCollection methods are no
* such as synchronized or predicated, the BoundedCollection methods are no
* longer accessible.
* The factory on this class will attempt to retrieve the bounded nature by
* examining the package scope variables.
@ -36,81 +36,80 @@ import org.apache.commons.collections.iterators.UnmodifiableIterator;
*
* @since Commons Collections 3.0
* @version $Revision$ $Date$
*
*
* @author Stephen Colebourne
*/
public final class UnmodifiableBoundedCollection
extends AbstractCollectionDecorator
implements BoundedCollection {
public final class UnmodifiableBoundedCollection<E> extends AbstractCollectionDecorator<E>
implements BoundedCollection<E> {
/** Serialization version */
private static final long serialVersionUID = -7112672385450340330L;
/**
* Factory method to create an unmodifiable bounded collection.
*
*
* @param coll the <code>BoundedCollection</code> to decorate, must not be null
* @return a new unmodifiable bounded collection
* @throws IllegalArgumentException if bag is null
*/
public static BoundedCollection decorate(BoundedCollection coll) {
return new UnmodifiableBoundedCollection(coll);
public static <E> BoundedCollection<E> decorate(BoundedCollection<E> coll) {
return new UnmodifiableBoundedCollection<E>(coll);
}
/**
* Factory method to create an unmodifiable bounded collection.
* <p>
* This method is capable of drilling down through up to 1000 other decorators
* This method is capable of drilling down through up to 1000 other decorators
* to find a suitable BoundedCollection.
*
*
* @param coll the <code>BoundedCollection</code> to decorate, must not be null
* @return a new unmodifiable bounded collection
* @throws IllegalArgumentException if bag is null
*/
public static BoundedCollection decorateUsing(Collection coll) {
@SuppressWarnings("unchecked")
public static <E> BoundedCollection<E> decorateUsing(Collection<? super E> coll) {
if (coll == null) {
throw new IllegalArgumentException("The collection must not be null");
}
// handle decorators
for (int i = 0; i < 1000; i++) { // counter to prevent infinite looping
if (coll instanceof BoundedCollection) {
break; // normal loop exit
} else if (coll instanceof AbstractCollectionDecorator) {
coll = ((AbstractCollectionDecorator) coll).collection;
}
if (coll instanceof AbstractCollectionDecorator) {
coll = ((AbstractCollectionDecorator<E>) coll).collection;
} else if (coll instanceof SynchronizedCollection) {
coll = ((SynchronizedCollection) coll).collection;
} else {
break; // normal loop exit
coll = ((SynchronizedCollection<E>) coll).collection;
}
}
if (coll instanceof BoundedCollection == false) {
throw new IllegalArgumentException("The collection is not a bounded collection");
}
return new UnmodifiableBoundedCollection((BoundedCollection) coll);
}
return new UnmodifiableBoundedCollection((BoundedCollection<E>) coll);
}
/**
* Constructor that wraps (not copies).
*
*
* @param coll the collection to decorate, must not be null
* @throws IllegalArgumentException if coll is null
*/
private UnmodifiableBoundedCollection(BoundedCollection coll) {
private UnmodifiableBoundedCollection(BoundedCollection<E> coll) {
super(coll);
}
//-----------------------------------------------------------------------
public Iterator iterator() {
public Iterator<E> iterator() {
return UnmodifiableIterator.decorate(decorated().iterator());
}
public boolean add(Object object) {
public boolean add(E object) {
throw new UnsupportedOperationException();
}
public boolean addAll(Collection coll) {
public boolean addAll(Collection<? extends E> coll) {
throw new UnsupportedOperationException();
}
@ -122,21 +121,28 @@ public final class UnmodifiableBoundedCollection
throw new UnsupportedOperationException();
}
public boolean removeAll(Collection coll) {
public boolean removeAll(Collection<?> coll) {
throw new UnsupportedOperationException();
}
public boolean retainAll(Collection coll) {
public boolean retainAll(Collection<?> coll) {
throw new UnsupportedOperationException();
}
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
public boolean isFull() {
return ((BoundedCollection) collection).isFull();
return decorated().isFull();
}
public int maxSize() {
return ((BoundedCollection) collection).maxSize();
return decorated().maxSize();
}
/**
* {@inheritDoc}
*/
@Override
protected BoundedCollection<E> decorated() {
return (BoundedCollection<E>) super.decorated();
}
}

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

@ -42,13 +42,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();
//-----------------------------------------------------------------------
/**
@ -60,8 +61,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;
}
//-----------------------------------------------------------------------
@ -88,8 +90,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

@ -5,9 +5,9 @@
* 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.
@ -34,33 +34,33 @@ import java.util.List;
* to multi-column sorting in SQL, and this class
* allows Java classes to emulate that kind of behaviour
* when sorting a List.</p>
*
*
* <p>To further facilitate SQL-like sorting, the order of
* any single Comparator in the list can be reversed.</p>
*
*
* <p>Calling a method that adds new Comparators or
* changes the ascend/descend sort <i>after compare(Object,
* Object) has been called</i> will result in an
* UnsupportedOperationException. However, <i>take care</i>
* to not alter the underlying List of Comparators
* or the BitSet that defines the sort order.</p>
*
*
* <p>Instances of ComparatorChain are not synchronized.
* The class is not thread-safe at construction time, but
* it <i>is</i> thread-safe to perform multiple comparisons
* after all the setup operations are complete.</p>
*
*
* @since Commons Collections 2.0
* @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

@ -5,9 +5,9 @@
* 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.
@ -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.
@ -40,7 +39,7 @@ import java.util.Map;
* Instances of FixedOrderComparator are not synchronized. The class is not
* thread-safe at construction time, but it is thread-safe to perform
* multiple comparisons after all the setup operations are complete.
*
*
* @since Commons Collections 3.0
* @version $Revision$ $Date$
*
@ -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;
/**
* A Comparator that will compare nulls to be either lower or higher than
* other objects.
@ -28,7 +30,7 @@ import java.util.Comparator;
*
* @author Michael A. Smith
*/
public class NullComparator implements Comparator, Serializable {
public class NullComparator<E> implements Comparator<E>, Serializable {
/** Serialization version. */
private static final long serialVersionUID = -5820772575483504339L;
@ -36,7 +38,7 @@ public class NullComparator implements Comparator, Serializable {
/**
* The comparator to use when comparing two non-<code>null</code> objects.
**/
private Comparator nonNullComparator;
private Comparator<E> nonNullComparator;
/**
* Specifies whether a <code>null</code> are compared as higher than
@ -51,8 +53,9 @@ public class NullComparator implements Comparator, Serializable {
* non-<code>null</code> objects, the {@link ComparableComparator} is
* used.
**/
@SuppressWarnings("unchecked")
public NullComparator() {
this(ComparableComparator.getInstance(), true);
this(ComparatorUtils.NATURAL_COMPARATOR, true);
}
/**
@ -68,7 +71,7 @@ public class NullComparator implements Comparator, Serializable {
* @exception NullPointerException if <code>nonNullComparator</code> is
* <code>null</code>
**/
public NullComparator(Comparator nonNullComparator) {
public NullComparator(Comparator<E> nonNullComparator) {
this(nonNullComparator, true);
}
@ -84,8 +87,9 @@ public class NullComparator implements Comparator, Serializable {
* that <code>null</code> should be compared as lower than a
* non-<code>null</code> object.
**/
@SuppressWarnings("unchecked")
public NullComparator(boolean nullsAreHigh) {
this(ComparableComparator.getInstance(), nullsAreHigh);
this(ComparatorUtils.NATURAL_COMPARATOR, nullsAreHigh);
}
/**
@ -107,11 +111,11 @@ public class NullComparator implements Comparator, Serializable {
* @exception NullPointerException if <code>nonNullComparator</code> is
* <code>null</code>
**/
public NullComparator(Comparator nonNullComparator, boolean nullsAreHigh) {
public NullComparator(Comparator<E> nonNullComparator, boolean nullsAreHigh) {
this.nonNullComparator = nonNullComparator;
this.nullsAreHigh = nullsAreHigh;
if(nonNullComparator == null) {
if (nonNullComparator == null) {
throw new NullPointerException("null nonNullComparator");
}
}
@ -133,7 +137,7 @@ public class NullComparator implements Comparator, Serializable {
* "higher" than (greater than, after, etc.) <code>o2</code>; or
* <code>0</code> if <code>o1</code> and <code>o2</code> are equal.
**/
public int compare(Object o1, Object o2) {
public int compare(E o1, E o2) {
if(o1 == o2) { return 0; }
if(o1 == null) { return (this.nullsAreHigh ? 1 : -1); }
if(o2 == null) { return (this.nullsAreHigh ? -1 : 1); }
@ -167,7 +171,7 @@ public class NullComparator implements Comparator, Serializable {
if(obj == this) { return true; }
if(!obj.getClass().equals(this.getClass())) { return false; }
NullComparator other = (NullComparator)obj;
NullComparator<?> other = (NullComparator<?>) obj;
return ((this.nullsAreHigh == other.nullsAreHigh) &&
(this.nonNullComparator.equals(other.nonNullComparator)));

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.
@ -31,13 +33,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;
//-----------------------------------------------------------------------
/**
@ -61,12 +63,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;
}
//-----------------------------------------------------------------------
@ -77,7 +76,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);
}
@ -110,16 +109,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

@ -99,7 +99,7 @@ public final class AllPredicate<T> implements Predicate<T>, PredicateDecorator<T
* @throws IllegalArgumentException if any predicate in the array is null
* @deprecated Use {@link #allPredicate(Collection<Predicate<? super T>>)} instead
*/
public static <T> Predicate<T> getInstance(Collection<Predicate<? super T>> predicates) {
public static <T> Predicate<T> getInstance(Collection<Predicate<T>> predicates) {
return allPredicate(predicates);
}
@ -114,13 +114,13 @@ public final class AllPredicate<T> implements Predicate<T>, PredicateDecorator<T
* @throws IllegalArgumentException if the predicates array is null
* @throws IllegalArgumentException if any predicate in the array is null
*/
public static <T> Predicate<T> allPredicate(Collection<Predicate<? super T>> predicates) {
final Predicate<? super T>[] preds = validate(predicates);
public static <T> Predicate<T> allPredicate(Collection<? extends Predicate<T>> predicates) {
final Predicate<T>[] preds = validate(predicates);
if (preds.length == 0) {
return truePredicate();
}
if (preds.length == 1) {
return coerce(preds[0]);
return preds[0];
}
return new AllPredicate<T>(preds);
}

View File

@ -5,9 +5,9 @@
* 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.
@ -22,45 +22,45 @@ import org.apache.commons.collections.Predicate;
/**
* Predicate implementation that returns true if both the predicates return true.
*
*
* @since Commons Collections 3.0
* @version $Revision$ $Date$
*
* @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

@ -5,9 +5,9 @@
* 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.
@ -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

@ -62,7 +62,7 @@ public final class EqualPredicate<T> implements Predicate<T>, Serializable {
* @return the predicate
* @throws IllegalArgumentException if the predicate is null
*/
public static <T, O extends T> Predicate<T> equalPredicate(O object) {
public static <T> Predicate<T> equalPredicate(T object) {
if (object == null) {
return nullPredicate();
}

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

@ -5,9 +5,9 @@
* 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.
@ -23,28 +23,29 @@ import org.apache.commons.collections.Predicate;
/**
* Predicate implementation that always throws an exception.
*
*
* @since Commons Collections 3.0
* @version $Revision$ $Date$
*
* @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

@ -5,9 +5,9 @@
* 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.
@ -23,29 +23,29 @@ import org.apache.commons.collections.Transformer;
/**
* Transformer implementation that always throws an exception.
*
*
* @since Commons Collections 3.0
* @version $Revision$ $Date$
*
* @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

@ -5,9 +5,9 @@
* 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.
@ -22,28 +22,40 @@ import org.apache.commons.collections.Predicate;
/**
* Predicate implementation that always returns false.
*
*
* @since Commons Collections 3.0
* @version $Revision$ $Date$
*
* @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

@ -5,9 +5,9 @@
* 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.
@ -24,7 +24,7 @@ import org.apache.commons.collections.Transformer;
/**
* Internal utilities for functors.
*
*
* @since Commons Collections 3.0
* @version $Revision$ $Date$
*
@ -32,38 +32,38 @@ import org.apache.commons.collections.Transformer;
* @author Matt Benson
*/
class FunctorUtils {
/**
* Restricted constructor.
*/
private FunctorUtils() {
super();
}
/**
* Clone the predicates to ensure that the internal reference can't be messed with.
* Due to the {@link Predicate#evaluate(T)} method, Predicate<? super T> is
* able to be coerced to Predicate<T> without casting issues.
*
* able to be coerced to Predicate<T> without casting issues.
*
* @param predicates the predicates to copy
* @return the cloned predicates
*/
@SuppressWarnings("unchecked")
static <T> Predicate<? super T>[] copy(Predicate<? super T>[] predicates) {
static <T> Predicate<T>[] copy(Predicate<? super T>[] predicates) {
if (predicates == null) {
return null;
}
return predicates.clone();
return (Predicate<T>[]) predicates.clone();
}
/**
* A very simple method that coerces Predicate<? super T> to Predicate<T>.
* Due to the {@link Predicate#evaluate(T)} method, Predicate<? super T> is
* able to be coerced to Predicate<T> without casting issues.
* able to be coerced to Predicate<T> without casting issues.
* <p>This method exists
* simply as centralised documentation and atomic unchecked warning
* suppression.
*
*
* @param <T> the type of object the returned predicate should "accept"
* @param predicate the predicate to coerce.
* @return the coerced predicate.
@ -72,10 +72,10 @@ class FunctorUtils {
static <T> Predicate<T> coerce(Predicate<? super T> predicate){
return (Predicate<T>) predicate;
}
/**
* Validate the predicates to ensure that all is well.
*
*
* @param predicates the predicates to validate
*/
static void validate(Predicate<?>[] predicates) {
@ -88,22 +88,22 @@ class FunctorUtils {
}
}
}
/**
* Validate the predicates to ensure that all is well.
*
*
* @param predicates the predicates to validate
* @return predicate array
*/
@SuppressWarnings("unchecked")
static <T> Predicate<? super T>[] validate(Collection<Predicate<? super T>> predicates) {
static <T> Predicate<T>[] validate(Collection<? extends Predicate<T>> predicates) {
if (predicates == null) {
throw new IllegalArgumentException("The predicate collection must not be null");
}
// convert to array like this to guarantee iterator() ordering
Predicate<? super T>[] preds = new Predicate[predicates.size()];
Predicate<T>[] preds = new Predicate[predicates.size()];
int i = 0;
for (Predicate<? super T> predicate : predicates) {
for (Predicate<T> predicate : predicates) {
preds[i] = predicate;
if (preds[i] == null) {
throw new IllegalArgumentException("The predicate collection must not contain a null predicate, index " + i + " was null");
@ -112,26 +112,27 @@ class FunctorUtils {
}
return preds;
}
/**
* Clone the closures to ensure that the internal reference can't be messed with.
*
*
* @param closures the closures to copy
* @return the cloned closures
*/
static Closure[] copy(Closure[] closures) {
@SuppressWarnings("unchecked")
static <E> Closure<E>[] copy(Closure<? super E>[] closures) {
if (closures == null) {
return null;
}
return (Closure[]) closures.clone();
return (Closure<E>[]) closures.clone();
}
/**
* Validate the closures to ensure that all is well.
*
*
* @param closures the closures to validate
*/
static void validate(Closure[] closures) {
static void validate(Closure<?>[] closures) {
if (closures == null) {
throw new IllegalArgumentException("The closure array must not be null");
}
@ -142,25 +143,41 @@ class FunctorUtils {
}
}
/**
* A very simple method that coerces Closure<? super T> to Closure<T>.
* <p>This method exists
* simply as centralised documentation and atomic unchecked warning
* suppression.
*
* @param <T> the type of object the returned closure should "accept"
* @param closure the closure to coerce.
* @return the coerced closure.
*/
@SuppressWarnings("unchecked")
static <T> Closure<T> coerce(Closure<? super T> closure){
return (Closure<T>) closure;
}
/**
* Copy method
*
*
* @param transformers the transformers to copy
* @return a clone of the transformers
*/
static Transformer[] copy(Transformer[] transformers) {
@SuppressWarnings("unchecked")
static <I, O> Transformer<I, O>[] copy(Transformer<? super I, ? extends O>[] transformers) {
if (transformers == null) {
return null;
}
return (Transformer[]) transformers.clone();
return (Transformer<I, O>[]) transformers.clone();
}
/**
* Validate method
*
*
* @param transformers the transformers to validate
*/
static void validate(Transformer[] transformers) {
static void validate(Transformer<?, ?>[] transformers) {
if (transformers == null) {
throw new IllegalArgumentException("The transformer array must not be null");
}
@ -172,4 +189,19 @@ class FunctorUtils {
}
}
/**
* A very simple method that coerces Transformer<? super I, ? extends O> to Transformer<I, O>.
* <p>This method exists
* simply as centralised documentation and atomic unchecked warning
* suppression.
*
* @param <T> the type of object the returned transformer should "accept"
* @param transformer the transformer to coerce.
* @return the coerced transformer.
*/
@SuppressWarnings("unchecked")
static <I, O> Transformer<I, O> coerce(Transformer<? super I, ? extends O> transformer) {
return (Transformer<I, O>) transformer;
}
}

View File

@ -5,9 +5,9 @@
* 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.
@ -23,42 +23,41 @@ import org.apache.commons.collections.Predicate;
/**
* Predicate implementation that returns true if the input is the same object
* as the one stored in this predicate.
*
*
* @since Commons Collections 3.0
* @version $Revision$ $Date$
*
* @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

@ -5,9 +5,9 @@
* 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.
@ -23,28 +23,28 @@ import org.apache.commons.collections.Predicate;
/**
* Predicate implementation that returns true if the input is an instanceof
* the type stored in this predicate.
*
*
* @since Commons Collections 3.0
* @version $Revision$ $Date$
*
* @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

@ -39,7 +39,7 @@ public class InstantiateFactory<T> implements Factory<T>, Serializable {
/** The class to create */
private final Class<T> iClassToInstantiate;
/** The constructor parameter types */
private final Class[] iParamTypes;
private final Class<?>[] iParamTypes;
/** The constructor arguments */
private final Object[] iArgs;
/** The constructor */
@ -53,7 +53,7 @@ public class InstantiateFactory<T> implements Factory<T>, Serializable {
* @param args the constructor arguments
* @return a new instantiate factory
*/
public static <T> Factory<T> getInstance(Class<T> classToInstantiate, Class[] paramTypes, Object[] args) {
public static <T> Factory<T> getInstance(Class<T> classToInstantiate, Class<?>[] paramTypes, Object[] args) {
if (classToInstantiate == null) {
throw new IllegalArgumentException("Class to instantiate must not be null");
}
@ -93,7 +93,7 @@ public class InstantiateFactory<T> implements Factory<T>, Serializable {
* @param paramTypes the constructor parameter types, not cloned
* @param args the constructor arguments, not cloned
*/
public InstantiateFactory(Class<T> classToInstantiate, Class[] paramTypes, Object[] args) {
public InstantiateFactory(Class<T> classToInstantiate, Class<?>[] paramTypes, Object[] args) {
super();
iClassToInstantiate = classToInstantiate;
iParamTypes = paramTypes;
@ -126,7 +126,6 @@ public class InstantiateFactory<T> implements Factory<T>, Serializable {
try {
return iConstructor.newInstance(iArgs);
} catch (InstantiationException ex) {
throw new FunctorException("InstantiateFactory: InstantiationException", ex);
} catch (IllegalAccessException ex) {

View File

@ -5,9 +5,9 @@
* 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.
@ -25,33 +25,42 @@ import org.apache.commons.collections.Transformer;
/**
* Transformer implementation that creates a new object instance by reflection.
*
*
* @since Commons Collections 3.0
* @version $Revision$ $Date$
*
* @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

@ -5,9 +5,9 @@
* 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.
@ -24,63 +24,63 @@ import org.apache.commons.collections.Transformer;
/**
* Transformer implementation that returns the value held in a specified map
* using the input parameter as a key.
*
*
* @since Commons Collections 3.0
* @version $Revision$ $Date$
*
* @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

@ -5,9 +5,9 @@
* 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.
@ -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

@ -5,9 +5,9 @@
* 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.
@ -22,41 +22,41 @@ import org.apache.commons.collections.Predicate;
/**
* Predicate implementation that returns false if the input is null.
*
*
* @since Commons Collections 3.0
* @version $Revision$ $Date$
*
* @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

@ -5,9 +5,9 @@
* 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.
@ -22,45 +22,45 @@ import org.apache.commons.collections.Predicate;
/**
* Predicate implementation that returns true if either of the predicates return true.
*
*
* @since Commons Collections 3.0
* @version $Revision$ $Date$
*
* @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

@ -23,20 +23,20 @@ import org.apache.commons.collections.Transformer;
/**
* Transformer implementation that calls a Predicate using the input object
* and then returns the input.
* and then returns the result.
*
* @since Commons Collections 3.0
* @version $Revision$ $Date$
*
* @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;
}

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