From d16bc8509fc423540a131184552649de1bbcaf98 Mon Sep 17 00:00:00 2001 From: Henri Yandell Date: Tue, 15 Sep 2009 05:29:56 +0000 Subject: [PATCH] Merging from -r468106:814127 of collections_jdk5_branch - namely where this code was generified in commit r738956. git-svn-id: https://svn.apache.org/repos/asf/commons/proper/collections/trunk@814997 13f79535-47bb-0310-9956-ffa450edef68 --- .../commons/collections/ArrayStack.java | 14 +- .../collections/BoundedCollection.java | 2 +- .../collections/BufferOverflowException.java | 3 + .../collections/BufferUnderflowException.java | 3 + .../apache/commons/collections/Closure.java | 7 +- .../commons/collections/ComparatorUtils.java | 48 +- .../commons/collections/EnumerationUtils.java | 19 +- .../apache/commons/collections/Factory.java | 6 +- .../commons/collections/FunctorException.java | 7 +- .../apache/commons/collections/Predicate.java | 6 +- .../commons/collections/Transformer.java | 7 +- .../collections/bag/AbstractMapBag.java | 270 +-- .../commons/collections/bag/HashBag.java | 10 +- .../collections/bag/TransformedBag.java | 28 +- .../collections/bag/TransformedSortedBag.java | 23 +- .../commons/collections/bag/TreeBag.java | 64 +- .../collections/bidimap/DualHashBidiMap.java | 22 +- .../collections/bidimap/TreeBidiMap.java | 1594 +++++++++-------- .../bidimap/UnmodifiableBidiMap.java | 48 +- .../bidimap/UnmodifiableOrderedBidiMap.java | 56 +- .../bidimap/UnmodifiableSortedBidiMap.java | 73 +- .../collections/buffer/BoundedFifoBuffer.java | 66 +- .../buffer/CircularFifoBuffer.java | 16 +- .../collections/buffer/PriorityBuffer.java | 71 +- .../collections/buffer/TransformedBuffer.java | 19 +- .../buffer/UnboundedFifoBuffer.java | 43 +- .../AbstractUntypedCollectionDecorator.java | 125 ++ .../comparators/BooleanComparator.java | 18 +- .../comparators/ComparableComparator.java | 14 +- .../comparators/ComparatorChain.java | 112 +- .../comparators/FixedOrderComparator.java | 143 +- .../comparators/ReverseComparator.java | 32 +- .../comparators/TransformingComparator.java | 20 +- .../collections/functors/AndPredicate.java | 29 +- .../collections/functors/AnyPredicate.java | 40 +- .../collections/functors/ChainedClosure.java | 39 +- .../functors/ChainedTransformer.java | 37 +- .../functors/CloneTransformer.java | 11 +- .../functors/ClosureTransformer.java | 14 +- .../collections/functors/ConstantFactory.java | 19 +- .../functors/ConstantTransformer.java | 55 +- .../functors/ExceptionClosure.java | 12 +- .../functors/ExceptionFactory.java | 12 +- .../functors/ExceptionPredicate.java | 19 +- .../functors/ExceptionTransformer.java | 16 +- .../functors/FactoryTransformer.java | 14 +- .../collections/functors/FalsePredicate.java | 30 +- .../collections/functors/ForClosure.java | 19 +- .../functors/IdentityPredicate.java | 27 +- .../collections/functors/IfClosure.java | 30 +- .../functors/InstanceofPredicate.java | 20 +- .../functors/InstantiateTransformer.java | 41 +- .../functors/InvokerTransformer.java | 24 +- .../collections/functors/MapTransformer.java | 26 +- .../collections/functors/NOPClosure.java | 26 +- .../collections/functors/NOPTransformer.java | 11 +- .../collections/functors/NonePredicate.java | 34 +- .../functors/NotNullPredicate.java | 11 +- .../collections/functors/NotPredicate.java | 15 +- .../functors/NullIsExceptionPredicate.java | 17 +- .../functors/NullIsFalsePredicate.java | 29 +- .../functors/NullIsTruePredicate.java | 17 +- .../collections/functors/OnePredicate.java | 25 +- .../collections/functors/OrPredicate.java | 29 +- .../functors/PredicateTransformer.java | 16 +- .../functors/PrototypeFactory.java | 40 +- .../functors/StringValueTransformer.java | 11 +- .../collections/functors/SwitchClosure.java | 82 +- .../functors/SwitchTransformer.java | 58 +- .../functors/TransformedPredicate.java | 36 +- .../functors/TransformerClosure.java | 16 +- .../functors/TransformerPredicate.java | 35 +- .../collections/functors/UniquePredicate.java | 18 +- .../collections/functors/WhileClosure.java | 18 +- .../iterators/AbstractEmptyIterator.java | 22 +- .../iterators/AbstractIteratorDecorator.java | 37 +- .../AbstractMapIteratorDecorator.java | 16 +- .../AbstractOrderedMapIteratorDecorator.java | 18 +- .../iterators/CollatingIterator.java | 225 +-- .../collections/iterators/EmptyIterator.java | 27 +- .../iterators/EmptyListIterator.java | 36 +- .../iterators/EmptyMapIterator.java | 16 +- .../iterators/EmptyOrderedIterator.java | 14 +- .../iterators/EmptyOrderedMapIterator.java | 16 +- .../iterators/EntrySetMapIterator.java | 23 +- .../iterators/EnumerationIterator.java | 20 +- .../collections/iterators/FilterIterator.java | 30 +- .../iterators/FilterListIterator.java | 82 +- .../collections/iterators/IteratorChain.java | 190 +- .../iterators/IteratorEnumeration.java | 61 +- .../iterators/LoopingIterator.java | 10 +- .../iterators/LoopingListIterator.java | 27 +- .../iterators/ObjectArrayIterator.java | 18 +- .../iterators/ReverseListIterator.java | 20 +- .../iterators/SingletonListIterator.java | 14 +- .../iterators/TransformIterator.java | 31 +- .../iterators/UniqueFilterIterator.java | 10 +- .../iterators/UnmodifiableIterator.java | 14 +- .../iterators/UnmodifiableListIterator.java | 18 +- .../iterators/UnmodifiableMapIterator.java | 20 +- .../UnmodifiableOrderedMapIterator.java | 25 +- .../keyvalue/AbstractKeyValue.java | 12 +- .../keyvalue/AbstractMapEntry.java | 9 +- .../keyvalue/AbstractMapEntryDecorator.java | 14 +- .../collections/keyvalue/DefaultKeyValue.java | 21 +- .../collections/keyvalue/DefaultMapEntry.java | 8 +- .../collections/keyvalue/MultiKey.java | 60 +- .../collections/keyvalue/TiedMapEntry.java | 16 +- .../keyvalue/UnmodifiableMapEntry.java | 10 +- .../collections/list/AbstractLinkedList.java | 325 ++-- .../AbstractSerializableListDecorator.java | 9 +- .../list/CursorableLinkedList.java | 99 +- .../list/NodeCachingLinkedList.java | 29 +- .../collections/list/SetUniqueList.java | 167 +- .../collections/list/TransformedList.java | 49 +- .../commons/collections/list/TreeList.java | 197 +- .../collections/map/AbstractHashedMap.java | 488 ++--- .../map/AbstractInputCheckedMapDecorator.java | 56 +- .../collections/map/AbstractLinkedMap.java | 227 ++- .../collections/map/AbstractReferenceMap.java | 427 ++--- .../collections/map/CaseInsensitiveMap.java | 11 +- .../collections/map/FixedSizeSortedMap.java | 61 +- .../commons/collections/map/Flat3Map.java | 310 ++-- .../commons/collections/map/HashedMap.java | 24 +- .../commons/collections/map/IdentityMap.java | 54 +- .../commons/collections/map/LRUMap.java | 76 +- .../commons/collections/map/LinkedMap.java | 83 +- .../commons/collections/map/MultiKeyMap.java | 292 ++- .../collections/map/PredicatedSortedMap.java | 40 +- .../collections/map/ReferenceIdentityMap.java | 23 +- .../commons/collections/map/ReferenceMap.java | 16 +- .../commons/collections/map/SingletonMap.java | 126 +- .../collections/map/UnmodifiableEntrySet.java | 56 +- .../collections/map/UnmodifiableMap.java | 42 +- .../set/AbstractSerializableSetDecorator.java | 9 +- .../commons/collections/set/CompositeSet.java | 89 +- .../commons/collections/set/MapBackedSet.java | 34 +- .../collections/set/TransformedSet.java | 11 +- .../collections/set/TransformedSortedSet.java | 39 +- .../collections/AbstractTestObject.java | 2 +- .../apache/commons/collections/BulkTest.java | 24 +- .../commons/collections/LocalTestNode.java | 30 +- .../commons/collections/TestArrayList.java | 21 +- .../commons/collections/TestArrayStack.java | 28 +- .../commons/collections/TestBufferUtils.java | 6 +- .../collections/TestEnumerationUtils.java | 18 +- .../commons/collections/TestLinkedList.java | 75 +- .../commons/collections/TestSetUtils.java | 35 +- .../commons/collections/TestTreeMap.java | 22 +- .../collections/TestTypedCollection.java | 23 +- .../bag/AbstractTestSortedBag.java | 12 +- .../commons/collections/bag/TestHashBag.java | 6 +- .../collections/bag/TestPredicatedBag.java | 69 +- .../collections/bag/TestTransformedBag.java | 19 +- .../bag/TestTransformedSortedBag.java | 20 +- .../commons/collections/bag/TestTreeBag.java | 101 +- .../bidimap/AbstractTestOrderedBidiMap.java | 96 +- .../bidimap/AbstractTestSortedBidiMap.java | 403 +++-- .../TestAbstractOrderedBidiMapDecorator.java | 37 +- .../bidimap/TestDualHashBidiMap.java | 13 +- .../bidimap/TestDualTreeBidiMap.java | 11 +- .../bidimap/TestDualTreeBidiMap2.java | 31 +- .../collections/bidimap/TestTreeBidiMap.java | 11 +- .../bidimap/TestUnmodifiableBidiMap.java | 30 +- .../TestUnmodifiableOrderedBidiMap.java | 34 +- .../TestUnmodifiableSortedBidiMap.java | 36 +- .../buffer/TestBlockingBuffer.java | 402 +++-- .../collections/buffer/TestBoundedBuffer.java | 122 +- .../buffer/TestBoundedFifoBuffer.java | 78 +- .../buffer/TestBoundedFifoBuffer2.java | 36 +- .../buffer/TestCircularFifoBuffer.java | 298 +-- .../buffer/TestPredicatedBuffer.java | 64 +- .../buffer/TestPriorityBuffer.java | 206 ++- .../buffer/TestSynchronizedBuffer.java | 35 +- .../buffer/TestTransformedBuffer.java | 4 +- .../buffer/TestUnboundedFifoBuffer.java | 200 ++- .../buffer/TestUnmodifiableBuffer.java | 49 +- .../comparators/TestBooleanComparator.java | 104 +- .../comparators/TestComparableComparator.java | 20 +- .../comparators/TestComparatorChain.java | 114 +- .../comparators/TestFixedOrderComparator.java | 78 +- .../comparators/TestReverseComparator.java | 19 +- .../iterators/AbstractTestIterator.java | 21 +- .../iterators/AbstractTestListIterator.java | 105 +- .../iterators/AbstractTestMapIterator.java | 158 +- .../AbstractTestOrderedMapIterator.java | 63 +- .../iterators/TestArrayIterator.java | 24 +- .../iterators/TestArrayIterator2.java | 47 +- .../iterators/TestArrayListIterator.java | 26 +- .../iterators/TestArrayListIterator2.java | 28 +- .../iterators/TestCollatingIterator.java | 118 +- .../iterators/TestFilterListIterator.java | 354 ++-- .../iterators/TestIteratorChain.java | 76 +- .../iterators/TestLoopingIterator.java | 30 +- .../iterators/TestLoopingListIterator.java | 50 +- .../iterators/TestObjectArrayIterator.java | 48 +- .../TestObjectArrayListIterator.java | 30 +- .../TestObjectArrayListIterator2.java | 22 +- .../iterators/TestObjectGraphIterator.java | 106 +- .../iterators/TestReverseListIterator.java | 40 +- .../iterators/TestSingletonIterator.java | 44 +- .../iterators/TestSingletonIterator2.java | 18 +- .../iterators/TestUniqueFilterIterator.java | 48 +- .../iterators/TestUnmodifiableIterator.java | 28 +- .../TestUnmodifiableListIterator.java | 30 +- .../TestUnmodifiableMapIterator.java | 50 +- .../TestUnmodifiableOrderedMapIterator.java | 50 +- .../keyvalue/AbstractTestMapEntry.java | 32 +- .../keyvalue/TestDefaultKeyValue.java | 54 +- .../keyvalue/TestDefaultMapEntry.java | 23 +- .../keyvalue/TestTiedMapEntry.java | 34 +- .../keyvalue/TestUnmodifiableMapEntry.java | 26 +- .../list/TestAbstractLinkedList.java | 118 +- .../collections/list/TestFixedSizeList.java | 12 +- .../collections/list/TestGrowthList.java | 40 +- .../list/TestNodeCachingLinkedList.java | 70 +- .../collections/list/TestPredicatedList.java | 159 +- .../collections/list/TestSetUniqueList.java | 291 +-- .../list/TestSynchronizedList.java | 13 +- .../collections/list/TestTransformedList.java | 63 +- .../list/TestUnmodifiableList.java | 74 +- .../map/AbstractTestOrderedMap.java | 136 +- .../map/AbstractTestSortedMap.java | 194 +- .../map/TestCaseInsensitiveMap.java | 71 +- .../map/TestFixedSizeSortedMap.java | 15 +- .../commons/collections/map/TestFlat3Map.java | 235 +-- .../collections/map/TestHashedMap.java | 21 +- .../collections/map/TestIdentityMap.java | 68 +- .../commons/collections/map/TestLRUMap.java | 327 ++-- .../collections/map/TestLinkedMap.java | 173 +- .../collections/map/TestListOrderedMap.java | 225 +-- .../collections/map/TestListOrderedMap2.java | 90 +- .../collections/map/TestMultiKeyMap.java | 181 +- .../map/TestPredicatedSortedMap.java | 118 +- .../map/TestReferenceIdentityMap.java | 118 +- .../collections/map/TestReferenceMap.java | 54 +- .../collections/map/TestSingletonMap.java | 58 +- .../map/TestTransformedSortedMap.java | 89 +- .../collections/map/TestUnmodifiableMap.java | 45 +- .../map/TestUnmodifiableOrderedMap.java | 45 +- .../map/TestUnmodifiableSortedMap.java | 45 +- .../collections/set/AbstractTestSet.java | 73 +- .../set/AbstractTestSortedSet.java | 106 +- .../collections/set/TestListOrderedSet2.java | 86 +- .../collections/set/TestMapBackedSet.java | 6 +- .../collections/set/TestMapBackedSet2.java | 20 +- .../collections/set/TestSynchronizedSet.java | 18 +- .../set/TestSynchronizedSortedSet.java | 20 +- .../collections/set/TestTransformedSet.java | 42 +- .../set/TestTransformedSortedSet.java | 32 +- .../collections/set/TestUnmodifiableSet.java | 28 +- .../set/TestUnmodifiableSortedSet.java | 71 +- 252 files changed, 8868 insertions(+), 8333 deletions(-) create mode 100644 src/java/org/apache/commons/collections/collection/AbstractUntypedCollectionDecorator.java diff --git a/src/java/org/apache/commons/collections/ArrayStack.java b/src/java/org/apache/commons/collections/ArrayStack.java index 4f9cc1db6..67127b89f 100644 --- a/src/java/org/apache/commons/collections/ArrayStack.java +++ b/src/java/org/apache/commons/collections/ArrayStack.java @@ -42,7 +42,7 @@ import java.util.EmptyStackException; * @author Paul Jack * @author Stephen Colebourne */ -public class ArrayStack extends ArrayList implements Buffer { +public class ArrayStack extends ArrayList implements Buffer { /** 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(); diff --git a/src/java/org/apache/commons/collections/BoundedCollection.java b/src/java/org/apache/commons/collections/BoundedCollection.java index cf056730c..8f02f2bbc 100644 --- a/src/java/org/apache/commons/collections/BoundedCollection.java +++ b/src/java/org/apache/commons/collections/BoundedCollection.java @@ -34,7 +34,7 @@ import java.util.Collection; * @author Herve Quiroz * @author Stephen Colebourne */ -public interface BoundedCollection extends Collection { +public interface BoundedCollection extends Collection { /** * Returns true if this collection is full and no new elements can be added. diff --git a/src/java/org/apache/commons/collections/BufferOverflowException.java b/src/java/org/apache/commons/collections/BufferOverflowException.java index 2a2616b8e..c3dd13ed1 100644 --- a/src/java/org/apache/commons/collections/BufferOverflowException.java +++ b/src/java/org/apache/commons/collections/BufferOverflowException.java @@ -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; diff --git a/src/java/org/apache/commons/collections/BufferUnderflowException.java b/src/java/org/apache/commons/collections/BufferUnderflowException.java index bb4667385..9ecfeba9d 100644 --- a/src/java/org/apache/commons/collections/BufferUnderflowException.java +++ b/src/java/org/apache/commons/collections/BufferUnderflowException.java @@ -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; diff --git a/src/java/org/apache/commons/collections/Closure.java b/src/java/org/apache/commons/collections/Closure.java index 059a50f15..9df4b0c06 100644 --- a/src/java/org/apache/commons/collections/Closure.java +++ b/src/java/org/apache/commons/collections/Closure.java @@ -24,7 +24,8 @@ package org.apache.commons.collections; *

* Standard implementations of common closures are provided by * {@link ClosureUtils}. These include method invokation and for/while loops. - * + * + * @param the type that the closure acts on * @since Commons Collections 1.0 * @version $Revision$ $Date$ * @@ -32,7 +33,7 @@ package org.apache.commons.collections; * @author Nicola Ken Barozzi * @author Stephen Colebourne */ -public interface Closure { +public interface Closure { /** * Performs an action on the specified input object. @@ -42,6 +43,6 @@ public interface Closure { * @throws IllegalArgumentException (runtime) if the input is invalid * @throws FunctorException (runtime) if any other error occurs */ - public void execute(Object input); + public void execute(T input); } diff --git a/src/java/org/apache/commons/collections/ComparatorUtils.java b/src/java/org/apache/commons/collections/ComparatorUtils.java index c65799b86..e04ae1248 100644 --- a/src/java/org/apache/commons/collections/ComparatorUtils.java +++ b/src/java/org/apache/commons/collections/ComparatorUtils.java @@ -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.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 > Comparator 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 > Comparator chainedComparator(Comparator comparator1, Comparator 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 > Comparator chainedComparator(Comparator[] comparators) { + ComparatorChain chain = new ComparatorChain(); 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 > Comparator chainedComparator(Collection> comparators) { return chainedComparator( - (Comparator[]) comparators.toArray(new Comparator[comparators.size()]) + (Comparator[]) 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 Comparator reversedComparator(Comparator comparator) { + return new ReverseComparator(comparator); } /** @@ -143,7 +144,7 @@ public class ComparatorUtils { * false {@link Boolean}s. * @return a comparator that sorts booleans */ - public static Comparator booleanComparator(boolean trueFirst) { + public static Comparator 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 Comparator nullLowComparator(Comparator comparator) { if (comparator == null) { comparator = NATURAL_COMPARATOR; } - return new NullComparator(comparator, false); + return new NullComparator(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 Comparator nullHighComparator(Comparator comparator) { if (comparator == null) { comparator = NATURAL_COMPARATOR; } - return new NullComparator(comparator, true); + return new NullComparator(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 Comparator transformedComparator(Comparator comparator, Transformer transformer) { if (comparator == null) { comparator = NATURAL_COMPARATOR; } - return new TransformingComparator(transformer, comparator); + return new TransformingComparator(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 min(E o1, E o2, Comparator 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 max(E o1, E o2, Comparator comparator) { if (comparator == null) { comparator = NATURAL_COMPARATOR; } diff --git a/src/java/org/apache/commons/collections/EnumerationUtils.java b/src/java/org/apache/commons/collections/EnumerationUtils.java index f12a5fb44..588860eda 100644 --- a/src/java/org/apache/commons/collections/EnumerationUtils.java +++ b/src/java/org/apache/commons/collections/EnumerationUtils.java @@ -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 null. * @throws NullPointerException if the enumeration parameter is null. */ - public static List toList(Enumeration enumeration) { - return IteratorUtils.toList(new EnumerationIterator(enumeration)); + public static List toList(Enumeration enumeration) { + return IteratorUtils.toList(new EnumerationIterator(enumeration)); } + /** + * Override toList(Enumeration) for StringTokenizer as it implements Enumeration + * for the sake of backward compatibility. + * @param stringTokenizer + * @return List + */ + public static List toList(StringTokenizer stringTokenizer) { + List result = new ArrayList(stringTokenizer.countTokens()); + while (stringTokenizer.hasMoreTokens()) { + result.add(stringTokenizer.nextToken()); + } + return result; + } } diff --git a/src/java/org/apache/commons/collections/Factory.java b/src/java/org/apache/commons/collections/Factory.java index 910e392b7..8d979431a 100644 --- a/src/java/org/apache/commons/collections/Factory.java +++ b/src/java/org/apache/commons/collections/Factory.java @@ -26,13 +26,15 @@ package org.apache.commons.collections; * {@link FactoryUtils}. These include factories that return a constant, * a copy of a prototype or a new instance. * + * @param the type that the factory creates + * * @since Commons Collections 2.1 * @version $Revision$ $Date$ * * @author Arron Bates * @author Stephen Colebourne */ -public interface Factory { +public interface Factory { /** * Create a new object. @@ -40,6 +42,6 @@ public interface Factory { * @return a new object * @throws FunctorException (runtime) if the factory cannot create an object */ - public Object create(); + public T create(); } diff --git a/src/java/org/apache/commons/collections/FunctorException.java b/src/java/org/apache/commons/collections/FunctorException.java index 8354fb0f4..eb23776d8 100644 --- a/src/java/org/apache/commons/collections/FunctorException.java +++ b/src/java/org/apache/commons/collections/FunctorException.java @@ -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 */ diff --git a/src/java/org/apache/commons/collections/Predicate.java b/src/java/org/apache/commons/collections/Predicate.java index da5107726..ceea0ad50 100644 --- a/src/java/org/apache/commons/collections/Predicate.java +++ b/src/java/org/apache/commons/collections/Predicate.java @@ -28,13 +28,15 @@ package org.apache.commons.collections; * {@link PredicateUtils}. These include true, false, instanceof, equals, and, * or, not, method invokation and null testing. * + * @param the type that the predicate queries + * * @since Commons Collections 1.0 * @version $Revision$ $Date$ * * @author James Strachan * @author Stephen Colebourne */ -public interface Predicate { +public interface Predicate { /** * Use the specified parameter to perform a test that returns true or false. @@ -45,6 +47,6 @@ public interface Predicate { * @throws IllegalArgumentException (runtime) if the input is invalid * @throws FunctorException (runtime) if the predicate encounters a problem */ - public boolean evaluate(Object object); + public boolean evaluate(T object); } diff --git a/src/java/org/apache/commons/collections/Transformer.java b/src/java/org/apache/commons/collections/Transformer.java index 94f1cc59b..8e0d4e05a 100644 --- a/src/java/org/apache/commons/collections/Transformer.java +++ b/src/java/org/apache/commons/collections/Transformer.java @@ -29,13 +29,16 @@ package org.apache.commons.collections; * {@link TransformerUtils}. These include method invokation, returning a constant, * cloning and returning the string value. * + * @param the input type to the transformer + * @param the output type from the transformer + * * @since Commons Collections 1.0 * @version $Revision$ $Date$ * * @author James Strachan * @author Stephen Colebourne */ -public interface Transformer { +public interface Transformer { /** * Transforms the input object (leaving it unchanged) into some output object. @@ -46,6 +49,6 @@ public interface Transformer { * @throws IllegalArgumentException (runtime) if the input is invalid * @throws FunctorException (runtime) if the transform cannot be completed */ - public Object transform(Object input); + public O transform(I input); } diff --git a/src/java/org/apache/commons/collections/bag/AbstractMapBag.java b/src/java/org/apache/commons/collections/bag/AbstractMapBag.java index c4cda9887..3a3dd002f 100644 --- a/src/java/org/apache/commons/collections/bag/AbstractMapBag.java +++ b/src/java/org/apache/commons/collections/bag/AbstractMapBag.java @@ -33,9 +33,9 @@ import org.apache.commons.collections.set.UnmodifiableSet; * Abstract implementation of the {@link Bag} interface to simplify the creation * of subclass implementations. *

- * Subclasses specify a Map implementation to use as the internal storage. - * The map will be used to map bag elements to a number; the number represents - * the number of occurrences of that element in the bag. + * Subclasses specify a Map implementation to use as the internal storage. The + * map will be used to map bag elements to a number; the number represents the + * number of occurrences of that element in the bag. * * @since Commons Collections 3.0 (previously DefaultMapBag v2.0) * @version $Revision$ $Date$ @@ -46,16 +46,16 @@ import org.apache.commons.collections.set.UnmodifiableSet; * @author Janek Bogucki * @author Steve Clark */ -public abstract class AbstractMapBag implements Bag { - +public abstract class AbstractMapBag implements Bag { + /** The map to use to store the data */ - private transient Map map; + private transient Map 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 uniqueSet; /** * Constructor needed for subclass serialisation. @@ -66,30 +66,30 @@ public abstract class AbstractMapBag implements Bag { } /** - * Constructor that assigns the specified Map as the backing store. - * The map must be empty and non-null. + * Constructor that assigns the specified Map as the backing store. The map + * must be empty and non-null. * - * @param map the map to assign + * @param map the map to assign */ - protected AbstractMapBag(Map map) { + protected AbstractMapBag(Map 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 getMap() { return map; } //----------------------------------------------------------------------- /** * Returns the number of elements in this bag. - * + * * @return current size of the bag */ public int size() { @@ -98,7 +98,7 @@ public abstract class AbstractMapBag implements Bag { /** * Returns true if the underlying map is empty. - * + * * @return true if bag is empty */ public boolean isEmpty() { @@ -106,14 +106,14 @@ public abstract class AbstractMapBag implements Bag { } /** - * Returns the number of occurrence of the given element in this bag - * by looking up its count in the underlying map. - * - * @param object the object to search for + * Returns the number of occurrence of the given element in this bag by + * looking up its count in the underlying map. + * + * @param object the object to search for * @return the number of occurrences of the object, zero if not found */ public int getCount(Object object) { - MutableInteger count = (MutableInteger) map.get(object); + MutableInteger count = map.get(object); if (count != null) { return count.value; } @@ -124,8 +124,8 @@ public abstract class AbstractMapBag implements Bag { /** * Determines if the bag contains the given element by checking if the * underlying map contains the element as a key. - * - * @param object the object to search for + * + * @param object the object to search for * @return true if the bag contains the given element */ public boolean contains(Object object) { @@ -135,26 +135,27 @@ public abstract class AbstractMapBag implements Bag { /** * Determines if the bag contains the given elements. * - * @param coll the collection to check against + * @param coll the collection to check against * @return true 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((Collection) coll)); } /** - * Returns true if the bag contains all elements in - * the given collection, respecting cardinality. + * Returns true 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 true if the Bag contains all the collection */ - boolean containsAll(Bag other) { + boolean containsAll(Bag other) { boolean result = true; - Iterator it = other.uniqueSet().iterator(); + Iterator it = other.uniqueSet().iterator(); while (it.hasNext()) { Object current = it.next(); boolean contains = getCount(current) >= other.getCount(current); @@ -165,22 +166,22 @@ public abstract class AbstractMapBag implements Bag { //----------------------------------------------------------------------- /** - * Gets an iterator over the bag elements. - * Elements present in the Bag more than once will be returned repeatedly. + * Gets an iterator over the bag elements. Elements present in the Bag more + * than once will be returned repeatedly. * * @return the iterator */ - public Iterator iterator() { - return new BagIterator(this); + public Iterator iterator() { + return new BagIterator(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 implements Iterator { + private AbstractMapBag parent; + private Iterator> entryIterator; + private Map.Entry current; private int itemCount; private final int mods; private boolean canRemove; @@ -188,9 +189,9 @@ public abstract class AbstractMapBag implements Bag { /** * Constructor. * - * @param parent the parent bag + * @param parent the parent bag */ - public BagIterator(AbstractMapBag parent) { + public BagIterator(AbstractMapBag parent) { this.parent = parent; this.entryIterator = parent.map.entrySet().iterator(); this.current = null; @@ -202,13 +203,13 @@ public abstract class AbstractMapBag implements Bag { return (itemCount > 0 || entryIterator.hasNext()); } - public Object next() { + public E next() { if (parent.modCount != mods) { throw new ConcurrentModificationException(); } if (itemCount == 0) { - current = (Map.Entry) entryIterator.next(); - itemCount = ((MutableInteger) current.getValue()).value; + current = (Map.Entry) entryIterator.next(); + itemCount = current.getValue().value; } canRemove = true; itemCount--; @@ -222,7 +223,7 @@ public abstract class AbstractMapBag implements Bag { if (canRemove == false) { throw new IllegalStateException(); } - MutableInteger mut = (MutableInteger) current.getValue(); + MutableInteger mut = current.getValue(); if (mut.value > 1) { mut.value--; } else { @@ -235,48 +236,49 @@ public abstract class AbstractMapBag implements Bag { //----------------------------------------------------------------------- /** - * Adds a new element to the bag, incrementing its count in the underlying map. - * - * @param object the object to add - * @return true if the object was not already in the uniqueSet + * Adds a new element to the bag, incrementing its count in the underlying + * map. + * + * @param object the object to add + * @return true if the object was not already in the + * uniqueSet */ - 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 true if the object was not already in the uniqueSet + * + * @param object the object to search for + * @param nCopies the number of copies to add + * @return true if the object was not already in the + * uniqueSet */ - 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 true if this call changed the bag */ - public boolean addAll(Collection coll) { + public boolean addAll(Collection coll) { boolean changed = false; - Iterator i = coll.iterator(); + Iterator i = coll.iterator(); while (i.hasNext()) { boolean added = add(i.next()); changed = changed || added; @@ -297,11 +299,11 @@ public abstract class AbstractMapBag implements Bag { /** * Removes all copies of the specified object from the bag. * - * @param object the object to remove + * @param object the object to remove * @return true if the bag changed */ public boolean remove(Object object) { - MutableInteger mut = (MutableInteger) map.get(object); + MutableInteger mut = map.get(object); if (mut == null) { return false; } @@ -314,12 +316,12 @@ public abstract class AbstractMapBag implements Bag { /** * Removes a specified number of copies of an object from the bag. * - * @param object the object to remove - * @param nCopies the number of copies to remove + * @param object the object to remove + * @param nCopies the number of copies to remove * @return true if the bag changed */ public boolean remove(Object object, int nCopies) { - MutableInteger mut = (MutableInteger) map.get(object); + MutableInteger mut = map.get(object); if (mut == null) { return false; } @@ -338,15 +340,16 @@ public abstract class AbstractMapBag implements Bag { } /** - * Removes objects from the bag according to their count in the specified collection. + * Removes objects from the bag according to their count in the specified + * collection. * - * @param coll the collection to use + * @param coll the collection to use * @return true if the bag changed */ - public boolean removeAll(Collection coll) { + public boolean removeAll(Collection coll) { boolean result = false; if (coll != null) { - Iterator i = coll.iterator(); + Iterator i = coll.iterator(); while (i.hasNext()) { boolean changed = remove(i.next(), 1); result = result || changed; @@ -356,33 +359,34 @@ public abstract class AbstractMapBag implements Bag { } /** - * Remove any members of the bag that are not in the given - * bag, respecting cardinality. - * - * @param coll the collection to retain + * Remove any members of the bag that are not in the given bag, respecting + * cardinality. + * + * @param coll the collection to retain * @return true if this call changed the collection */ - public boolean retainAll(Collection coll) { + @SuppressWarnings("unchecked") + public boolean retainAll(Collection coll) { if (coll instanceof Bag) { - return retainAll((Bag) coll); + return retainAll((Bag) coll); } - return retainAll(new HashBag(coll)); + return retainAll(new HashBag((Collection) 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 true 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 excess = new HashBag(); + Iterator i = uniqueSet().iterator(); while (i.hasNext()) { - Object current = i.next(); + E current = i.next(); int myCount = getCount(current); int otherCount = other.getCount(current); if (1 <= otherCount && otherCount <= myCount) { @@ -404,15 +408,15 @@ public abstract class AbstractMapBag implements Bag { protected static class MutableInteger { /** The value of this mutable. */ protected int value; - + /** * Constructor. - * @param value the initial value + * @param value the initial value */ MutableInteger(int value) { this.value = value; } - + public boolean equals(Object obj) { if (obj instanceof MutableInteger == false) { return false; @@ -424,19 +428,19 @@ public abstract class AbstractMapBag implements Bag { return value; } } - + //----------------------------------------------------------------------- /** * Returns an array of all of this bag's elements. - * + * * @return an array of all of this bag's elements */ public Object[] toArray() { Object[] result = new Object[size()]; int i = 0; - Iterator it = map.keySet().iterator(); + Iterator it = map.keySet().iterator(); while (it.hasNext()) { - Object current = it.next(); + E current = it.next(); for (int index = getCount(current); index > 0; index--) { result[i++] = current; } @@ -446,38 +450,39 @@ public abstract class AbstractMapBag implements Bag { /** * Returns an array of all of this bag's elements. - * - * @param array the array to populate + * + * @param array the array to populate * @return an array of all of this bag's elements */ - public Object[] toArray(Object[] array) { + @SuppressWarnings("unchecked") + public T[] 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 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 uniqueSet() { if (uniqueSet == null) { - uniqueSet = UnmodifiableSet.decorate(map.keySet()); + uniqueSet = UnmodifiableSet. decorate(map.keySet()); } return uniqueSet; } @@ -485,26 +490,28 @@ public abstract class AbstractMapBag implements Bag { //----------------------------------------------------------------------- /** * Write the map out using a custom routine. - * @param out the output stream + * @param out the output stream * @throws IOException */ protected void doWriteObject(ObjectOutputStream out) throws IOException { out.writeInt(map.size()); - for (Iterator it = map.entrySet().iterator(); it.hasNext();) { - Map.Entry entry = (Map.Entry) it.next(); + for (Iterator> it = map.entrySet().iterator(); it.hasNext();) { + Map.Entry entry = it.next(); out.writeObject(entry.getKey()); - out.writeInt(((MutableInteger) entry.getValue()).value); + out.writeInt(entry.getValue().value); } } /** * Read the map in using a custom routine. - * @param map the map to use - * @param in the input stream + * @param map the map to use + * @param in the input stream * @throws IOException * @throws ClassNotFoundException */ - protected void doReadObject(Map map, ObjectInputStream in) throws IOException, ClassNotFoundException { + @SuppressWarnings("unchecked") + protected void doReadObject(Map map, ObjectInputStream in) throws IOException, + ClassNotFoundException { this.map = map; int entrySize = in.readInt(); for (int i = 0; i < entrySize; i++) { @@ -514,14 +521,13 @@ public abstract class AbstractMapBag implements Bag { size += count; } } - + //----------------------------------------------------------------------- /** - * Compares this Bag to another. - * This Bag equals another Bag if it contains the same number of occurrences of - * the same elements. + * Compares this Bag to another. This Bag equals another Bag if it contains + * the same number of occurrences of the same elements. * - * @param object the Bag to compare to + * @param object the Bag to compare to * @return true if equal */ public boolean equals(Object object) { @@ -531,12 +537,12 @@ public abstract class AbstractMapBag implements Bag { if (object instanceof Bag == false) { return false; } - Bag other = (Bag) object; + Bag other = (Bag) object; if (other.size() != size()) { return false; } - for (Iterator it = map.keySet().iterator(); it.hasNext();) { - Object element = it.next(); + for (Iterator it = map.keySet().iterator(); it.hasNext();) { + E element = it.next(); if (other.getCount(element) != getCount(element)) { return false; } @@ -546,19 +552,19 @@ public abstract class AbstractMapBag implements Bag { /** * Gets a hash code for the Bag compatible with the definition of equals. - * The hash code is defined as the sum total of a hash code for each element. - * The per element hash code is defined as - * (e==null ? 0 : e.hashCode()) ^ noOccurances). - * 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 + * (e==null ? 0 : e.hashCode()) ^ noOccurances). 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> it = map.entrySet().iterator(); it.hasNext();) { + Map.Entry entry = it.next(); + E element = entry.getKey(); + MutableInteger count = entry.getValue(); total += (element == null ? 0 : element.hashCode()) ^ count.value; } return total; @@ -575,7 +581,7 @@ public abstract class AbstractMapBag implements Bag { } StringBuffer buf = new StringBuffer(); buf.append('['); - Iterator it = uniqueSet().iterator(); + Iterator it = uniqueSet().iterator(); while (it.hasNext()) { Object current = it.next(); int count = getCount(current); @@ -589,5 +595,5 @@ public abstract class AbstractMapBag implements Bag { buf.append(']'); return buf.toString(); } - + } diff --git a/src/java/org/apache/commons/collections/bag/HashBag.java b/src/java/org/apache/commons/collections/bag/HashBag.java index aa6c0c92e..814b11b53 100644 --- a/src/java/org/apache/commons/collections/bag/HashBag.java +++ b/src/java/org/apache/commons/collections/bag/HashBag.java @@ -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 + extends AbstractMapBag implements Bag, Serializable { /** Serial version lock */ private static final long serialVersionUID = -6561115435802554013L; @@ -51,7 +51,7 @@ public class HashBag * Constructs an empty HashBag. */ public HashBag() { - super(new HashMap()); + super(new HashMap()); } /** @@ -59,7 +59,7 @@ public class HashBag * * @param coll a collection to copy into this bag */ - public HashBag(Collection coll) { + public HashBag(Collection 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(), in); } } diff --git a/src/java/org/apache/commons/collections/bag/TransformedBag.java b/src/java/org/apache/commons/collections/bag/TransformedBag.java index f000abcb5..153d1cf6d 100644 --- a/src/java/org/apache/commons/collections/bag/TransformedBag.java +++ b/src/java/org/apache/commons/collections/bag/TransformedBag.java @@ -38,8 +38,8 @@ import org.apache.commons.collections.set.TransformedSet; * * @author Stephen Colebourne */ -public class TransformedBag - extends TransformedCollection implements Bag { +public class TransformedBag + extends TransformedCollection implements Bag { /** Serialization version */ private static final long serialVersionUID = 5421170911299074185L; @@ -56,8 +56,8 @@ public class TransformedBag * @return a new transformed Bag * @throws IllegalArgumentException if bag or transformer is null */ - public static Bag decorate(Bag bag, Transformer transformer) { - return new TransformedBag(bag, transformer); + public static Bag decorate(Bag bag, Transformer transformer) { + return new TransformedBag(bag, transformer); } /** @@ -74,13 +74,14 @@ public class TransformedBag * @throws IllegalArgumentException if bag or transformer is null * @since Commons Collections 3.3 */ + // TODO: Generics public static Bag decorateTransform(Bag bag, Transformer transformer) { TransformedBag decorated = new TransformedBag(bag, transformer); if (transformer != null && bag != null && bag.size() > 0) { Object[] values = bag.toArray(); bag.clear(); for(int i=0; i bag, Transformer transformer) { super(bag, transformer); } @@ -106,8 +107,8 @@ public class TransformedBag * * @return the decorated bag */ - protected Bag getBag() { - return (Bag) collection; + protected Bag getBag() { + return (Bag) collection; } //----------------------------------------------------------------------- @@ -120,14 +121,13 @@ public class TransformedBag } //----------------------------------------------------------------------- - public boolean add(Object object, int nCopies) { - object = transform(object); - return getBag().add(object, nCopies); + public boolean add(E object, int nCopies) { + return getBag().add(transform(object), nCopies); } - public Set uniqueSet() { - Set set = getBag().uniqueSet(); - return TransformedSet.decorate(set, transformer); + public Set uniqueSet() { + Set set = getBag().uniqueSet(); + return TransformedSet.decorate(set, transformer); } } diff --git a/src/java/org/apache/commons/collections/bag/TransformedSortedBag.java b/src/java/org/apache/commons/collections/bag/TransformedSortedBag.java index 8b950c206..51ca15f95 100644 --- a/src/java/org/apache/commons/collections/bag/TransformedSortedBag.java +++ b/src/java/org/apache/commons/collections/bag/TransformedSortedBag.java @@ -36,8 +36,8 @@ import org.apache.commons.collections.Transformer; * * @author Stephen Colebourne */ -public class TransformedSortedBag - extends TransformedBag implements SortedBag { +public class TransformedSortedBag + extends TransformedBag implements SortedBag { /** Serialization version */ private static final long serialVersionUID = -251737742649401930L; @@ -54,8 +54,8 @@ public class TransformedSortedBag * @return a new transformed SortedBag * @throws IllegalArgumentException if bag or transformer is null */ - public static SortedBag decorate(SortedBag bag, Transformer transformer) { - return new TransformedSortedBag(bag, transformer); + public static SortedBag decorate(SortedBag bag, Transformer transformer) { + return new TransformedSortedBag(bag, transformer); } /** @@ -72,13 +72,14 @@ public class TransformedSortedBag * @throws IllegalArgumentException if bag or transformer is null * @since Commons Collections 3.3 */ + // TODO: Generics public static SortedBag decorateTransform(SortedBag bag, Transformer transformer) { TransformedSortedBag decorated = new TransformedSortedBag(bag, transformer); if (transformer != null && bag != null && bag.size() > 0) { Object[] values = bag.toArray(); bag.clear(); for(int i=0; i bag, Transformer transformer) { super(bag, transformer); } @@ -104,20 +105,20 @@ public class TransformedSortedBag * * @return the decorated bag */ - protected SortedBag getSortedBag() { - return (SortedBag) collection; + protected SortedBag getSortedBag() { + return (SortedBag) collection; } //----------------------------------------------------------------------- - public Object first() { + public E first() { return getSortedBag().first(); } - public Object last() { + public E last() { return getSortedBag().last(); } - public Comparator comparator() { + public Comparator comparator() { return getSortedBag().comparator(); } diff --git a/src/java/org/apache/commons/collections/bag/TreeBag.java b/src/java/org/apache/commons/collections/bag/TreeBag.java index 10be39e79..608cb4c7d 100644 --- a/src/java/org/apache/commons/collections/bag/TreeBag.java +++ b/src/java/org/apache/commons/collections/bag/TreeBag.java @@ -34,11 +34,11 @@ import org.apache.commons.collections.SortedBag; * Order will be maintained among the bag members and can be viewed through the * iterator. *

- * A Bag 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 - * Collection interface specification. + * A Bag 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 Collection + * interface specification. * * @since Commons Collections 3.0 (previously in main package v2.0) * @version $Revision$ $Date$ @@ -46,60 +46,69 @@ import org.apache.commons.collections.SortedBag; * @author Chuck Burdick * @author Stephen Colebourne */ -public class TreeBag - extends AbstractMapBag implements SortedBag, Serializable { +public class TreeBag extends AbstractMapBag implements SortedBag, Serializable { /** Serial version lock */ private static final long serialVersionUID = -7740146511091606676L; - + /** * Constructs an empty TreeBag. */ public TreeBag() { - super(new TreeMap()); + super(new TreeMap()); } /** - * 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 comparator) { + super(new TreeMap(comparator)); } /** * Constructs a TreeBag 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 coll) { this(); addAll(coll); } //----------------------------------------------------------------------- - public boolean add(Object o) { - if(comparator() == null && !(o instanceof Comparable)) { - throw new IllegalArgumentException("Objects of type " + o.getClass() + " cannot be added to " + + // TODO: Generics - should this be E or some such? + public boolean add(E object) { + if(comparator() == null && !(object instanceof Comparable)) { + throw new IllegalArgumentException("Objects of type " + object.getClass() + " cannot be added to " + "a naturally ordered TreeBag as it does not implement Comparable"); } - return super.add(o); + return super.add(object); } //----------------------------------------------------------------------- - public Object first() { - return ((SortedMap) getMap()).firstKey(); + public E first() { + return getMap().firstKey(); } - public Object last() { - return ((SortedMap) getMap()).lastKey(); + public E last() { + return getMap().lastKey(); } - public Comparator comparator() { - return ((SortedMap) getMap()).comparator(); + public Comparator comparator() { + return getMap().comparator(); + } + + /** + * {@inheritDoc} + */ + @Override + protected SortedMap getMap() { + return (SortedMap) super + .getMap(); } //----------------------------------------------------------------------- @@ -115,10 +124,11 @@ public class TreeBag /** * Read the bag in using a custom routine. */ + @SuppressWarnings("unchecked") private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); Comparator comp = (Comparator) in.readObject(); super.doReadObject(new TreeMap(comp), in); } - + } diff --git a/src/java/org/apache/commons/collections/bidimap/DualHashBidiMap.java b/src/java/org/apache/commons/collections/bidimap/DualHashBidiMap.java index 34b4d5eea..59722c792 100644 --- a/src/java/org/apache/commons/collections/bidimap/DualHashBidiMap.java +++ b/src/java/org/apache/commons/collections/bidimap/DualHashBidiMap.java @@ -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 extends AbstractDualBidiMap implements Serializable { /** Ensure serialization compatibility */ private static final long serialVersionUID = 721969328361808L; @@ -52,7 +51,7 @@ public class DualHashBidiMap * Creates an empty HashBidiMap. */ public DualHashBidiMap() { - super(new HashMap(), new HashMap()); + super(new HashMap(), new HashMap()); } /** @@ -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 map) { + super(new HashMap(), new HashMap()); 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 normalMap, Map reverseMap, BidiMap 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 createBidiMap(Map normalMap, Map reverseMap, BidiMap inverseBidiMap) { + return new DualHashBidiMap(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); } diff --git a/src/java/org/apache/commons/collections/bidimap/TreeBidiMap.java b/src/java/org/apache/commons/collections/bidimap/TreeBidiMap.java index a689fbd13..b1192fd98 100644 --- a/src/java/org/apache/commons/collections/bidimap/TreeBidiMap.java +++ b/src/java/org/apache/commons/collections/bidimap/TreeBidiMap.java @@ -16,8 +16,6 @@ */ package org.apache.commons.collections.bidimap; -import java.io.Serializable; - import java.util.AbstractSet; import java.util.Collection; import java.util.ConcurrentModificationException; @@ -26,7 +24,6 @@ import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; -import org.apache.commons.collections.BidiMap; import org.apache.commons.collections.KeyValue; import org.apache.commons.collections.MapIterator; import org.apache.commons.collections.OrderedBidiMap; @@ -34,6 +31,7 @@ import org.apache.commons.collections.OrderedIterator; import org.apache.commons.collections.OrderedMapIterator; import org.apache.commons.collections.iterators.EmptyOrderedMapIterator; import org.apache.commons.collections.keyvalue.UnmodifiableMapEntry; +import static org.apache.commons.collections.bidimap.TreeBidiMap.DataElement.*; /** * Red-Black tree-based implementation of BidiMap where all objects added @@ -74,33 +72,47 @@ import org.apache.commons.collections.keyvalue.UnmodifiableMapEntry; * * @author Marc Johnson * @author Stephen Colebourne + * @author Matt Benson */ -public class TreeBidiMap implements OrderedBidiMap, Serializable { +public class TreeBidiMap, V extends Comparable> implements OrderedBidiMap { - private static final int KEY = 0; - private static final int VALUE = 1; - private static final int MAPENTRY = 2; - private static final int INVERSEMAPENTRY = 3; - private static final int SUM_OF_INDICES = KEY + VALUE; - private static final int FIRST_INDEX = 0; - private static final int NUMBER_OF_INDICES = 2; - private static final String[] dataName = new String[] { "key", "value" }; - - private Node[] rootNode = new Node[2]; + static enum DataElement { + KEY("key"), VALUE("value"); + + private final String description; + + /** + * Create a new TreeBidiMap.DataElement. + */ + private DataElement(String description) { + this.description = description; + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return description; + } + } + + private Node[] rootNode; private int nodeCount = 0; private int modifications = 0; - - private transient Set keySet; - private transient Set valuesSet; - private transient Set entrySet; - private transient TreeBidiMap.Inverse inverse = null; + private Set keySet; + private Set valuesSet; + private Set> entrySet; + private Inverse inverse = null; //----------------------------------------------------------------------- /** * Constructs a new empty TreeBidiMap. */ + @SuppressWarnings("unchecked") public TreeBidiMap() { super(); + rootNode = new Node[2]; } /** @@ -111,8 +123,8 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { * not Comparable or are not mutually comparable * @throws NullPointerException if any key or value in the map is null */ - public TreeBidiMap(final Map map) { - super(); + public TreeBidiMap(final Map map) { + this(); putAll(map); } @@ -147,11 +159,11 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { */ public boolean containsKey(final Object key) { checkKey(key); - return (lookup((Comparable) key, KEY) != null); + return (lookupKey(key) != null); } /** - * Checks whether this map contains a mapping for the specified value. + * Checks whether this map contains the a mapping for the specified value. *

* The value must implement Comparable. * @@ -162,7 +174,7 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { */ public boolean containsValue(final Object value) { checkValue(value); - return (lookup((Comparable) value, VALUE) != null); + return (lookupValue(value) != null); } /** @@ -177,8 +189,10 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { * @throws ClassCastException if the key is of an inappropriate type * @throws NullPointerException if the key is null */ - public Object get(final Object key) { - return doGet((Comparable) key, KEY); + public V get(final Object key) { + checkKey(key); + Node node = lookupKey(key); + return node == null ? null : node.getValue(); } /** @@ -191,7 +205,7 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { * BidiMap map1 = new TreeBidiMap(); * map.put("A","B"); // contains A mapped to B, as per Map * map.put("A","C"); // contains A mapped to C, as per Map - * + * * BidiMap map2 = new TreeBidiMap(); * map.put("A","B"); // contains A mapped to B, as per Map * map.put("C","B"); // contains C mapped to B, key A is removed @@ -205,25 +219,25 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { * @throws ClassCastException if the key is of an inappropriate type * @throws NullPointerException if the key is null */ - public Object put(final Object key, final Object value) { - return doPut((Comparable) key, (Comparable) value, KEY); + public V put(final K key, final V value) { + V result = get(key); + doPut(key, value); + return result; } /** * Puts all the mappings from the specified map into this map. *

* All keys and values must implement Comparable. - * + * * @param map the map to copy from */ - public void putAll(Map map) { - Iterator it = map.entrySet().iterator(); - while (it.hasNext()) { - Map.Entry entry = (Map.Entry) it.next(); - put(entry.getKey(), entry.getValue()); + public void putAll(Map map) { + for (Map.Entry e : map.entrySet()) { + put(e.getKey(), e.getValue()); } } - + /** * Removes the mapping for this key from this map if present. *

@@ -235,8 +249,8 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { * @throws ClassCastException if the key is of an inappropriate type * @throws NullPointerException if the key is null */ - public Object remove(final Object key) { - return doRemove((Comparable) key, KEY); + public V remove(final Object key) { + return doRemoveKey(key); } /** @@ -246,8 +260,8 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { modify(); nodeCount = 0; - rootNode[KEY] = null; - rootNode[VALUE] = null; + rootNode[KEY.ordinal()] = null; + rootNode[VALUE.ordinal()] = null; } //----------------------------------------------------------------------- @@ -263,8 +277,10 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { * @throws ClassCastException if the value is of an inappropriate type * @throws NullPointerException if the value is null */ - public Object getKey(final Object value) { - return doGet((Comparable) value, VALUE); + public K getKey(final Object value) { + checkValue(value); + Node node = lookupValue(value); + return node == null ? null : node.getKey(); } /** @@ -278,8 +294,8 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { * @throws ClassCastException if the value is of an inappropriate type * @throws NullPointerException if the value is null */ - public Object removeValue(final Object value) { - return doRemove((Comparable) value, VALUE); + public K removeValue(final Object value) { + return doRemoveValue(value); } //----------------------------------------------------------------------- @@ -289,11 +305,11 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { * @return the first (lowest) key currently in this sorted map * @throws NoSuchElementException if this map is empty */ - public Object firstKey() { + public K firstKey() { if (nodeCount == 0) { throw new NoSuchElementException("Map is empty"); } - return leastNode(rootNode[KEY], KEY).getKey(); + return leastNode(rootNode[KEY.ordinal()], KEY).getKey(); } /** @@ -302,13 +318,13 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { * @return the last (highest) key currently in this sorted map * @throws NoSuchElementException if this map is empty */ - public Object lastKey() { + public K lastKey() { if (nodeCount == 0) { throw new NoSuchElementException("Map is empty"); } - return greatestNode(rootNode[KEY], KEY).getKey(); + return greatestNode(rootNode[KEY.ordinal()], KEY).getKey(); } - + /** * Gets the next key after the one specified. *

@@ -317,10 +333,10 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { * @param key the key to search for next from * @return the next key, null if no match or at end */ - public Object nextKey(Object key) { + public K nextKey(K key) { checkKey(key); - Node node = nextGreater(lookup((Comparable) key, KEY), KEY); - return (node == null ? null : node.getKey()); + Node node = nextGreater(lookupKey(key), KEY); + return node == null ? null : node.getKey(); } /** @@ -331,12 +347,12 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { * @param key the key to search for previous from * @return the previous key, null if no match or at start */ - public Object previousKey(Object key) { + public K previousKey(K key) { checkKey(key); - Node node = nextSmaller(lookup((Comparable) key, KEY), KEY); - return (node == null ? null : node.getKey()); + Node node = nextSmaller(lookupKey(key), KEY); + return node == null ? null : node.getKey(); } - + //----------------------------------------------------------------------- /** * Returns a set view of the keys contained in this map in key order. @@ -350,9 +366,9 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { * * @return a set view of the keys contained in this map. */ - public Set keySet() { + public Set keySet() { if (keySet == null) { - keySet = new View(this, KEY, KEY); + keySet = new KeyView(KEY); } return keySet; } @@ -371,9 +387,9 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { * * @return a set view of the values contained in this map. */ - public Collection values() { + public Collection values() { if (valuesSet == null) { - valuesSet = new View(this, KEY, VALUE); + valuesSet = new ValueView(KEY); } return valuesSet; } @@ -393,60 +409,33 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { * * @return a set view of the values contained in this map. */ - public Set entrySet() { + public Set> entrySet() { if (entrySet == null) { - entrySet = new EntryView(this, KEY, MAPENTRY); + return new EntryView(); } return entrySet; } //----------------------------------------------------------------------- /** - * Gets an iterator over the map entries. - *

- * For this map, this iterator is the fastest way to iterate over the entries. - * - * @return an iterator + * {@inheritDoc} */ - public MapIterator mapIterator() { + public OrderedMapIterator mapIterator() { if (isEmpty()) { - return EmptyOrderedMapIterator.INSTANCE; + return EmptyOrderedMapIterator.getInstance(); } - return new ViewMapIterator(this, KEY); - } - - /** - * Gets an ordered iterator over the map entries. - *

- * This iterator allows both forward and reverse iteration over the entries. - * - * @return an iterator - */ - public OrderedMapIterator orderedMapIterator() { - if (isEmpty()) { - return EmptyOrderedMapIterator.INSTANCE; - } - return new ViewMapIterator(this, KEY); + return new ViewMapIterator(KEY); } //----------------------------------------------------------------------- /** * Gets the inverse map for comparison. - * + * * @return the inverse map */ - public BidiMap inverseBidiMap() { - return inverseOrderedBidiMap(); - } - - /** - * Gets the inverse map for comparison. - * - * @return the inverse map - */ - public OrderedBidiMap inverseOrderedBidiMap() { + public OrderedBidiMap inverseBidiMap() { if (inverse == null) { - inverse = new Inverse(this); + inverse = new Inverse(); } return inverse; } @@ -461,7 +450,7 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { public boolean equals(Object obj) { return this.doEquals(obj, KEY); } - + /** * Gets the hash code value for this map as per the API. * @@ -470,61 +459,43 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { public int hashCode() { return this.doHashCode(KEY); } - + /** * Returns a string version of this Map in standard format. - * + * * @return a standard format string version of the map */ public String toString() { return this.doToString(KEY); } - + //----------------------------------------------------------------------- /** - * Common get logic, used to get by key or get by value + * Put logic. * - * @param obj the key or value that we're looking for - * @param index the KEY or VALUE int - * @return the key (if the value was mapped) or the value (if the - * key was mapped); null if we couldn't find the specified - * object - */ - private Object doGet(final Comparable obj, final int index) { - checkNonNullComparable(obj, index); - Node node = lookup(obj, index); - return ((node == null) ? null : node.getData(oppositeIndex(index))); - } - - /** - * Common put logic, differing only in the return value. - * * @param key the key, always the main map key * @param value the value, always the main map value - * @param index the KEY or VALUE int, for the return value only - * @return the previously mapped value */ - private Object doPut(final Comparable key, final Comparable value, final int index) { + private void doPut(final K key, final V value) { checkKeyAndValue(key, value); - + // store previous and remove previous mappings - Object prev = (index == KEY ? doGet(key, KEY) : doGet(value, VALUE)); - doRemove(key, KEY); - doRemove(value, VALUE); - - Node node = rootNode[KEY]; + doRemoveKey(key); + doRemoveValue(value); + + Node node = rootNode[KEY.ordinal()]; if (node == null) { // map is empty - Node root = new Node(key, value); - rootNode[KEY] = root; - rootNode[VALUE] = root; + Node root = new Node(key, value); + rootNode[KEY.ordinal()] = root; + rootNode[VALUE.ordinal()] = root; grow(); - + } else { // add new mapping while (true) { - int cmp = compare(key, node.getData(KEY)); - + int cmp = compare(key, node.getKey()); + if (cmp == 0) { // shouldn't happen throw new IllegalArgumentException("Cannot store a duplicate key (\"" + key + "\") in this Map"); @@ -532,54 +503,51 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { if (node.getLeft(KEY) != null) { node = node.getLeft(KEY); } else { - Node newNode = new Node(key, value); - + Node newNode = new Node(key, value); + insertValue(newNode); node.setLeft(newNode, KEY); newNode.setParent(node, KEY); doRedBlackInsert(newNode, KEY); grow(); - + break; } } else { // cmp > 0 if (node.getRight(KEY) != null) { node = node.getRight(KEY); } else { - Node newNode = new Node(key, value); - + Node newNode = new Node(key, value); + insertValue(newNode); node.setRight(newNode, KEY); newNode.setParent(node, KEY); doRedBlackInsert(newNode, KEY); grow(); - + break; } } } } - return prev; } - /** - * Remove by object (remove by key or remove by value) - * - * @param o the key, or value, that we're looking for - * @param index the KEY or VALUE int - * - * @return the key, if remove by value, or the value, if remove by - * key. null if the specified key or value could not be - * found - */ - private Object doRemove(final Comparable o, final int index) { - Node node = lookup(o, index); - Object rval = null; - if (node != null) { - rval = node.getData(oppositeIndex(index)); - doRedBlackDelete(node); + private V doRemoveKey(Object key) { + Node node = lookupKey(key); + if (node == null) { + return null; } - return rval; + doRedBlackDelete(node); + return node.getValue(); + } + + private K doRemoveValue(Object value) { + Node node = lookupValue(value); + if (node == null) { + return null; + } + doRedBlackDelete(node); + return node.getKey(); } /** @@ -590,23 +558,32 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { * @return the desired Node, or null if there is no mapping of the * specified data */ - private Node lookup(final Comparable data, final int index) { - Node rval = null; - Node node = rootNode[index]; + @SuppressWarnings("unchecked") + private > Node lookup(final Object data, final DataElement dataElement) { + Node rval = null; + Node node = rootNode[dataElement.ordinal()]; while (node != null) { - int cmp = compare(data, node.getData(index)); + int cmp = compare((T) data, (T) node.getData(dataElement)); if (cmp == 0) { rval = node; break; } else { - node = (cmp < 0) ? node.getLeft(index) : node.getRight(index); + node = (cmp < 0) ? node.getLeft(dataElement) : node.getRight(dataElement); } } return rval; } + private Node lookupKey(Object key) { + return this.lookup(key, KEY); + } + + private Node lookupValue(Object value) { + return this.lookup(value, VALUE); + } + /** * get the next larger node from the specified node * @@ -614,14 +591,14 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { * @param index the KEY or VALUE int * @return the specified node */ - private Node nextGreater(final Node node, final int index) { - Node rval = null; + private Node nextGreater(final Node node, final DataElement dataElement) { + Node rval = null; if (node == null) { rval = null; - } else if (node.getRight(index) != null) { + } else if (node.getRight(dataElement) != null) { // everything to the node's right is larger. The least of // the right node's descendants is the next larger node - rval = leastNode(node.getRight(index), index); + rval = leastNode(node.getRight(dataElement), dataElement); } else { // traverse up our ancestry until we find an ancestor that // is null or one whose left child is our ancestor. If we @@ -629,12 +606,12 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { // tree, and there is no greater node. Otherwise, we are // the largest node in the subtree on that ancestor's left // ... and that ancestor is the next greatest node - Node parent = node.getParent(index); - Node child = node; + Node parent = node.getParent(dataElement); + Node child = node; - while ((parent != null) && (child == parent.getRight(index))) { + while ((parent != null) && (child == parent.getRight(dataElement))) { child = parent; - parent = parent.getParent(index); + parent = parent.getParent(dataElement); } rval = parent; } @@ -648,14 +625,14 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { * @param index the KEY or VALUE int * @return the specified node */ - private Node nextSmaller(final Node node, final int index) { - Node rval = null; + private Node nextSmaller(final Node node, final DataElement dataElement) { + Node rval = null; if (node == null) { rval = null; - } else if (node.getLeft(index) != null) { + } else if (node.getLeft(dataElement) != null) { // everything to the node's left is smaller. The greatest of // the left node's descendants is the next smaller node - rval = greatestNode(node.getLeft(index), index); + rval = greatestNode(node.getLeft(dataElement), dataElement); } else { // traverse up our ancestry until we find an ancestor that // is null or one whose right child is our ancestor. If we @@ -663,12 +640,12 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { // tree, and there is no greater node. Otherwise, we are // the largest node in the subtree on that ancestor's right // ... and that ancestor is the next greatest node - Node parent = node.getParent(index); - Node child = node; + Node parent = node.getParent(dataElement); + Node child = node; - while ((parent != null) && (child == parent.getLeft(index))) { + while ((parent != null) && (child == parent.getLeft(dataElement))) { child = parent; - parent = parent.getParent(index); + parent = parent.getParent(dataElement); } rval = parent; } @@ -676,18 +653,6 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { } //----------------------------------------------------------------------- - /** - * Get the opposite index of the specified index - * - * @param index the KEY or VALUE int - * @return VALUE (if KEY was specified), else KEY - */ - private static int oppositeIndex(final int index) { - // old trick ... to find the opposite of a value, m or n, - // subtract the value from the sum of the two possible - // values. (m + n) - m = n; (m + n) - n = m - return SUM_OF_INDICES - index; - } /** * Compare two objects @@ -698,7 +663,7 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { * @return negative value if o1 < o2; 0 if o1 == o2; positive * value if o1 > o2 */ - private static int compare(final Comparable o1, final Comparable o2) { + private static > int compare(final T o1, final T o2) { return o1.compareTo(o2); } @@ -710,11 +675,11 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { * @return the smallest node, from the specified node, in the * specified mapping */ - private static Node leastNode(final Node node, final int index) { - Node rval = node; + private Node leastNode(final Node node, final DataElement dataElement) { + Node rval = node; if (rval != null) { - while (rval.getLeft(index) != null) { - rval = rval.getLeft(index); + while (rval.getLeft(dataElement) != null) { + rval = rval.getLeft(dataElement); } } return rval; @@ -727,11 +692,11 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { * @param index the KEY or VALUE int * @return the greatest node, from the specified node */ - private static Node greatestNode(final Node node, final int index) { - Node rval = node; + private Node greatestNode(final Node node, final DataElement dataElement) { + Node rval = node; if (rval != null) { - while (rval.getRight(index) != null) { - rval = rval.getRight(index); + while (rval.getRight(dataElement) != null) { + rval = rval.getRight(dataElement); } } return rval; @@ -745,13 +710,13 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { * @param to the node whose color we're changing; may be null * @param index the KEY or VALUE int */ - private static void copyColor(final Node from, final Node to, final int index) { + private void copyColor(final Node from, final Node to, final DataElement dataElement) { if (to != null) { if (from == null) { // by default, make it black - to.setBlack(index); + to.setBlack(dataElement); } else { - to.copyColor(from, index); + to.copyColor(from, dataElement); } } } @@ -763,8 +728,8 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { * @param node the node (may be null) in question * @param index the KEY or VALUE int */ - private static boolean isRed(final Node node, final int index) { - return ((node == null) ? false : node.isRed(index)); + private static boolean isRed(final Node node, final DataElement dataElement) { + return node != null && node.isRed(dataElement); } /** @@ -774,8 +739,8 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { * @param node the node (may be null) in question * @param index the KEY or VALUE int */ - private static boolean isBlack(final Node node, final int index) { - return ((node == null) ? true : node.isBlack(index)); + private static boolean isBlack(final Node node, final DataElement dataElement) { + return node == null || node.isBlack(dataElement); } /** @@ -784,9 +749,9 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { * @param node the node (may be null) in question * @param index the KEY or VALUE int */ - private static void makeRed(final Node node, final int index) { + private static void makeRed(final Node node, final DataElement dataElement) { if (node != null) { - node.setRed(index); + node.setRed(dataElement); } } @@ -796,9 +761,9 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { * @param node the node (may be null) in question * @param index the KEY or VALUE int */ - private static void makeBlack(final Node node, final int index) { + private static void makeBlack(final Node node, final DataElement dataElement) { if (node != null) { - node.setBlack(index); + node.setBlack(dataElement); } } @@ -809,8 +774,8 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { * @param node the node (may be null) in question * @param index the KEY or VALUE int */ - private static Node getGrandParent(final Node node, final int index) { - return getParent(getParent(node, index), index); + private Node getGrandParent(final Node node, final DataElement dataElement) { + return getParent(getParent(node, dataElement), dataElement); } /** @@ -820,8 +785,8 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { * @param node the node (may be null) in question * @param index the KEY or VALUE int */ - private static Node getParent(final Node node, final int index) { - return ((node == null) ? null : node.getParent(index)); + private Node getParent(final Node node, final DataElement dataElement) { + return node == null ? null : node.getParent(dataElement); } /** @@ -831,8 +796,8 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { * @param node the node (may be null) in question * @param index the KEY or VALUE int */ - private static Node getRightChild(final Node node, final int index) { - return (node == null) ? null : node.getRight(index); + private Node getRightChild(final Node node, final DataElement dataElement) { + return node == null ? null : node.getRight(dataElement); } /** @@ -842,44 +807,8 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { * @param node the node (may be null) in question * @param index the KEY or VALUE int */ - private static Node getLeftChild(final Node node, final int index) { - return (node == null) ? null : node.getLeft(index); - } - - /** - * is this node its parent's left child? mind you, the node, or - * its parent, may not exist. no problem. if the node doesn't - * exist ... it's its non-existent parent's left child. If the - * node does exist but has no parent ... no, we're not the - * non-existent parent's left child. Otherwise (both the specified - * node AND its parent exist), check. - * - * @param node the node (may be null) in question - * @param index the KEY or VALUE int - */ - private static boolean isLeftChild(final Node node, final int index) { - return (node == null) - ? true - : ((node.getParent(index) == null) ? - false : (node == node.getParent(index).getLeft(index))); - } - - /** - * is this node its parent's right child? mind you, the node, or - * its parent, may not exist. no problem. if the node doesn't - * exist ... it's its non-existent parent's right child. If the - * node does exist but has no parent ... no, we're not the - * non-existent parent's right child. Otherwise (both the - * specified node AND its parent exist), check. - * - * @param node the node (may be null) in question - * @param index the KEY or VALUE int - */ - private static boolean isRightChild(final Node node, final int index) { - return (node == null) - ? true - : ((node.getParent(index) == null) ? - false : (node == node.getParent(index).getRight(index))); + private Node getLeftChild(final Node node, final DataElement dataElement) { + return node == null ? null : node.getLeft(dataElement); } /** @@ -888,26 +817,26 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { * @param node the node to be rotated * @param index the KEY or VALUE int */ - private void rotateLeft(final Node node, final int index) { - Node rightChild = node.getRight(index); - node.setRight(rightChild.getLeft(index), index); + private void rotateLeft(final Node node, final DataElement dataElement) { + Node rightChild = node.getRight(dataElement); + node.setRight(rightChild.getLeft(dataElement), dataElement); - if (rightChild.getLeft(index) != null) { - rightChild.getLeft(index).setParent(node, index); + if (rightChild.getLeft(dataElement) != null) { + rightChild.getLeft(dataElement).setParent(node, dataElement); } - rightChild.setParent(node.getParent(index), index); - - if (node.getParent(index) == null) { + rightChild.setParent(node.getParent(dataElement), dataElement); + + if (node.getParent(dataElement) == null) { // node was the root ... now its right child is the root - rootNode[index] = rightChild; - } else if (node.getParent(index).getLeft(index) == node) { - node.getParent(index).setLeft(rightChild, index); + rootNode[dataElement.ordinal()] = rightChild; + } else if (node.getParent(dataElement).getLeft(dataElement) == node) { + node.getParent(dataElement).setLeft(rightChild, dataElement); } else { - node.getParent(index).setRight(rightChild, index); + node.getParent(dataElement).setRight(rightChild, dataElement); } - rightChild.setLeft(node, index); - node.setParent(rightChild, index); + rightChild.setLeft(node, dataElement); + node.setParent(rightChild, dataElement); } /** @@ -916,25 +845,25 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { * @param node the node to be rotated * @param index the KEY or VALUE int */ - private void rotateRight(final Node node, final int index) { - Node leftChild = node.getLeft(index); - node.setLeft(leftChild.getRight(index), index); - if (leftChild.getRight(index) != null) { - leftChild.getRight(index).setParent(node, index); + private void rotateRight(final Node node, final DataElement dataElement) { + Node leftChild = node.getLeft(dataElement); + node.setLeft(leftChild.getRight(dataElement), dataElement); + if (leftChild.getRight(dataElement) != null) { + leftChild.getRight(dataElement).setParent(node, dataElement); } - leftChild.setParent(node.getParent(index), index); + leftChild.setParent(node.getParent(dataElement), dataElement); - if (node.getParent(index) == null) { + if (node.getParent(dataElement) == null) { // node was the root ... now its left child is the root - rootNode[index] = leftChild; - } else if (node.getParent(index).getRight(index) == node) { - node.getParent(index).setRight(leftChild, index); + rootNode[dataElement.ordinal()] = leftChild; + } else if (node.getParent(dataElement).getRight(dataElement) == node) { + node.getParent(dataElement).setRight(leftChild, dataElement); } else { - node.getParent(index).setLeft(leftChild, index); + node.getParent(dataElement).setLeft(leftChild, dataElement); } - leftChild.setRight(node, index); - node.setParent(leftChild, index); + leftChild.setRight(node, dataElement); + node.setParent(leftChild, dataElement); } /** @@ -942,67 +871,69 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { * implementation, though it's barely recognizable any more * * @param insertedNode the node to be inserted - * @param index the KEY or VALUE int + * @param dataElement the KEY or VALUE int */ - private void doRedBlackInsert(final Node insertedNode, final int index) { - Node currentNode = insertedNode; - makeRed(currentNode, index); + private void doRedBlackInsert(final Node insertedNode, final DataElement dataElement) { + Node currentNode = insertedNode; + makeRed(currentNode, dataElement); while ((currentNode != null) - && (currentNode != rootNode[index]) - && (isRed(currentNode.getParent(index), index))) { - if (isLeftChild(getParent(currentNode, index), index)) { - Node y = getRightChild(getGrandParent(currentNode, index), index); + && (currentNode != rootNode[dataElement.ordinal()]) + && (isRed(currentNode.getParent(dataElement), dataElement))) { + if (currentNode.isLeftChild(dataElement)) { + Node y = getRightChild(getGrandParent(currentNode, dataElement), dataElement); - if (isRed(y, index)) { - makeBlack(getParent(currentNode, index), index); - makeBlack(y, index); - makeRed(getGrandParent(currentNode, index), index); + if (isRed(y, dataElement)) { + makeBlack(getParent(currentNode, dataElement), dataElement); + makeBlack(y, dataElement); + makeRed(getGrandParent(currentNode, dataElement), dataElement); - currentNode = getGrandParent(currentNode, index); + currentNode = getGrandParent(currentNode, dataElement); } else { - if (isRightChild(currentNode, index)) { - currentNode = getParent(currentNode, index); + //dead code? + if (currentNode.isRightChild(dataElement)) { + currentNode = getParent(currentNode, dataElement); - rotateLeft(currentNode, index); + rotateLeft(currentNode, dataElement); } - makeBlack(getParent(currentNode, index), index); - makeRed(getGrandParent(currentNode, index), index); + makeBlack(getParent(currentNode, dataElement), dataElement); + makeRed(getGrandParent(currentNode, dataElement), dataElement); - if (getGrandParent(currentNode, index) != null) { - rotateRight(getGrandParent(currentNode, index), index); + if (getGrandParent(currentNode, dataElement) != null) { + rotateRight(getGrandParent(currentNode, dataElement), dataElement); } } } else { // just like clause above, except swap left for right - Node y = getLeftChild(getGrandParent(currentNode, index), index); + Node y = getLeftChild(getGrandParent(currentNode, dataElement), dataElement); - if (isRed(y, index)) { - makeBlack(getParent(currentNode, index), index); - makeBlack(y, index); - makeRed(getGrandParent(currentNode, index), index); + if (isRed(y, dataElement)) { + makeBlack(getParent(currentNode, dataElement), dataElement); + makeBlack(y, dataElement); + makeRed(getGrandParent(currentNode, dataElement), dataElement); - currentNode = getGrandParent(currentNode, index); + currentNode = getGrandParent(currentNode, dataElement); } else { - if (isLeftChild(currentNode, index)) { - currentNode = getParent(currentNode, index); + //dead code? + if (currentNode.isLeftChild(dataElement)) { + currentNode = getParent(currentNode, dataElement); - rotateRight(currentNode, index); + rotateRight(currentNode, dataElement); } - makeBlack(getParent(currentNode, index), index); - makeRed(getGrandParent(currentNode, index), index); + makeBlack(getParent(currentNode, dataElement), dataElement); + makeRed(getGrandParent(currentNode, dataElement), dataElement); - if (getGrandParent(currentNode, index) != null) { - rotateLeft(getGrandParent(currentNode, index), index); + if (getGrandParent(currentNode, dataElement) != null) { + rotateLeft(getGrandParent(currentNode, dataElement), dataElement); } } } } - makeBlack(rootNode[index], index); + makeBlack(rootNode[dataElement.ordinal()], dataElement); } /** @@ -1011,57 +942,57 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { * * @param deletedNode the node to be deleted */ - private void doRedBlackDelete(final Node deletedNode) { - for (int index = FIRST_INDEX; index < NUMBER_OF_INDICES; index++) { + private void doRedBlackDelete(final Node deletedNode) { + for (DataElement dataElement : DataElement.values()) { // if deleted node has both left and children, swap with // the next greater node - if ((deletedNode.getLeft(index) != null) && (deletedNode.getRight(index) != null)) { - swapPosition(nextGreater(deletedNode, index), deletedNode, index); + if ((deletedNode.getLeft(dataElement) != null) && (deletedNode.getRight(dataElement) != null)) { + swapPosition(nextGreater(deletedNode, dataElement), deletedNode, dataElement); } - Node replacement = - ((deletedNode.getLeft(index) != null) ? deletedNode.getLeft(index) : deletedNode.getRight(index)); + Node replacement = + ((deletedNode.getLeft(dataElement) != null) ? deletedNode.getLeft(dataElement) : deletedNode.getRight(dataElement)); if (replacement != null) { - replacement.setParent(deletedNode.getParent(index), index); + replacement.setParent(deletedNode.getParent(dataElement), dataElement); - if (deletedNode.getParent(index) == null) { - rootNode[index] = replacement; - } else if (deletedNode == deletedNode.getParent(index).getLeft(index)) { - deletedNode.getParent(index).setLeft(replacement, index); + if (deletedNode.getParent(dataElement) == null) { + rootNode[dataElement.ordinal()] = replacement; + } else if (deletedNode == deletedNode.getParent(dataElement).getLeft(dataElement)) { + deletedNode.getParent(dataElement).setLeft(replacement, dataElement); } else { - deletedNode.getParent(index).setRight(replacement, index); + deletedNode.getParent(dataElement).setRight(replacement, dataElement); } - deletedNode.setLeft(null, index); - deletedNode.setRight(null, index); - deletedNode.setParent(null, index); + deletedNode.setLeft(null, dataElement); + deletedNode.setRight(null, dataElement); + deletedNode.setParent(null, dataElement); - if (isBlack(deletedNode, index)) { - doRedBlackDeleteFixup(replacement, index); + if (isBlack(deletedNode, dataElement)) { + doRedBlackDeleteFixup(replacement, dataElement); } } else { // replacement is null - if (deletedNode.getParent(index) == null) { + if (deletedNode.getParent(dataElement) == null) { // empty tree - rootNode[index] = null; + rootNode[dataElement.ordinal()] = null; } else { // deleted node had no children - if (isBlack(deletedNode, index)) { - doRedBlackDeleteFixup(deletedNode, index); + if (isBlack(deletedNode, dataElement)) { + doRedBlackDeleteFixup(deletedNode, dataElement); } - if (deletedNode.getParent(index) != null) { - if (deletedNode == deletedNode.getParent(index).getLeft(index)) { - deletedNode.getParent(index).setLeft(null, index); + if (deletedNode.getParent(dataElement) != null) { + if (deletedNode == deletedNode.getParent(dataElement).getLeft(dataElement)) { + deletedNode.getParent(dataElement).setLeft(null, dataElement); } else { - deletedNode.getParent(index).setRight(null, index); + deletedNode.getParent(dataElement).setRight(null, dataElement); } - deletedNode.setParent(null, index); + deletedNode.setParent(null, dataElement); } } } @@ -1076,80 +1007,80 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { * perfectly balanced -- perfect balancing takes longer) * * @param replacementNode the node being replaced - * @param index the KEY or VALUE int + * @param dataElement the KEY or VALUE int */ - private void doRedBlackDeleteFixup(final Node replacementNode, final int index) { - Node currentNode = replacementNode; + private void doRedBlackDeleteFixup(final Node replacementNode, final DataElement dataElement) { + Node currentNode = replacementNode; - while ((currentNode != rootNode[index]) && (isBlack(currentNode, index))) { - if (isLeftChild(currentNode, index)) { - Node siblingNode = getRightChild(getParent(currentNode, index), index); + while ((currentNode != rootNode[dataElement.ordinal()]) && (isBlack(currentNode, dataElement))) { + if (currentNode.isLeftChild(dataElement)) { + Node siblingNode = getRightChild(getParent(currentNode, dataElement), dataElement); - if (isRed(siblingNode, index)) { - makeBlack(siblingNode, index); - makeRed(getParent(currentNode, index), index); - rotateLeft(getParent(currentNode, index), index); + if (isRed(siblingNode, dataElement)) { + makeBlack(siblingNode, dataElement); + makeRed(getParent(currentNode, dataElement), dataElement); + rotateLeft(getParent(currentNode, dataElement), dataElement); - siblingNode = getRightChild(getParent(currentNode, index), index); + siblingNode = getRightChild(getParent(currentNode, dataElement), dataElement); } - if (isBlack(getLeftChild(siblingNode, index), index) - && isBlack(getRightChild(siblingNode, index), index)) { - makeRed(siblingNode, index); + if (isBlack(getLeftChild(siblingNode, dataElement), dataElement) + && isBlack(getRightChild(siblingNode, dataElement), dataElement)) { + makeRed(siblingNode, dataElement); - currentNode = getParent(currentNode, index); + currentNode = getParent(currentNode, dataElement); } else { - if (isBlack(getRightChild(siblingNode, index), index)) { - makeBlack(getLeftChild(siblingNode, index), index); - makeRed(siblingNode, index); - rotateRight(siblingNode, index); + if (isBlack(getRightChild(siblingNode, dataElement), dataElement)) { + makeBlack(getLeftChild(siblingNode, dataElement), dataElement); + makeRed(siblingNode, dataElement); + rotateRight(siblingNode, dataElement); - siblingNode = getRightChild(getParent(currentNode, index), index); + siblingNode = getRightChild(getParent(currentNode, dataElement), dataElement); } - copyColor(getParent(currentNode, index), siblingNode, index); - makeBlack(getParent(currentNode, index), index); - makeBlack(getRightChild(siblingNode, index), index); - rotateLeft(getParent(currentNode, index), index); + copyColor(getParent(currentNode, dataElement), siblingNode, dataElement); + makeBlack(getParent(currentNode, dataElement), dataElement); + makeBlack(getRightChild(siblingNode, dataElement), dataElement); + rotateLeft(getParent(currentNode, dataElement), dataElement); - currentNode = rootNode[index]; + currentNode = rootNode[dataElement.ordinal()]; } } else { - Node siblingNode = getLeftChild(getParent(currentNode, index), index); + Node siblingNode = getLeftChild(getParent(currentNode, dataElement), dataElement); - if (isRed(siblingNode, index)) { - makeBlack(siblingNode, index); - makeRed(getParent(currentNode, index), index); - rotateRight(getParent(currentNode, index), index); + if (isRed(siblingNode, dataElement)) { + makeBlack(siblingNode, dataElement); + makeRed(getParent(currentNode, dataElement), dataElement); + rotateRight(getParent(currentNode, dataElement), dataElement); - siblingNode = getLeftChild(getParent(currentNode, index), index); + siblingNode = getLeftChild(getParent(currentNode, dataElement), dataElement); } - if (isBlack(getRightChild(siblingNode, index), index) - && isBlack(getLeftChild(siblingNode, index), index)) { - makeRed(siblingNode, index); + if (isBlack(getRightChild(siblingNode, dataElement), dataElement) + && isBlack(getLeftChild(siblingNode, dataElement), dataElement)) { + makeRed(siblingNode, dataElement); - currentNode = getParent(currentNode, index); + currentNode = getParent(currentNode, dataElement); } else { - if (isBlack(getLeftChild(siblingNode, index), index)) { - makeBlack(getRightChild(siblingNode, index), index); - makeRed(siblingNode, index); - rotateLeft(siblingNode, index); + if (isBlack(getLeftChild(siblingNode, dataElement), dataElement)) { + makeBlack(getRightChild(siblingNode, dataElement), dataElement); + makeRed(siblingNode, dataElement); + rotateLeft(siblingNode, dataElement); - siblingNode = getLeftChild(getParent(currentNode, index), index); + siblingNode = getLeftChild(getParent(currentNode, dataElement), dataElement); } - copyColor(getParent(currentNode, index), siblingNode, index); - makeBlack(getParent(currentNode, index), index); - makeBlack(getLeftChild(siblingNode, index), index); - rotateRight(getParent(currentNode, index), index); + copyColor(getParent(currentNode, dataElement), siblingNode, dataElement); + makeBlack(getParent(currentNode, dataElement), dataElement); + makeBlack(getLeftChild(siblingNode, dataElement), dataElement); + rotateRight(getParent(currentNode, dataElement), dataElement); - currentNode = rootNode[index]; + currentNode = rootNode[dataElement.ordinal()]; } } } - makeBlack(currentNode, index); + makeBlack(currentNode, dataElement); } /** @@ -1159,94 +1090,94 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { * * @param x one node * @param y another node - * @param index the KEY or VALUE int + * @param dataElement the KEY or VALUE int */ - private void swapPosition(final Node x, final Node y, final int index) { + private void swapPosition(final Node x, final Node y, final DataElement dataElement) { // Save initial values. - Node xFormerParent = x.getParent(index); - Node xFormerLeftChild = x.getLeft(index); - Node xFormerRightChild = x.getRight(index); - Node yFormerParent = y.getParent(index); - Node yFormerLeftChild = y.getLeft(index); - Node yFormerRightChild = y.getRight(index); - boolean xWasLeftChild = (x.getParent(index) != null) && (x == x.getParent(index).getLeft(index)); - boolean yWasLeftChild = (y.getParent(index) != null) && (y == y.getParent(index).getLeft(index)); + Node xFormerParent = x.getParent(dataElement); + Node xFormerLeftChild = x.getLeft(dataElement); + Node xFormerRightChild = x.getRight(dataElement); + Node yFormerParent = y.getParent(dataElement); + Node yFormerLeftChild = y.getLeft(dataElement); + Node yFormerRightChild = y.getRight(dataElement); + boolean xWasLeftChild = (x.getParent(dataElement) != null) && (x == x.getParent(dataElement).getLeft(dataElement)); + boolean yWasLeftChild = (y.getParent(dataElement) != null) && (y == y.getParent(dataElement).getLeft(dataElement)); // Swap, handling special cases of one being the other's parent. if (x == yFormerParent) { // x was y's parent - x.setParent(y, index); + x.setParent(y, dataElement); if (yWasLeftChild) { - y.setLeft(x, index); - y.setRight(xFormerRightChild, index); + y.setLeft(x, dataElement); + y.setRight(xFormerRightChild, dataElement); } else { - y.setRight(x, index); - y.setLeft(xFormerLeftChild, index); + y.setRight(x, dataElement); + y.setLeft(xFormerLeftChild, dataElement); } } else { - x.setParent(yFormerParent, index); + x.setParent(yFormerParent, dataElement); if (yFormerParent != null) { if (yWasLeftChild) { - yFormerParent.setLeft(x, index); + yFormerParent.setLeft(x, dataElement); } else { - yFormerParent.setRight(x, index); + yFormerParent.setRight(x, dataElement); } } - y.setLeft(xFormerLeftChild, index); - y.setRight(xFormerRightChild, index); + y.setLeft(xFormerLeftChild, dataElement); + y.setRight(xFormerRightChild, dataElement); } if (y == xFormerParent) { // y was x's parent - y.setParent(x, index); + y.setParent(x, dataElement); if (xWasLeftChild) { - x.setLeft(y, index); - x.setRight(yFormerRightChild, index); + x.setLeft(y, dataElement); + x.setRight(yFormerRightChild, dataElement); } else { - x.setRight(y, index); - x.setLeft(yFormerLeftChild, index); + x.setRight(y, dataElement); + x.setLeft(yFormerLeftChild, dataElement); } } else { - y.setParent(xFormerParent, index); + y.setParent(xFormerParent, dataElement); if (xFormerParent != null) { if (xWasLeftChild) { - xFormerParent.setLeft(y, index); + xFormerParent.setLeft(y, dataElement); } else { - xFormerParent.setRight(y, index); + xFormerParent.setRight(y, dataElement); } } - x.setLeft(yFormerLeftChild, index); - x.setRight(yFormerRightChild, index); + x.setLeft(yFormerLeftChild, dataElement); + x.setRight(yFormerRightChild, dataElement); } // Fix children's parent pointers - if (x.getLeft(index) != null) { - x.getLeft(index).setParent(x, index); + if (x.getLeft(dataElement) != null) { + x.getLeft(dataElement).setParent(x, dataElement); } - if (x.getRight(index) != null) { - x.getRight(index).setParent(x, index); + if (x.getRight(dataElement) != null) { + x.getRight(dataElement).setParent(x, dataElement); } - if (y.getLeft(index) != null) { - y.getLeft(index).setParent(y, index); + if (y.getLeft(dataElement) != null) { + y.getLeft(dataElement).setParent(y, dataElement); } - if (y.getRight(index) != null) { - y.getRight(index).setParent(y, index); + if (y.getRight(dataElement) != null) { + y.getRight(dataElement).setParent(y, dataElement); } - x.swapColors(y, index); + x.swapColors(y, dataElement); // Check if root changed - if (rootNode[index] == x) { - rootNode[index] = y; - } else if (rootNode[index] == y) { - rootNode[index] = x; + if (rootNode[dataElement.ordinal()] == x) { + rootNode[dataElement.ordinal()] = y; + } else if (rootNode[dataElement.ordinal()] == y) { + rootNode[dataElement.ordinal()] = x; } } @@ -1261,12 +1192,12 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { * @throws NullPointerException if o is null * @throws ClassCastException if o is not Comparable */ - private static void checkNonNullComparable(final Object o, final int index) { + private static void checkNonNullComparable(final Object o, final DataElement dataElement) { if (o == null) { - throw new NullPointerException(dataName[index] + " cannot be null"); + throw new NullPointerException(dataElement + " cannot be null"); } if (!(o instanceof Comparable)) { - throw new ClassCastException(dataName[index] + " must be Comparable"); + throw new ClassCastException(dataElement + " must be Comparable"); } } @@ -1342,11 +1273,11 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { * @throws IllegalArgumentException if the node already exists * in the value mapping */ - private void insertValue(final Node newNode) throws IllegalArgumentException { - Node node = rootNode[VALUE]; + private void insertValue(final Node newNode) throws IllegalArgumentException { + Node node = rootNode[VALUE.ordinal()]; while (true) { - int cmp = compare(newNode.getData(VALUE), node.getData(VALUE)); + int cmp = compare(newNode.getValue(), node.getValue()); if (cmp == 0) { throw new IllegalArgumentException( @@ -1374,7 +1305,7 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { } } } - + //----------------------------------------------------------------------- /** * Compares for equals as per the API. @@ -1383,21 +1314,21 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { * @param type the KEY or VALUE int * @return true if equal */ - private boolean doEquals(Object obj, final int type) { + private boolean doEquals(Object obj, DataElement dataElement) { if (obj == this) { return true; } if (obj instanceof Map == false) { return false; } - Map other = (Map) obj; + Map other = (Map) obj; if (other.size() != size()) { return false; } if (nodeCount > 0) { try { - for (MapIterator it = new ViewMapIterator(this, type); it.hasNext(); ) { + for (MapIterator it = getMapIterator(dataElement); it.hasNext(); ) { Object key = it.next(); Object value = it.getValue(); if (value.equals(other.get(key)) == false) { @@ -1419,10 +1350,10 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { * @param type the KEY or VALUE int * @return the hash code value for this map */ - private int doHashCode(final int type) { + private int doHashCode(DataElement dataElement) { int total = 0; if (nodeCount > 0) { - for (MapIterator it = new ViewMapIterator(this, type); it.hasNext(); ) { + for (MapIterator it = getMapIterator(dataElement); it.hasNext(); ) { Object key = it.next(); Object value = it.getValue(); total += (key.hashCode() ^ value.hashCode()); @@ -1430,20 +1361,20 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { } return total; } - + /** * Gets the string form of this map as per AbstractMap. * * @param type the KEY or VALUE int * @return the string form of this map */ - private String doToString(final int type) { + private String doToString(DataElement dataElement) { if (nodeCount == 0) { return "{}"; } StringBuffer buf = new StringBuffer(nodeCount * 32); buf.append('{'); - MapIterator it = new ViewMapIterator(this, type); + MapIterator it = getMapIterator(dataElement); boolean hasNext = it.hasNext(); while (hasNext) { Object key = it.next(); @@ -1462,260 +1393,400 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { return buf.toString(); } + private MapIterator getMapIterator(DataElement dataElement) { + switch (dataElement) { + case KEY: + return new ViewMapIterator(KEY); + case VALUE: + return new InverseViewMapIterator(VALUE); + default: + throw new IllegalArgumentException(); + } + } + //----------------------------------------------------------------------- /** * A view of this map. */ - static class View extends AbstractSet { - - /** The parent map. */ - protected final TreeBidiMap main; + abstract class View extends AbstractSet { + /** Whether to return KEY or VALUE order. */ - protected final int orderType; - /** Whether to return KEY, VALUE, MAPENTRY or INVERSEMAPENTRY data. */ - protected final int dataType; + protected final DataElement orderType; /** * Constructor. - * - * @param main the main map * @param orderType the KEY or VALUE int for the order - * @param dataType the KEY, VALUE, MAPENTRY or INVERSEMAPENTRY int + * @param main the main map */ - View(final TreeBidiMap main, final int orderType, final int dataType) { + View(final DataElement orderType) { super(); - this.main = main; this.orderType = orderType; - this.dataType = dataType; - } - - public Iterator iterator() { - return new ViewIterator(main, orderType, dataType); } public int size() { - return main.size(); - } - - public boolean contains(final Object obj) { - checkNonNullComparable(obj, dataType); - return (main.lookup((Comparable) obj, dataType) != null); - } - - public boolean remove(final Object obj) { - return (main.doRemove((Comparable) obj, dataType) != null); + return TreeBidiMap.this.size(); } public void clear() { - main.clear(); + TreeBidiMap.this.clear(); } } - //----------------------------------------------------------------------- - /** - * An iterator over the map. - */ - static class ViewIterator implements OrderedIterator { - - /** The parent map. */ - protected final TreeBidiMap main; - /** Whether to return KEY or VALUE order. */ - protected final int orderType; - /** Whether to return KEY, VALUE, MAPENTRY or INVERSEMAPENTRY data. */ - protected final int dataType; - /** The last node returned by the iterator. */ - protected Node lastReturnedNode; - /** The next node to be returned by the iterator. */ - protected Node nextNode; - /** The previous node in the sequence returned by the iterator. */ - protected Node previousNode; - /** The modification count. */ - private int expectedModifications; + class KeyView extends View { /** - * Constructor. - * - * @param main the main map - * @param orderType the KEY or VALUE int for the order - * @param dataType the KEY, VALUE, MAPENTRY or INVERSEMAPENTRY int + * Create a new TreeBidiMap.KeyView. */ - ViewIterator(final TreeBidiMap main, final int orderType, final int dataType) { - super(); - this.main = main; - this.orderType = orderType; - this.dataType = dataType; - expectedModifications = main.modifications; - nextNode = leastNode(main.rootNode[orderType], orderType); - lastReturnedNode = null; - previousNode = null; + public KeyView(DataElement orderType) { + super(orderType); } - public final boolean hasNext() { - return (nextNode != null); + @Override + public Iterator iterator() { + return new ViewMapIterator(orderType); } - public final Object next() { - if (nextNode == null) { - throw new NoSuchElementException(); - } - if (main.modifications != expectedModifications) { - throw new ConcurrentModificationException(); - } - lastReturnedNode = nextNode; - previousNode = nextNode; - nextNode = main.nextGreater(nextNode, orderType); - return doGetData(); + @Override + public boolean contains(final Object obj) { + checkNonNullComparable(obj, KEY); + return (lookupKey(obj) != null); } - public boolean hasPrevious() { - return (previousNode != null); + @Override + public boolean remove(Object o) { + return doRemoveKey(o) != null; } - public Object previous() { - if (previousNode == null) { - throw new NoSuchElementException(); - } - if (main.modifications != expectedModifications) { - throw new ConcurrentModificationException(); - } - nextNode = lastReturnedNode; - if (nextNode == null) { - nextNode = main.nextGreater(previousNode, orderType); - } - lastReturnedNode = previousNode; - previousNode = main.nextSmaller(previousNode, orderType); - return doGetData(); - } - - /** - * Gets the data value for the lastReturnedNode field. - * @return the data value - */ - protected Object doGetData() { - switch (dataType) { - case KEY: - return lastReturnedNode.getKey(); - case VALUE: - return lastReturnedNode.getValue(); - case MAPENTRY: - return lastReturnedNode; - case INVERSEMAPENTRY: - return new UnmodifiableMapEntry(lastReturnedNode.getValue(), lastReturnedNode.getKey()); - } - return null; - } - - public final void remove() { - if (lastReturnedNode == null) { - throw new IllegalStateException(); - } - if (main.modifications != expectedModifications) { - throw new ConcurrentModificationException(); - } - main.doRedBlackDelete(lastReturnedNode); - expectedModifications++; - lastReturnedNode = null; - if (nextNode == null) { - previousNode = TreeBidiMap.greatestNode(main.rootNode[orderType], orderType); - } else { - previousNode = main.nextSmaller(nextNode, orderType); - } - } } - //----------------------------------------------------------------------- - /** - * An iterator over the map. - */ - static class ViewMapIterator extends ViewIterator implements OrderedMapIterator { + class ValueView extends View { - private final int oppositeType; - /** - * Constructor. - * - * @param main the main map - * @param orderType the KEY or VALUE int for the order + * Create a new TreeBidiMap.ValueView. */ - ViewMapIterator(final TreeBidiMap main, final int orderType) { - super(main, orderType, orderType); - this.oppositeType = oppositeIndex(dataType); - } - - public Object getKey() { - if (lastReturnedNode == null) { - throw new IllegalStateException("Iterator getKey() can only be called after next() and before remove()"); - } - return lastReturnedNode.getData(dataType); + public ValueView(DataElement orderType) { + super(orderType); } - public Object getValue() { - if (lastReturnedNode == null) { - throw new IllegalStateException("Iterator getValue() can only be called after next() and before remove()"); - } - return lastReturnedNode.getData(oppositeType); + @Override + public Iterator iterator() { + return new InverseViewMapIterator(orderType); } - public Object setValue(final Object obj) { - throw new UnsupportedOperationException(); + @Override + public boolean contains(final Object obj) { + checkNonNullComparable(obj, VALUE); + return (lookupValue(obj) != null); } + + @Override + public boolean remove(Object o) { + return doRemoveValue(o) != null; + } + } - //----------------------------------------------------------------------- /** * A view of this map. */ - static class EntryView extends View { - - private final int oppositeType; - - /** - * Constructor. - * - * @param main the main map - * @param orderType the KEY or VALUE int for the order - * @param dataType the MAPENTRY or INVERSEMAPENTRY int for the returned data - */ - EntryView(final TreeBidiMap main, final int orderType, final int dataType) { - super(main, orderType, dataType); - this.oppositeType = TreeBidiMap.oppositeIndex(orderType); + class EntryView extends View> { + + EntryView() { + super(KEY); } - + public boolean contains(Object obj) { if (obj instanceof Map.Entry == false) { return false; } - Map.Entry entry = (Map.Entry) obj; + Map.Entry entry = (Map.Entry) obj; Object value = entry.getValue(); - Node node = main.lookup((Comparable) entry.getKey(), orderType); - return (node != null && node.getData(oppositeType).equals(value)); + Node node = lookupKey(entry.getKey()); + return node != null && node.getValue().equals(value); } 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 value = entry.getValue(); - Node node = main.lookup((Comparable) entry.getKey(), orderType); - if (node != null && node.getData(oppositeType).equals(value)) { - main.doRedBlackDelete(node); + Node node = lookupKey(entry.getKey()); + if (node != null && node.getValue().equals(value)) { + doRedBlackDelete(node); return true; } return false; } + + @Override + public Iterator> iterator() { + return new ViewMapEntryIterator(); + } + } + + /** + * A view of this map. + */ + class InverseEntryView extends View> { + + InverseEntryView() { + super(VALUE); + } + + public boolean contains(Object obj) { + if (obj instanceof Map.Entry == false) { + return false; + } + Map.Entry entry = (Map.Entry) obj; + Object value = entry.getValue(); + Node node = lookupValue(entry.getKey()); + return node != null && node.getKey().equals(value); + } + + public boolean remove(Object obj) { + if (obj instanceof Map.Entry == false) { + return false; + } + Map.Entry entry = (Map.Entry) obj; + Object value = entry.getValue(); + Node node = lookupValue(entry.getKey()); + if (node != null && node.getKey().equals(value)) { + doRedBlackDelete(node); + return true; + } + return false; + } + + @Override + public Iterator> iterator() { + return new InverseViewMapEntryIterator(); + } } + //----------------------------------------------------------------------- + /** + * An iterator over the map. + */ + abstract class ViewIterator { + + /** Whether to return KEY or VALUE order. */ + protected final DataElement orderType; + /** The last node returned by the iterator. */ + protected Node lastReturnedNode; + /** The next node to be returned by the iterator. */ + protected Node nextNode; + /** The previous node in the sequence returned by the iterator. */ + protected Node previousNode; + /** The modification count. */ + private int expectedModifications; + + /** + * Constructor. + * @param orderType the KEY or VALUE int for the order + * @param main the main map + */ + ViewIterator(final DataElement orderType) { + super(); + this.orderType = orderType; + expectedModifications = modifications; + nextNode = leastNode(rootNode[orderType.ordinal()], orderType); + lastReturnedNode = null; + previousNode = null; + } + + public final boolean hasNext() { + return nextNode != null; + } + + protected Node navigateNext() { + if (nextNode == null) { + throw new NoSuchElementException(); + } + if (modifications != expectedModifications) { + throw new ConcurrentModificationException(); + } + lastReturnedNode = nextNode; + previousNode = nextNode; + nextNode = nextGreater(nextNode, orderType); + return lastReturnedNode; + } + + public boolean hasPrevious() { + return previousNode != null; + } + + protected Node navigatePrevious() { + if (previousNode == null) { + throw new NoSuchElementException(); + } + if (modifications != expectedModifications) { + throw new ConcurrentModificationException(); + } + nextNode = lastReturnedNode; + if (nextNode == null) { + nextNode = nextGreater(previousNode, orderType); + } + lastReturnedNode = previousNode; + previousNode = nextSmaller(previousNode, orderType); + return lastReturnedNode; + } + + public final void remove() { + if (lastReturnedNode == null) { + throw new IllegalStateException(); + } + if (modifications != expectedModifications) { + throw new ConcurrentModificationException(); + } + doRedBlackDelete(lastReturnedNode); + expectedModifications++; + lastReturnedNode = null; + if (nextNode == null) { + previousNode = greatestNode(rootNode[orderType.ordinal()], orderType); + } else { + previousNode = nextSmaller(nextNode, orderType); + } + } + } + + //----------------------------------------------------------------------- + /** + * An iterator over the map. + */ + class ViewMapIterator extends ViewIterator implements OrderedMapIterator { + + /** + * Constructor. + */ + ViewMapIterator(DataElement orderType) { + super(orderType); + } + + public K getKey() { + if (lastReturnedNode == null) { + throw new IllegalStateException("Iterator getKey() can only be called after next() and before remove()"); + } + return lastReturnedNode.getKey(); + } + + public V getValue() { + if (lastReturnedNode == null) { + throw new IllegalStateException("Iterator getValue() can only be called after next() and before remove()"); + } + return lastReturnedNode.getValue(); + } + + public V setValue(final V obj) { + throw new UnsupportedOperationException(); + } + + public K next() { + return navigateNext().getKey(); + } + + public K previous() { + return navigatePrevious().getKey(); + } + } + + /** + * An iterator over the map. + */ + class InverseViewMapIterator extends ViewIterator implements OrderedMapIterator { + + /** + * Create a new TreeBidiMap.InverseViewMapIterator. + */ + public InverseViewMapIterator(DataElement orderType) { + super(orderType); + } + + public V getKey() { + if (lastReturnedNode == null) { + throw new IllegalStateException("Iterator getKey() can only be called after next() and before remove()"); + } + return lastReturnedNode.getValue(); + } + + public K getValue() { + if (lastReturnedNode == null) { + throw new IllegalStateException("Iterator getValue() can only be called after next() and before remove()"); + } + return lastReturnedNode.getKey(); + } + + public K setValue(final K obj) { + throw new UnsupportedOperationException(); + } + + public V next() { + return navigateNext().getValue(); + } + + public V previous() { + return navigatePrevious().getValue(); + } + } + + /** + * An iterator over the map entries. + */ + class ViewMapEntryIterator extends ViewIterator implements OrderedIterator> { + + /** + * Constructor. + */ + ViewMapEntryIterator() { + super(KEY); + } + + public Map.Entry next() { + return navigateNext(); + } + + public Map.Entry previous() { + return navigatePrevious(); + } + } + + /** + * An iterator over the inverse map entries. + */ + class InverseViewMapEntryIterator extends ViewIterator implements OrderedIterator> { + + /** + * Constructor. + */ + InverseViewMapEntryIterator() { + super(VALUE); + } + + public Map.Entry next() { + return createEntry(navigateNext()); + } + + public Map.Entry previous() { + return createEntry(navigatePrevious()); + } + + private Map.Entry createEntry(Node node) { + return new UnmodifiableMapEntry(node.getValue(), node.getKey()); + } + } + + //----------------------------------------------------------------------- //----------------------------------------------------------------------- /** * A node used to store the data. */ - static class Node implements Map.Entry, KeyValue, Serializable { + static class Node, V extends Comparable> implements Map.Entry, KeyValue { - private Comparable[] data; - private Node[] leftNode; - private Node[] rightNode; - private Node[] parentNode; + private K key; + private V value; + private Node[] leftNode; + private Node[] rightNode; + private Node[] parentNode; private boolean[] blackColor; private int hashcodeValue; private boolean calculatedHashCode; @@ -1727,9 +1798,11 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { * @param key * @param value */ - Node(final Comparable key, final Comparable value) { + @SuppressWarnings("unchecked") + Node(final K key, final V value) { super(); - data = new Comparable[] { key, value }; + this.key = key; + this.value = value; leftNode = new Node[2]; rightNode = new Node[2]; parentNode = new Node[2]; @@ -1737,54 +1810,31 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { calculatedHashCode = false; } - /** - * Get the specified data. - * - * @param index the KEY or VALUE int - * @return the key or value - */ - private Comparable getData(final int index) { - return data[index]; + private Object getData(final DataElement dataElement) { + switch (dataElement) { + case KEY: + return getKey(); + case VALUE: + return getValue(); + default: + throw new IllegalArgumentException(); + } } - /** - * Set this node's left node. - * - * @param node the new left node - * @param index the KEY or VALUE int - */ - private void setLeft(final Node node, final int index) { - leftNode[index] = node; + private void setLeft(final Node node, final DataElement dataElement) { + leftNode[dataElement.ordinal()] = node; } - /** - * Get the left node. - * - * @param index the KEY or VALUE int - * @return the left node, may be null - */ - private Node getLeft(final int index) { - return leftNode[index]; + private Node getLeft(final DataElement dataElement) { + return leftNode[dataElement.ordinal()]; } - /** - * Set this node's right node. - * - * @param node the new right node - * @param index the KEY or VALUE int - */ - private void setRight(final Node node, final int index) { - rightNode[index] = node; + private void setRight(final Node node, final DataElement dataElement) { + rightNode[dataElement.ordinal()] = node; } - /** - * Get the right node. - * - * @param index the KEY or VALUE int - * @return the right node, may be null - */ - private Node getRight(final int index) { - return rightNode[index]; + private Node getRight(final DataElement dataElement) { + return rightNode[dataElement.ordinal()]; } /** @@ -1793,8 +1843,8 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { * @param node the new parent node * @param index the KEY or VALUE int */ - private void setParent(final Node node, final int index) { - parentNode[index] = node; + private void setParent(final Node node, final DataElement dataElement) { + parentNode[dataElement.ordinal()] = node; } /** @@ -1803,8 +1853,8 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { * @param index the KEY or VALUE int * @return the parent node, may be null */ - private Node getParent(final int index) { - return parentNode[index]; + private Node getParent(final DataElement dataElement) { + return parentNode[dataElement.ordinal()]; } /** @@ -1813,11 +1863,11 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { * @param node the node to swap with * @param index the KEY or VALUE int */ - private void swapColors(final Node node, final int index) { + private void swapColors(final Node node, final DataElement dataElement) { // Swap colors -- old hacker's trick - blackColor[index] ^= node.blackColor[index]; - node.blackColor[index] ^= blackColor[index]; - blackColor[index] ^= node.blackColor[index]; + blackColor[dataElement.ordinal()] ^= node.blackColor[dataElement.ordinal()]; + node.blackColor[dataElement.ordinal()] ^= blackColor[dataElement.ordinal()]; + blackColor[dataElement.ordinal()] ^= node.blackColor[dataElement.ordinal()]; } /** @@ -1826,8 +1876,8 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { * @param index the KEY or VALUE int * @return true if black (which is represented as a true boolean) */ - private boolean isBlack(final int index) { - return blackColor[index]; + private boolean isBlack(final DataElement dataElement) { + return blackColor[dataElement.ordinal()]; } /** @@ -1836,8 +1886,8 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { * @param index the KEY or VALUE int * @return true if non-black */ - private boolean isRed(final int index) { - return !blackColor[index]; + private boolean isRed(final DataElement dataElement) { + return !blackColor[dataElement.ordinal()]; } /** @@ -1845,8 +1895,8 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { * * @param index the KEY or VALUE int */ - private void setBlack(final int index) { - blackColor[index] = true; + private void setBlack(final DataElement dataElement) { + blackColor[dataElement.ordinal()] = true; } /** @@ -1854,8 +1904,8 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { * * @param index the KEY or VALUE int */ - private void setRed(final int index) { - blackColor[index] = false; + private void setRed(final DataElement dataElement) { + blackColor[dataElement.ordinal()] = false; } /** @@ -1864,27 +1914,37 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { * @param node the node whose color we're adopting * @param index the KEY or VALUE int */ - private void copyColor(final Node node, final int index) { - blackColor[index] = node.blackColor[index]; + private void copyColor(final Node node, final DataElement dataElement) { + blackColor[dataElement.ordinal()] = node.blackColor[dataElement.ordinal()]; + } + + private boolean isLeftChild(final DataElement dataElement) { + return parentNode[dataElement.ordinal()] != null + && parentNode[dataElement.ordinal()].leftNode[dataElement.ordinal()] == this; + } + + private boolean isRightChild(final DataElement dataElement) { + return parentNode[dataElement.ordinal()] != null + && parentNode[dataElement.ordinal()].rightNode[dataElement.ordinal()] == this; } //------------------------------------------------------------------- /** * Gets the key. - * + * * @return the key corresponding to this entry. */ - public Object getKey() { - return data[KEY]; + public K getKey() { + return key; } /** * Gets the value. - * + * * @return the value corresponding to this entry. */ - public Object getValue() { - return data[VALUE]; + public V getValue() { + return value; } /** @@ -1894,10 +1954,8 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { * @return does not return * @throws UnsupportedOperationException always */ - public Object setValue(final Object ignored) - throws UnsupportedOperationException { - throw new UnsupportedOperationException( - "Map.Entry.setValue is not supported"); + public V setValue(final V ignored) throws UnsupportedOperationException { + throw new UnsupportedOperationException("Map.Entry.setValue is not supported"); } /** @@ -1915,8 +1973,8 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { if (!(obj instanceof Map.Entry)) { return false; } - Map.Entry e = (Map.Entry) obj; - return data[KEY].equals(e.getKey()) && data[VALUE].equals(e.getValue()); + Map.Entry e = (Map.Entry) obj; + return getKey().equals(e.getKey()) && getValue().equals(e.getValue()); } /** @@ -1924,164 +1982,142 @@ public class TreeBidiMap implements OrderedBidiMap, Serializable { */ public int hashCode() { if (!calculatedHashCode) { - hashcodeValue = data[KEY].hashCode() ^ data[VALUE].hashCode(); + hashcodeValue = getKey().hashCode() ^ getValue().hashCode(); calculatedHashCode = true; } return hashcodeValue; } } - + //----------------------------------------------------------------------- /** - * A node used to store the data. + * The inverse map implementation. */ - static class Inverse implements OrderedBidiMap { - - /** The parent map. */ - private final TreeBidiMap main; + class Inverse implements OrderedBidiMap { + /** Store the keySet once created. */ - private Set keySet; + private Set keySet; /** Store the valuesSet once created. */ - private Set valuesSet; + private Set valuesSet; /** Store the entrySet once created. */ - private Set entrySet; - - /** - * Constructor. - * @param main the main map - */ - Inverse(final TreeBidiMap main) { - super(); - this.main = main; - } + private Set> entrySet; public int size() { - return main.size(); + return TreeBidiMap.this.size(); } public boolean isEmpty() { - return main.isEmpty(); + return TreeBidiMap.this.isEmpty(); } - public Object get(final Object key) { - return main.getKey(key); + public K get(final Object key) { + return TreeBidiMap.this.getKey(key); } - public Object getKey(final Object value) { - return main.get(value); + public V getKey(final Object value) { + return TreeBidiMap.this.get(value); } public boolean containsKey(final Object key) { - return main.containsValue(key); + return TreeBidiMap.this.containsValue(key); } public boolean containsValue(final Object value) { - return main.containsKey(value); + return TreeBidiMap.this.containsKey(value); } - public Object firstKey() { - if (main.nodeCount == 0) { + public V firstKey() { + if (TreeBidiMap.this.nodeCount == 0) { throw new NoSuchElementException("Map is empty"); } - return TreeBidiMap.leastNode(main.rootNode[VALUE], VALUE).getValue(); + return leastNode(TreeBidiMap.this.rootNode[VALUE.ordinal()], VALUE).getValue(); } - public Object lastKey() { - if (main.nodeCount == 0) { + public V lastKey() { + if (TreeBidiMap.this.nodeCount == 0) { throw new NoSuchElementException("Map is empty"); } - return TreeBidiMap.greatestNode(main.rootNode[VALUE], VALUE).getValue(); + return greatestNode(TreeBidiMap.this.rootNode[VALUE.ordinal()], VALUE).getValue(); } - - public Object nextKey(Object key) { + + public V nextKey(V key) { checkKey(key); - Node node = main.nextGreater(main.lookup((Comparable) key, VALUE), VALUE); - return (node == null ? null : node.getValue()); + Node node = nextGreater(TreeBidiMap.this.lookup(key, VALUE), VALUE); + return node == null ? null : node.getValue(); } - public Object previousKey(Object key) { + public V previousKey(V key) { checkKey(key); - Node node = main.nextSmaller(main.lookup((Comparable) key, VALUE), VALUE); - return (node == null ? null : node.getValue()); + Node node = TreeBidiMap.this.nextSmaller(TreeBidiMap.this.lookup(key, VALUE), VALUE); + return node == null ? null : node.getValue(); } - public Object put(final Object key, final Object value) { - return main.doPut((Comparable) value, (Comparable) key, VALUE); + public K put(final V key, final K value) { + K result = get(key); + TreeBidiMap.this.doPut(value, key); + return result; } - public void putAll(Map map) { - Iterator it = map.entrySet().iterator(); - while (it.hasNext()) { - Map.Entry entry = (Map.Entry) it.next(); - put(entry.getKey(), entry.getValue()); + public void putAll(Map map) { + for (Map.Entry e : map.entrySet()) { + put(e.getKey(), e.getValue()); } } - - public Object remove(final Object key) { - return main.removeValue(key); + + public K remove(final Object key) { + return TreeBidiMap.this.removeValue(key); } - public Object removeValue(final Object value) { - return main.remove(value); + public V removeValue(final Object value) { + return TreeBidiMap.this.remove(value); } public void clear() { - main.clear(); + TreeBidiMap.this.clear(); } - public Set keySet() { + public Set keySet() { if (keySet == null) { - keySet = new View(main, VALUE, VALUE); + keySet = new ValueView(VALUE); } return keySet; } - public Collection values() { + public Collection values() { if (valuesSet == null) { - valuesSet = new View(main, VALUE, KEY); + valuesSet = new KeyView(VALUE); } return valuesSet; } - public Set entrySet() { + public Set> entrySet() { if (entrySet == null) { - entrySet= new EntryView(main, VALUE, INVERSEMAPENTRY); + return new InverseEntryView(); } return entrySet; } - - public MapIterator mapIterator() { + + public OrderedMapIterator mapIterator() { if (isEmpty()) { - return EmptyOrderedMapIterator.INSTANCE; + return EmptyOrderedMapIterator.getInstance(); } - return new ViewMapIterator(main, VALUE); + return new InverseViewMapIterator(VALUE); } - public OrderedMapIterator orderedMapIterator() { - if (isEmpty()) { - return EmptyOrderedMapIterator.INSTANCE; - } - return new ViewMapIterator(main, VALUE); + public OrderedBidiMap inverseBidiMap() { + return TreeBidiMap.this; } - public BidiMap inverseBidiMap() { - return main; - } - - public OrderedBidiMap inverseOrderedBidiMap() { - return main; - } - public boolean equals(Object obj) { - return main.doEquals(obj, VALUE); + return TreeBidiMap.this.doEquals(obj, DataElement.VALUE); } - + public int hashCode() { - return main.doHashCode(VALUE); + return TreeBidiMap.this.doHashCode(DataElement.VALUE); } - + public String toString() { - return main.doToString(VALUE); + return TreeBidiMap.this.doToString(DataElement.VALUE); } } diff --git a/src/java/org/apache/commons/collections/bidimap/UnmodifiableBidiMap.java b/src/java/org/apache/commons/collections/bidimap/UnmodifiableBidiMap.java index 9452227f1..b7ad0f014 100644 --- a/src/java/org/apache/commons/collections/bidimap/UnmodifiableBidiMap.java +++ b/src/java/org/apache/commons/collections/bidimap/UnmodifiableBidiMap.java @@ -38,36 +38,36 @@ import org.apache.commons.collections.set.UnmodifiableSet; * * @author Stephen Colebourne */ -public final class UnmodifiableBidiMap - extends AbstractBidiMapDecorator implements Unmodifiable { - +public final class UnmodifiableBidiMap + extends AbstractBidiMapDecorator implements Unmodifiable { + /** The inverse unmodifiable map */ - private UnmodifiableBidiMap inverse; + private UnmodifiableBidiMap inverse; /** * Factory method to create an unmodifiable map. *

* 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 BidiMap decorate(BidiMap map) { if (map instanceof Unmodifiable) { return map; } - return new UnmodifiableBidiMap(map); + return new UnmodifiableBidiMap(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 map) { super(map); } @@ -76,49 +76,49 @@ public final class UnmodifiableBidiMap throw new UnsupportedOperationException(); } - public Object put(Object key, Object value) { + public V put(K key, V value) { throw new UnsupportedOperationException(); } - public void putAll(Map mapToCopy) { + public void putAll(Map 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> entrySet() { + Set> set = super.entrySet(); return UnmodifiableEntrySet.decorate(set); } - public Set keySet() { - Set set = super.keySet(); + public Set keySet() { + Set set = super.keySet(); return UnmodifiableSet.decorate(set); } - public Collection values() { - Collection coll = super.values(); + public Collection values() { + Collection 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 mapIterator() { + MapIterator it = decorated().mapIterator(); return UnmodifiableMapIterator.decorate(it); } - public BidiMap inverseBidiMap() { + public synchronized BidiMap inverseBidiMap() { if (inverse == null) { - inverse = new UnmodifiableBidiMap(getBidiMap().inverseBidiMap()); + inverse = new UnmodifiableBidiMap(decorated().inverseBidiMap()); inverse.inverse = this; } return inverse; } - + } diff --git a/src/java/org/apache/commons/collections/bidimap/UnmodifiableOrderedBidiMap.java b/src/java/org/apache/commons/collections/bidimap/UnmodifiableOrderedBidiMap.java index a500dca28..f452bba3e 100644 --- a/src/java/org/apache/commons/collections/bidimap/UnmodifiableOrderedBidiMap.java +++ b/src/java/org/apache/commons/collections/bidimap/UnmodifiableOrderedBidiMap.java @@ -20,8 +20,6 @@ import java.util.Collection; import java.util.Map; import java.util.Set; -import org.apache.commons.collections.BidiMap; -import org.apache.commons.collections.MapIterator; import org.apache.commons.collections.OrderedBidiMap; import org.apache.commons.collections.OrderedMapIterator; import org.apache.commons.collections.Unmodifiable; @@ -40,36 +38,36 @@ import org.apache.commons.collections.set.UnmodifiableSet; * * @author Stephen Colebourne */ -public final class UnmodifiableOrderedBidiMap - extends AbstractOrderedBidiMapDecorator implements Unmodifiable { - +public final class UnmodifiableOrderedBidiMap + extends AbstractOrderedBidiMapDecorator implements Unmodifiable { + /** The inverse unmodifiable map */ - private UnmodifiableOrderedBidiMap inverse; + private UnmodifiableOrderedBidiMap inverse; /** * Factory method to create an unmodifiable map. *

* 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 OrderedBidiMap decorate(OrderedBidiMap map) { if (map instanceof Unmodifiable) { return map; } - return new UnmodifiableOrderedBidiMap(map); + return new UnmodifiableOrderedBidiMap(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 map) { super(map); } @@ -78,55 +76,51 @@ public final class UnmodifiableOrderedBidiMap throw new UnsupportedOperationException(); } - public Object put(Object key, Object value) { + public V put(K key, V value) { throw new UnsupportedOperationException(); } - public void putAll(Map mapToCopy) { + public void putAll(Map 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> entrySet() { + Set> set = super.entrySet(); return UnmodifiableEntrySet.decorate(set); } - public Set keySet() { - Set set = super.keySet(); + public Set keySet() { + Set set = super.keySet(); return UnmodifiableSet.decorate(set); } - public Collection values() { - Collection coll = super.values(); + public Collection values() { + Collection 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 inverseBidiMap() { return inverseOrderedBidiMap(); } - + //----------------------------------------------------------------------- - public OrderedMapIterator orderedMapIterator() { - OrderedMapIterator it = getOrderedBidiMap().orderedMapIterator(); + public OrderedMapIterator mapIterator() { + OrderedMapIterator it = decorated().mapIterator(); return UnmodifiableOrderedMapIterator.decorate(it); } - public OrderedBidiMap inverseOrderedBidiMap() { + public OrderedBidiMap inverseOrderedBidiMap() { if (inverse == null) { - inverse = new UnmodifiableOrderedBidiMap(getOrderedBidiMap().inverseOrderedBidiMap()); + inverse = new UnmodifiableOrderedBidiMap(decorated().inverseBidiMap()); inverse.inverse = this; } return inverse; diff --git a/src/java/org/apache/commons/collections/bidimap/UnmodifiableSortedBidiMap.java b/src/java/org/apache/commons/collections/bidimap/UnmodifiableSortedBidiMap.java index 870b8cc0c..764a7ecba 100644 --- a/src/java/org/apache/commons/collections/bidimap/UnmodifiableSortedBidiMap.java +++ b/src/java/org/apache/commons/collections/bidimap/UnmodifiableSortedBidiMap.java @@ -21,9 +21,6 @@ import java.util.Map; import java.util.Set; import java.util.SortedMap; -import org.apache.commons.collections.BidiMap; -import org.apache.commons.collections.MapIterator; -import org.apache.commons.collections.OrderedBidiMap; import org.apache.commons.collections.OrderedMapIterator; import org.apache.commons.collections.SortedBidiMap; import org.apache.commons.collections.Unmodifiable; @@ -43,36 +40,36 @@ import org.apache.commons.collections.set.UnmodifiableSet; * * @author Stephen Colebourne */ -public final class UnmodifiableSortedBidiMap - extends AbstractSortedBidiMapDecorator implements Unmodifiable { - +public final class UnmodifiableSortedBidiMap + extends AbstractSortedBidiMapDecorator implements Unmodifiable { + /** The inverse unmodifiable map */ - private UnmodifiableSortedBidiMap inverse; + private UnmodifiableSortedBidiMap inverse; /** * Factory method to create an unmodifiable map. *

* 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 SortedBidiMap decorate(SortedBidiMap map) { if (map instanceof Unmodifiable) { return map; } - return new UnmodifiableSortedBidiMap(map); + return new UnmodifiableSortedBidiMap(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 map) { super(map); } @@ -81,77 +78,65 @@ public final class UnmodifiableSortedBidiMap throw new UnsupportedOperationException(); } - public Object put(Object key, Object value) { + public V put(K key, V value) { throw new UnsupportedOperationException(); } - public void putAll(Map mapToCopy) { + public void putAll(Map 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> entrySet() { + Set> set = super.entrySet(); return UnmodifiableEntrySet.decorate(set); } - public Set keySet() { - Set set = super.keySet(); + public Set keySet() { + Set set = super.keySet(); return UnmodifiableSet.decorate(set); } - public Collection values() { - Collection coll = super.values(); + public Collection values() { + Collection 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 mapIterator() { + OrderedMapIterator it = decorated().mapIterator(); return UnmodifiableOrderedMapIterator.decorate(it); } - public OrderedBidiMap inverseOrderedBidiMap() { - return inverseSortedBidiMap(); - } - //----------------------------------------------------------------------- - public SortedBidiMap inverseSortedBidiMap() { + public SortedBidiMap inverseBidiMap() { if (inverse == null) { - inverse = new UnmodifiableSortedBidiMap(getSortedBidiMap().inverseSortedBidiMap()); + inverse = new UnmodifiableSortedBidiMap(decorated().inverseBidiMap()); inverse.inverse = this; } return inverse; } - public SortedMap subMap(Object fromKey, Object toKey) { - SortedMap sm = getSortedBidiMap().subMap(fromKey, toKey); + public SortedMap subMap(K fromKey, K toKey) { + SortedMap sm = decorated().subMap(fromKey, toKey); return UnmodifiableSortedMap.decorate(sm); } - public SortedMap headMap(Object toKey) { - SortedMap sm = getSortedBidiMap().headMap(toKey); + public SortedMap headMap(K toKey) { + SortedMap sm = decorated().headMap(toKey); return UnmodifiableSortedMap.decorate(sm); } - public SortedMap tailMap(Object fromKey) { - SortedMap sm = getSortedBidiMap().tailMap(fromKey); + public SortedMap tailMap(K fromKey) { + SortedMap sm = decorated().tailMap(fromKey); return UnmodifiableSortedMap.decorate(sm); } diff --git a/src/java/org/apache/commons/collections/buffer/BoundedFifoBuffer.java b/src/java/org/apache/commons/collections/buffer/BoundedFifoBuffer.java index afec58656..1fdab68ca 100644 --- a/src/java/org/apache/commons/collections/buffer/BoundedFifoBuffer.java +++ b/src/java/org/apache/commons/collections/buffer/BoundedFifoBuffer.java @@ -35,7 +35,7 @@ import org.apache.commons.collections.BufferUnderflowException; * The BoundedFifoBuffer is a very efficient implementation of * Buffer that is of a fixed size. *

- * The removal order of a BoundedFifoBuffer is based on the + * The removal order of a BoundedFifoBuffer 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. *

@@ -62,30 +62,30 @@ import org.apache.commons.collections.BufferUnderflowException; * @author Stephen Colebourne * @author Herve Quiroz */ -public class BoundedFifoBuffer extends AbstractCollection - implements Buffer, BoundedCollection, Serializable { +public class BoundedFifoBuffer extends AbstractCollection + implements Buffer, BoundedCollection, 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 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 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 iterator() { + return new Iterator() { 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(); } diff --git a/src/java/org/apache/commons/collections/buffer/CircularFifoBuffer.java b/src/java/org/apache/commons/collections/buffer/CircularFifoBuffer.java index cdbfae21a..1f354fd74 100644 --- a/src/java/org/apache/commons/collections/buffer/CircularFifoBuffer.java +++ b/src/java/org/apache/commons/collections/buffer/CircularFifoBuffer.java @@ -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. *

- * The removal order of a CircularFifoBuffer is based on the + * The removal order of a CircularFifoBuffer 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. *

@@ -46,7 +46,7 @@ import java.util.Collection; * @author Stefano Fornari * @author Stephen Colebourne */ -public class CircularFifoBuffer extends BoundedFifoBuffer { +public class CircularFifoBuffer extends BoundedFifoBuffer { /** 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 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); } - + } diff --git a/src/java/org/apache/commons/collections/buffer/PriorityBuffer.java b/src/java/org/apache/commons/collections/buffer/PriorityBuffer.java index 87792cf8d..66d66d022 100644 --- a/src/java/org/apache/commons/collections/buffer/PriorityBuffer.java +++ b/src/java/org/apache/commons/collections/buffer/PriorityBuffer.java @@ -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 Buffer 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 extends AbstractCollection implements Buffer, 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 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 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 comparator) { this(DEFAULT_CAPACITY, ascendingOrder, comparator); } @@ -155,7 +158,7 @@ public class PriorityBuffer extends AbstractCollection * null means use natural order * @throws IllegalArgumentException if capacity is <= 0 */ - public PriorityBuffer(int capacity, Comparator comparator) { + public PriorityBuffer(int capacity, Comparator comparator) { this(capacity, true, comparator); } @@ -183,7 +186,8 @@ public class PriorityBuffer extends AbstractCollection * null means use natural order * @throws IllegalArgumentException if capacity is <= 0 */ - public PriorityBuffer(int capacity, boolean ascendingOrder, Comparator comparator) { + @SuppressWarnings("unchecked") + public PriorityBuffer(int capacity, boolean ascendingOrder, Comparator 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) (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 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 iterator() { + return new Iterator() { 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(); } diff --git a/src/java/org/apache/commons/collections/buffer/TransformedBuffer.java b/src/java/org/apache/commons/collections/buffer/TransformedBuffer.java index bfd4e1ee5..123e67123 100644 --- a/src/java/org/apache/commons/collections/buffer/TransformedBuffer.java +++ b/src/java/org/apache/commons/collections/buffer/TransformedBuffer.java @@ -35,7 +35,7 @@ import org.apache.commons.collections.collection.TransformedCollection; * * @author Stephen Colebourne */ -public class TransformedBuffer extends TransformedCollection implements Buffer { +public class TransformedBuffer extends TransformedCollection implements Buffer { /** Serialization version */ private static final long serialVersionUID = -7901091318986132033L; @@ -52,8 +52,8 @@ public class TransformedBuffer extends TransformedCollection implements Buffer { * @return a new transformed Buffer * @throws IllegalArgumentException if buffer or transformer is null */ - public static Buffer decorate(Buffer buffer, Transformer transformer) { - return new TransformedBuffer(buffer, transformer); + public static Buffer decorate(Buffer buffer, Transformer transformer) { + return new TransformedBuffer(buffer, transformer); } /** @@ -70,13 +70,14 @@ public class TransformedBuffer extends TransformedCollection implements Buffer { * @throws IllegalArgumentException if buffer or transformer is null * @since Commons Collections 3.3 */ + // TODO: Generics public static Buffer decorateTransform(Buffer buffer, Transformer transformer) { TransformedBuffer decorated = new TransformedBuffer(buffer, transformer); if (transformer != null && buffer != null && buffer.size() > 0) { Object[] values = buffer.toArray(); buffer.clear(); for(int i=0; i buffer, Transformer transformer) { super(buffer, transformer); } @@ -102,16 +103,16 @@ public class TransformedBuffer extends TransformedCollection implements Buffer { * * @return the decorated buffer */ - protected Buffer getBuffer() { - return (Buffer) collection; + protected Buffer getBuffer() { + return (Buffer) collection; } //----------------------------------------------------------------------- - public Object get() { + public E get() { return getBuffer().get(); } - public Object remove() { + public E remove() { return getBuffer().remove(); } diff --git a/src/java/org/apache/commons/collections/buffer/UnboundedFifoBuffer.java b/src/java/org/apache/commons/collections/buffer/UnboundedFifoBuffer.java index 7b49e4957..c4b734053 100644 --- a/src/java/org/apache/commons/collections/buffer/UnboundedFifoBuffer.java +++ b/src/java/org/apache/commons/collections/buffer/UnboundedFifoBuffer.java @@ -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 extends AbstractCollection implements Buffer, Serializable { // invariant: buffer.length > size() // ie.buffer always has at least one empty entry @@ -71,9 +71,11 @@ public class UnboundedFifoBuffer extends AbstractCollection implements Buffer, S private static final long serialVersionUID = -3482960336579541419L; /** The array of objects in the buffer. */ - protected transient Object[] buffer; + protected transient E[] buffer; + /** The current head index. */ protected transient int head; + /** The current tail index. */ protected transient int tail; @@ -92,15 +94,16 @@ public class UnboundedFifoBuffer extends AbstractCollection implements Buffer, S /** * Constructs an UnboundedFifoBuffer with the specified number of elements. * The integer must be a positive integer. - * + * * @param initialSize the initial size of the buffer * @throws IllegalArgumentException if the size is less than 1 */ + @SuppressWarnings("unchecked") public UnboundedFifoBuffer(int initialSize) { if (initialSize <= 0) { throw new IllegalArgumentException("The size must be greater than 0"); } - buffer = new Object[initialSize + 1]; + buffer = (E[]) new Object[initialSize + 1]; head = 0; tail = 0; } @@ -108,7 +111,7 @@ public class UnboundedFifoBuffer extends AbstractCollection implements Buffer, S //----------------------------------------------------------------------- /** * Write the buffer out using a custom routine. - * + * * @param out the output stream * @throws IOException */ @@ -116,25 +119,26 @@ public class UnboundedFifoBuffer extends AbstractCollection implements Buffer, S out.defaultWriteObject(); out.writeInt(size()); out.writeInt(buffer.length); - for (Iterator it = iterator(); it.hasNext();) { + for (Iterator it = iterator(); it.hasNext();) { out.writeObject(it.next()); } } /** * Read the buffer in using a custom routine. - * + * * @param in the input stream * @throws IOException * @throws ClassNotFoundException */ + @SuppressWarnings("unchecked") private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); int size = in.readInt(); int length = in.readInt(); - buffer = new Object[length]; + buffer = (E[]) new Object[length]; for (int i = 0; i < size; i++) { - buffer[i] = in.readObject(); + buffer[i] = (E) in.readObject(); } head = 0; tail = size; @@ -174,14 +178,15 @@ public class UnboundedFifoBuffer extends AbstractCollection implements Buffer, S * @return true, always * @throws NullPointerException if the given element is null */ - public boolean add(final Object obj) { + @SuppressWarnings("unchecked") + public boolean add(final E obj) { if (obj == null) { throw new NullPointerException("Attempted to add null object to buffer"); } if (size() + 1 >= buffer.length) { // copy contents to a new buffer array - Object[] tmp = new Object[((buffer.length - 1) * 2) + 1]; + E[] tmp = (E[]) new Object[((buffer.length - 1) * 2) + 1]; int j = 0; // move head to element zero in the new array for (int i = head; i != tail;) { @@ -207,7 +212,7 @@ public class UnboundedFifoBuffer extends AbstractCollection implements Buffer, S * @return the next object in the buffer * @throws BufferUnderflowException if this buffer is empty */ - public Object get() { + public E get() { if (isEmpty()) { throw new BufferUnderflowException("The buffer is already empty"); } @@ -221,12 +226,12 @@ public class UnboundedFifoBuffer extends AbstractCollection implements Buffer, S * @return the removed object * @throws BufferUnderflowException if this buffer is empty */ - public Object remove() { + public E remove() { if (isEmpty()) { throw new BufferUnderflowException("The buffer is already empty"); } - Object element = buffer[head]; + E element = buffer[head]; if (element != null) { buffer[head] = null; head = increment(head); @@ -236,7 +241,7 @@ public class UnboundedFifoBuffer extends AbstractCollection implements Buffer, S /** * Increments the internal index. - * + * * @param index the index to increment * @return the updated index */ @@ -250,7 +255,7 @@ public class UnboundedFifoBuffer extends AbstractCollection implements Buffer, S /** * Decrements the internal index. - * + * * @param index the index to decrement * @return the updated index */ @@ -267,8 +272,8 @@ public class UnboundedFifoBuffer extends AbstractCollection implements Buffer, S * * @return an iterator over this buffer's elements */ - public Iterator iterator() { - return new Iterator() { + public Iterator iterator() { + return new Iterator() { private int index = head; private int lastReturnedIndex = -1; @@ -278,7 +283,7 @@ public class UnboundedFifoBuffer extends AbstractCollection implements Buffer, S } - public Object next() { + public E next() { if (!hasNext()) { throw new NoSuchElementException(); } diff --git a/src/java/org/apache/commons/collections/collection/AbstractUntypedCollectionDecorator.java b/src/java/org/apache/commons/collections/collection/AbstractUntypedCollectionDecorator.java new file mode 100644 index 000000000..6bc76c66d --- /dev/null +++ b/src/java/org/apache/commons/collections/collection/AbstractUntypedCollectionDecorator.java @@ -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 Collection to provide additional behaviour + * without guaranteeing that the provided Collection type is the + * same as that of the decorated Collection. + *

+ * Each untyped method call made on this Collection is forwarded to the + * decorated Collection. 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 Collection, whereas sub-classing requires a + * new class to be written for each implementation. + *

+ * 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 the type of the elements in the decorated collection + * @param 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 implements Collection, Serializable { + + /** Serialization version */ + private static final long serialVersionUID = -8016691444524268856L; + + /** The collection being decorated */ + protected Collection 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 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[] 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(); + } + +} \ No newline at end of file diff --git a/src/java/org/apache/commons/collections/comparators/BooleanComparator.java b/src/java/org/apache/commons/collections/comparators/BooleanComparator.java index 2f9fb2cf3..cf4bf8216 100644 --- a/src/java/org/apache/commons/collections/comparators/BooleanComparator.java +++ b/src/java/org/apache/commons/collections/comparators/BooleanComparator.java @@ -32,7 +32,7 @@ import java.util.Comparator; * * @author Rodney Waldhoff */ -public final class BooleanComparator implements Comparator, Serializable { +public final class BooleanComparator implements Comparator, 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 Boolean, this method is equivalent to - * {@link #compare(Boolean,Boolean) compare((Boolean)obj1,(Boolean)obj2)}. - * When either argument is not a Boolean, 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 Boolean - */ - public int compare(Object obj1, Object obj2) { - return compare((Boolean)obj1, (Boolean)obj2); - } - /** * Compares two non-null Boolean objects * according to the value of {@link #sortsTrueFirst()}. diff --git a/src/java/org/apache/commons/collections/comparators/ComparableComparator.java b/src/java/org/apache/commons/collections/comparators/ComparableComparator.java index c7e9340e4..ab463c731 100644 --- a/src/java/org/apache/commons/collections/comparators/ComparableComparator.java +++ b/src/java/org/apache/commons/collections/comparators/ComparableComparator.java @@ -40,13 +40,14 @@ import java.util.Comparator; * * @see java.util.Collections#reverseOrder() */ -public class ComparableComparator implements Comparator, Serializable { +public class ComparableComparator> implements Comparator, Serializable { /** Serialization version. */ private static final long serialVersionUID=-291439688585137865L; /** The singleton instance. */ - private static final ComparableComparator instance = new ComparableComparator(); + @SuppressWarnings("unchecked") + public static final ComparableComparator INSTANCE = new ComparableComparator(); //----------------------------------------------------------------------- /** @@ -58,8 +59,9 @@ public class ComparableComparator implements Comparator, Serializable { * * @return the singleton ComparableComparator */ - public static ComparableComparator getInstance() { - return instance; + @SuppressWarnings("unchecked") + public static > ComparableComparator getInstance() { + return (ComparableComparator) INSTANCE; } //----------------------------------------------------------------------- @@ -86,8 +88,8 @@ public class ComparableComparator implements Comparator, Serializable { * @throws ClassCastException when obj1 is not a Comparable, * or when ((Comparable)obj1).compareTo(obj2) does */ - public int compare(Object obj1, Object obj2) { - return ((Comparable)obj1).compareTo(obj2); + public int compare(E obj1, E obj2) { + return obj1.compareTo(obj2); } //----------------------------------------------------------------------- diff --git a/src/java/org/apache/commons/collections/comparators/ComparatorChain.java b/src/java/org/apache/commons/collections/comparators/ComparatorChain.java index 2d0582b06..cbb6c891d 100644 --- a/src/java/org/apache/commons/collections/comparators/ComparatorChain.java +++ b/src/java/org/apache/commons/collections/comparators/ComparatorChain.java @@ -54,13 +54,13 @@ import java.util.List; * @author Morgan Delagrange * @version $Revision$ $Date$ */ -public class ComparatorChain implements Comparator, Serializable { +public class ComparatorChain implements Comparator, 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> 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>(), 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 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 comparator, boolean reverse) { + comparatorChain = new ArrayList>(); 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> list) { + this(list, new BitSet(list.size())); } /** @@ -124,13 +124,13 @@ public class ComparatorChain implements Comparator, Serializable { * If that method returns false, the forward * sort order is used; a return value of true * 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> 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 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 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 < 0 or index >= size() */ - public void setComparator(int index, Comparator comparator) - throws IndexOutOfBoundsException { - setComparator(index,comparator,false); + public void setComparator(int index, Comparator 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 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> comparators = comparatorChain.iterator(); for (int comparatorIndex = 0; comparators.hasNext(); ++comparatorIndex) { - Comparator comparator = (Comparator) comparators.next(); + Comparator 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 true iff that Object is - * is a {@link Comparator} whose ordering is known to be + * Returns true iff that Object is + * is a {@link Comparator} whose ordering is known to be * equivalent to mine. *

* This implementation returns true * iff object.{@link Object#getClass() getClass()} - * equals this.getClass(), and the underlying + * equals this.getClass(), 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; } } diff --git a/src/java/org/apache/commons/collections/comparators/FixedOrderComparator.java b/src/java/org/apache/commons/collections/comparators/FixedOrderComparator.java index 6bad31ffb..05fc8350f 100644 --- a/src/java/org/apache/commons/collections/comparators/FixedOrderComparator.java +++ b/src/java/org/apache/commons/collections/comparators/FixedOrderComparator.java @@ -18,11 +18,10 @@ package org.apache.commons.collections.comparators; import java.util.Comparator; import java.util.HashMap; -import java.util.Iterator; import java.util.List; import java.util.Map; -/** +/** * A Comparator which imposes a specific order on a specific set of Objects. * Objects are presented to the FixedOrderComparator in a specified order and * subsequent calls to {@link #compare(Object, Object) compare} yield that order. @@ -48,55 +47,47 @@ import java.util.Map; * @author Stephen Colebourne * @author Janek Bogucki */ -public class FixedOrderComparator implements Comparator { +public class FixedOrderComparator implements Comparator { - /** - * 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 map = new HashMap(); + /** 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. *

* 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. *

* 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 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. *

* 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); } } diff --git a/src/java/org/apache/commons/collections/comparators/ReverseComparator.java b/src/java/org/apache/commons/collections/comparators/ReverseComparator.java index 5e316f0fd..58410b95a 100644 --- a/src/java/org/apache/commons/collections/comparators/ReverseComparator.java +++ b/src/java/org/apache/commons/collections/comparators/ReverseComparator.java @@ -19,6 +19,8 @@ package org.apache.commons.collections.comparators; import java.io.Serializable; import java.util.Comparator; +import org.apache.commons.collections.ComparatorUtils; + /** * Reverses the order of another comparator by reversing the arguments * to its {@link #compare(Object, Object) compare} method. @@ -30,13 +32,13 @@ import java.util.Comparator; * * @see java.util.Collections#reverseOrder() */ -public class ReverseComparator implements Comparator, Serializable { +public class ReverseComparator implements Comparator, Serializable { /** Serialization version from Collections 2.0. */ private static final long serialVersionUID = 2858887242028539265L; /** The comparator being decorated. */ - private Comparator comparator; + private Comparator comparator; //----------------------------------------------------------------------- /** @@ -60,12 +62,9 @@ public class ReverseComparator implements Comparator, Serializable { * * @param comparator Comparator to reverse */ - public ReverseComparator(Comparator comparator) { - if(comparator != null) { - this.comparator = comparator; - } else { - this.comparator = ComparableComparator.getInstance(); - } + @SuppressWarnings("unchecked") + public ReverseComparator(Comparator comparator) { + this.comparator = comparator == null ? ComparatorUtils.NATURAL_COMPARATOR : comparator; } //----------------------------------------------------------------------- @@ -76,7 +75,7 @@ public class ReverseComparator implements Comparator, Serializable { * @param obj2 the second object to compare * @return negative if obj1 is less, positive if greater, zero if equal */ - public int compare(Object obj1, Object obj2) { + public int compare(E obj1, E obj2) { return comparator.compare(obj2, obj1); } @@ -109,16 +108,17 @@ public class ReverseComparator implements Comparator, Serializable { * @since Commons Collections 3.0 */ public boolean equals(Object object) { - if(this == object) { + if (this == object) { return true; - } else if(null == object) { - return false; - } else if(object.getClass().equals(this.getClass())) { - ReverseComparator thatrc = (ReverseComparator)object; - return comparator.equals(thatrc.comparator); - } else { + } + if (null == object) { return false; } + if (object.getClass().equals(this.getClass())) { + ReverseComparator thatrc = (ReverseComparator) object; + return comparator.equals(thatrc.comparator); + } + return false; } } diff --git a/src/java/org/apache/commons/collections/comparators/TransformingComparator.java b/src/java/org/apache/commons/collections/comparators/TransformingComparator.java index 29fee649a..6b0ee812f 100644 --- a/src/java/org/apache/commons/collections/comparators/TransformingComparator.java +++ b/src/java/org/apache/commons/collections/comparators/TransformingComparator.java @@ -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 implements Comparator { /** The decorated comparator. */ - protected Comparator decorated; + protected Comparator decorated; /** The transformer being used. */ - protected Transformer transformer; + protected Transformer transformer; //----------------------------------------------------------------------- /** @@ -45,8 +46,9 @@ public class TransformingComparator implements Comparator { * * @param transformer what will transform the arguments to compare */ - public TransformingComparator(Transformer transformer) { - this(transformer, new ComparableComparator()); + @SuppressWarnings("unchecked") + public TransformingComparator(Transformer transformer) { + this(transformer, ComparatorUtils.NATURAL_COMPARATOR); } /** @@ -55,7 +57,7 @@ public class TransformingComparator implements Comparator { * @param transformer what will transform the arguments to compare * @param decorated the decorated Comparator */ - public TransformingComparator(Transformer transformer, Comparator decorated) { + public TransformingComparator(Transformer transformer, Comparator 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); } diff --git a/src/java/org/apache/commons/collections/functors/AndPredicate.java b/src/java/org/apache/commons/collections/functors/AndPredicate.java index 890a3e5a9..a30fcd083 100644 --- a/src/java/org/apache/commons/collections/functors/AndPredicate.java +++ b/src/java/org/apache/commons/collections/functors/AndPredicate.java @@ -28,39 +28,39 @@ import org.apache.commons.collections.Predicate; * * @author Stephen Colebourne */ -public final class AndPredicate implements Predicate, PredicateDecorator, Serializable { +public final class AndPredicate implements Predicate, PredicateDecorator, Serializable { /** Serial version UID */ private static final long serialVersionUID = 4189014213763186912L; - + /** The array of predicates to call */ - private final Predicate iPredicate1; + private final Predicate iPredicate1; /** The array of predicates to call */ - private final Predicate iPredicate2; - + private final Predicate 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 and predicate * @throws IllegalArgumentException if either predicate is null */ - public static Predicate getInstance(Predicate predicate1, Predicate predicate2) { + public static Predicate getInstance(Predicate predicate1, Predicate predicate2) { if (predicate1 == null || predicate2 == null) { throw new IllegalArgumentException("Predicate must not be null"); } - return new AndPredicate(predicate1, predicate2); + return new AndPredicate(predicate1, predicate2); } /** * Constructor that performs no validation. * Use getInstance 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 predicate1, Predicate 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[] getPredicates() { return new Predicate[] {iPredicate1, iPredicate2}; } diff --git a/src/java/org/apache/commons/collections/functors/AnyPredicate.java b/src/java/org/apache/commons/collections/functors/AnyPredicate.java index 5ee6cd4b6..430d6d367 100644 --- a/src/java/org/apache/commons/collections/functors/AnyPredicate.java +++ b/src/java/org/apache/commons/collections/functors/AnyPredicate.java @@ -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 implements Predicate, PredicateDecorator, Serializable { /** Serial version UID */ private static final long serialVersionUID = 7429999530934647542L; - + /** The array of predicates to call */ - private final Predicate[] iPredicates; - + private final Predicate[] iPredicates; + /** * Factory to create the predicate. *

@@ -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 Predicate getInstance(Predicate[] predicates) { FunctorUtils.validate(predicates); if (predicates.length == 0) { - return FalsePredicate.INSTANCE; + return FalsePredicate.falsePredicate(); } if (predicates.length == 1) { - return predicates[0]; + return (Predicate) predicates[0]; } - return new AnyPredicate(FunctorUtils.copy(predicates)); + return new AnyPredicate(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 Predicate getInstance(Collection> predicates) { + Predicate[] preds = FunctorUtils.validate(predicates); if (preds.length == 0) { - return FalsePredicate.INSTANCE; + return FalsePredicate.falsePredicate(); } if (preds.length == 1) { - return preds[0]; + return (Predicate) preds[0]; } - return new AnyPredicate(preds); + return new AnyPredicate(preds); } /** * Constructor that performs no validation. * Use getInstance if you want that. - * + * * @param predicates the predicates to check, not cloned, not null */ - public AnyPredicate(Predicate[] predicates) { + public AnyPredicate(Predicate[] 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[] getPredicates() { return iPredicates; } diff --git a/src/java/org/apache/commons/collections/functors/ChainedClosure.java b/src/java/org/apache/commons/collections/functors/ChainedClosure.java index edc0dace2..c5f3736f2 100644 --- a/src/java/org/apache/commons/collections/functors/ChainedClosure.java +++ b/src/java/org/apache/commons/collections/functors/ChainedClosure.java @@ -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 implements Closure, Serializable { /** Serial version UID */ private static final long serialVersionUID = -3520677225766901240L; /** The closures to call in turn */ - private final Closure[] iClosures; + private final Closure[] 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 Closure getInstance(Closure[] closures) { FunctorUtils.validate(closures); if (closures.length == 0) { - return NOPClosure.INSTANCE; + return NOPClosure.getInstance(); } closures = FunctorUtils.copy(closures); - return new ChainedClosure(closures); + return new ChainedClosure(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 Closure getInstance(Collection> closures) { if (closures == null) { throw new IllegalArgumentException("Closure collection must not be null"); } if (closures.size() == 0) { - return NOPClosure.INSTANCE; + return NOPClosure.getInstance(); } // convert to array like this to guarantee iterator() ordering - Closure[] cmds = new Closure[closures.size()]; + Closure[] cmds = new Closure[closures.size()]; int i = 0; - for (Iterator it = closures.iterator(); it.hasNext();) { - cmds[i++] = (Closure) it.next(); + for (Closure closure : closures) { + cmds[i++] = (Closure) closure; } FunctorUtils.validate(cmds); - return new ChainedClosure(cmds); + return new ChainedClosure(cmds); } /** @@ -90,12 +90,13 @@ public class ChainedClosure implements Closure, Serializable { * @return the chained closure * @throws IllegalArgumentException if either closure is null */ - public static Closure getInstance(Closure closure1, Closure closure2) { + @SuppressWarnings("unchecked") + public static Closure getInstance(Closure closure1, Closure 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[] closures = new Closure[] { closure1, closure2 }; + return new ChainedClosure(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[] 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[] getClosures() { return iClosures; } diff --git a/src/java/org/apache/commons/collections/functors/ChainedTransformer.java b/src/java/org/apache/commons/collections/functors/ChainedTransformer.java index 1d742dc0e..35c92965e 100644 --- a/src/java/org/apache/commons/collections/functors/ChainedTransformer.java +++ b/src/java/org/apache/commons/collections/functors/ChainedTransformer.java @@ -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 implements Transformer, Serializable { /** Serial version UID */ private static final long serialVersionUID = 3514945074733160196L; /** The transformers to call in turn */ - private final Transformer[] iTransformers; + private final Transformer[] 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 Transformer getInstance(Transformer[] transformers) { FunctorUtils.validate(transformers); if (transformers.length == 0) { - return NOPTransformer.INSTANCE; + return NOPTransformer.getInstance(); } transformers = FunctorUtils.copy(transformers); - return new ChainedTransformer(transformers); + return new ChainedTransformer(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 Transformer getInstance(Collection> transformers) { if (transformers == null) { throw new IllegalArgumentException("Transformer collection must not be null"); } if (transformers.size() == 0) { - return NOPTransformer.INSTANCE; + return NOPTransformer.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[] cmds = transformers.toArray(new Transformer[transformers.size()]); FunctorUtils.validate(cmds); - return new ChainedTransformer(cmds); + return new ChainedTransformer(cmds); } /** @@ -93,12 +89,13 @@ public class ChainedTransformer implements Transformer, Serializable { * @return the chained transformer * @throws IllegalArgumentException if either transformer is null */ - public static Transformer getInstance(Transformer transformer1, Transformer transformer2) { + @SuppressWarnings("unchecked") + public static Transformer getInstance(Transformer transformer1, Transformer 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[] transformers = new Transformer[] { transformer1, transformer2 }; + return new ChainedTransformer(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[] 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[] getTransformers() { return iTransformers; } diff --git a/src/java/org/apache/commons/collections/functors/CloneTransformer.java b/src/java/org/apache/commons/collections/functors/CloneTransformer.java index 58ae9d1ac..2900f7a6d 100644 --- a/src/java/org/apache/commons/collections/functors/CloneTransformer.java +++ b/src/java/org/apache/commons/collections/functors/CloneTransformer.java @@ -30,13 +30,13 @@ import org.apache.commons.collections.Transformer; * * @author Stephen Colebourne */ -public class CloneTransformer implements Transformer, Serializable { +public class CloneTransformer implements Transformer, Serializable { /** Serial version UID */ private static final long serialVersionUID = -8188742709499652567L; /** Singleton predicate instance */ - public static final Transformer INSTANCE = new CloneTransformer(); + public static final Transformer INSTANCE = new CloneTransformer(); /** * 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 Transformer getInstance() { + return (Transformer) 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; } diff --git a/src/java/org/apache/commons/collections/functors/ClosureTransformer.java b/src/java/org/apache/commons/collections/functors/ClosureTransformer.java index 53c55840e..e54ce639f 100644 --- a/src/java/org/apache/commons/collections/functors/ClosureTransformer.java +++ b/src/java/org/apache/commons/collections/functors/ClosureTransformer.java @@ -30,13 +30,13 @@ import org.apache.commons.collections.Transformer; * * @author Stephen Colebourne */ -public class ClosureTransformer implements Transformer, Serializable { +public class ClosureTransformer implements Transformer, Serializable { /** Serial version UID */ private static final long serialVersionUID = 478466901448617286L; /** The closure to wrap */ - private final Closure iClosure; + private final Closure iClosure; /** * Factory method that performs validation. @@ -45,11 +45,11 @@ public class ClosureTransformer implements Transformer, Serializable { * @return the closure transformer * @throws IllegalArgumentException if the closure is null */ - public static Transformer getInstance(Closure closure) { + public static Transformer getInstance(Closure closure) { if (closure == null) { throw new IllegalArgumentException("Closure must not be null"); } - return new ClosureTransformer(closure); + return new ClosureTransformer(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 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 getClosure() { return iClosure; } diff --git a/src/java/org/apache/commons/collections/functors/ConstantFactory.java b/src/java/org/apache/commons/collections/functors/ConstantFactory.java index 4ecf8b31c..bf4a7ac68 100644 --- a/src/java/org/apache/commons/collections/functors/ConstantFactory.java +++ b/src/java/org/apache/commons/collections/functors/ConstantFactory.java @@ -32,16 +32,16 @@ import org.apache.commons.collections.Factory; * * @author Stephen Colebourne */ -public class ConstantFactory implements Factory, Serializable { +public class ConstantFactory implements Factory, 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 NULL_INSTANCE = new ConstantFactory(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 constant factory. */ - public static Factory getInstance(Object constantToReturn) { + @SuppressWarnings("unchecked") + public static Factory getInstance(T constantToReturn) { if (constantToReturn == null) { - return NULL_INSTANCE; + return (Factory) NULL_INSTANCE; } - return new ConstantFactory(constantToReturn); + return new ConstantFactory(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; } diff --git a/src/java/org/apache/commons/collections/functors/ConstantTransformer.java b/src/java/org/apache/commons/collections/functors/ConstantTransformer.java index 2c96a8b9f..d660b41ac 100644 --- a/src/java/org/apache/commons/collections/functors/ConstantTransformer.java +++ b/src/java/org/apache/commons/collections/functors/ConstantTransformer.java @@ -32,16 +32,27 @@ import org.apache.commons.collections.Transformer; * * @author Stephen Colebourne */ -public class ConstantTransformer implements Transformer, Serializable { +public class ConstantTransformer implements Transformer, 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 NULL_INSTANCE = new ConstantTransformer(null); /** The closures to call in turn */ - private final Object iConstant; + private final O iConstant; + + /** + * Get a typed null instance. + * @param + * @param + * @return Transformer that always returns null. + */ + @SuppressWarnings("unchecked") + public static Transformer getNullInstance() { + return (Transformer) 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 constant factory. */ - public static Transformer getInstance(Object constantToReturn) { + public static Transformer getInstance(O constantToReturn) { if (constantToReturn == null) { - return NULL_INSTANCE; + return getNullInstance(); } - return new ConstantTransformer(constantToReturn); + return new ConstantTransformer(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; + } } diff --git a/src/java/org/apache/commons/collections/functors/ExceptionClosure.java b/src/java/org/apache/commons/collections/functors/ExceptionClosure.java index c44f62939..755e4a7a8 100644 --- a/src/java/org/apache/commons/collections/functors/ExceptionClosure.java +++ b/src/java/org/apache/commons/collections/functors/ExceptionClosure.java @@ -29,14 +29,13 @@ import org.apache.commons.collections.FunctorException; * * @author Stephen Colebourne */ -public final class ExceptionClosure implements Closure, Serializable { +public final class ExceptionClosure implements Closure, Serializable { /** Serial version UID */ private static final long serialVersionUID = 7179106032121985545L; - /** Singleton predicate instance */ - public static final Closure INSTANCE = new ExceptionClosure(); + public static final Closure INSTANCE = new ExceptionClosure(); /** * 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 Closure getInstance() { + return (Closure) 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"); } diff --git a/src/java/org/apache/commons/collections/functors/ExceptionFactory.java b/src/java/org/apache/commons/collections/functors/ExceptionFactory.java index bcb71d9a9..aa8e02260 100644 --- a/src/java/org/apache/commons/collections/functors/ExceptionFactory.java +++ b/src/java/org/apache/commons/collections/functors/ExceptionFactory.java @@ -29,14 +29,13 @@ import org.apache.commons.collections.FunctorException; * * @author Stephen Colebourne */ -public final class ExceptionFactory implements Factory, Serializable { +public final class ExceptionFactory implements Factory, Serializable { /** Serial version UID */ private static final long serialVersionUID = 7179106032121985545L; - /** Singleton predicate instance */ - public static final Factory INSTANCE = new ExceptionFactory(); + public static final Factory INSTANCE = new ExceptionFactory(); /** * 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 Factory getInstance() { + return (Factory) 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"); } diff --git a/src/java/org/apache/commons/collections/functors/ExceptionPredicate.java b/src/java/org/apache/commons/collections/functors/ExceptionPredicate.java index dd2c23560..238e455eb 100644 --- a/src/java/org/apache/commons/collections/functors/ExceptionPredicate.java +++ b/src/java/org/apache/commons/collections/functors/ExceptionPredicate.java @@ -29,22 +29,23 @@ import org.apache.commons.collections.Predicate; * * @author Stephen Colebourne */ -public final class ExceptionPredicate implements Predicate, Serializable { +public final class ExceptionPredicate implements Predicate, Serializable { /** Serial version UID */ private static final long serialVersionUID = 7179106032121985545L; - + /** Singleton predicate instance */ - public static final Predicate INSTANCE = new ExceptionPredicate(); + public static final Predicate INSTANCE = new ExceptionPredicate(); /** * Factory returning the singleton instance. - * + * * @return the singleton instance * @since Commons Collections 3.1 */ - public static Predicate getInstance() { - return INSTANCE; + @SuppressWarnings("unchecked") + public static Predicate getInstance() { + return (Predicate) 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"); } - + } diff --git a/src/java/org/apache/commons/collections/functors/ExceptionTransformer.java b/src/java/org/apache/commons/collections/functors/ExceptionTransformer.java index e7780df2b..b1bcf2cb8 100644 --- a/src/java/org/apache/commons/collections/functors/ExceptionTransformer.java +++ b/src/java/org/apache/commons/collections/functors/ExceptionTransformer.java @@ -29,23 +29,23 @@ import org.apache.commons.collections.Transformer; * * @author Stephen Colebourne */ -public final class ExceptionTransformer implements Transformer, Serializable { +public final class ExceptionTransformer implements Transformer, Serializable { /** Serial version UID */ private static final long serialVersionUID = 7179106032121985545L; - /** Singleton predicate instance */ - public static final Transformer INSTANCE = new ExceptionTransformer(); + public static final Transformer INSTANCE = new ExceptionTransformer(); /** * Factory returning the singleton instance. - * + * * @return the singleton instance * @since Commons Collections 3.1 */ - public static Transformer getInstance() { - return INSTANCE; + @SuppressWarnings("unchecked") + public static Transformer getInstance() { + return (Transformer) 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"); } diff --git a/src/java/org/apache/commons/collections/functors/FactoryTransformer.java b/src/java/org/apache/commons/collections/functors/FactoryTransformer.java index a8978e5cf..0988d850c 100644 --- a/src/java/org/apache/commons/collections/functors/FactoryTransformer.java +++ b/src/java/org/apache/commons/collections/functors/FactoryTransformer.java @@ -29,13 +29,13 @@ import org.apache.commons.collections.Transformer; * * @author Stephen Colebourne */ -public class FactoryTransformer implements Transformer, Serializable { +public class FactoryTransformer implements Transformer, Serializable { /** Serial version UID */ private static final long serialVersionUID = -6817674502475353160L; /** The factory to wrap */ - private final Factory iFactory; + private final Factory iFactory; /** * Factory method that performs validation. @@ -44,11 +44,11 @@ public class FactoryTransformer implements Transformer, Serializable { * @return the factory transformer * @throws IllegalArgumentException if the factory is null */ - public static Transformer getInstance(Factory factory) { + public static Transformer getInstance(Factory factory) { if (factory == null) { throw new IllegalArgumentException("Factory must not be null"); } - return new FactoryTransformer(factory); + return new FactoryTransformer(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 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 getFactory() { return iFactory; } diff --git a/src/java/org/apache/commons/collections/functors/FalsePredicate.java b/src/java/org/apache/commons/collections/functors/FalsePredicate.java index bff3c6b78..c007844f2 100644 --- a/src/java/org/apache/commons/collections/functors/FalsePredicate.java +++ b/src/java/org/apache/commons/collections/functors/FalsePredicate.java @@ -28,22 +28,34 @@ import org.apache.commons.collections.Predicate; * * @author Stephen Colebourne */ -public final class FalsePredicate implements Predicate, Serializable { +public final class FalsePredicate implements Predicate, Serializable { /** Serial version UID */ private static final long serialVersionUID = 7533784454832764388L; - + /** Singleton predicate instance */ - public static final Predicate INSTANCE = new FalsePredicate(); + public static final Predicate INSTANCE = new FalsePredicate(); /** - * 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 Predicate getInstance() { + return FalsePredicate.falsePredicate(); + } + + /** + * Get a typed instance. + * + * @return the singleton instance + * @since Commons Collections 5 + */ + @SuppressWarnings("unchecked") + public static Predicate falsePredicate() { + return (Predicate) 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; } diff --git a/src/java/org/apache/commons/collections/functors/ForClosure.java b/src/java/org/apache/commons/collections/functors/ForClosure.java index 4aa3b2e48..f9abcbacb 100644 --- a/src/java/org/apache/commons/collections/functors/ForClosure.java +++ b/src/java/org/apache/commons/collections/functors/ForClosure.java @@ -28,7 +28,7 @@ import org.apache.commons.collections.Closure; * * @author Stephen Colebourne */ -public class ForClosure implements Closure, Serializable { +public class ForClosure implements Closure, 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 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 for closure */ - public static Closure getInstance(int count, Closure closure) { + @SuppressWarnings("unchecked") + public static Closure getInstance(int count, Closure closure) { if (count <= 0 || closure == null) { - return NOPClosure.INSTANCE; + return NOPClosure.getInstance(); } if (count == 1) { - return closure; + return (Closure) closure; } - return new ForClosure(count, closure); + return new ForClosure(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 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 getClosure() { return iClosure; } diff --git a/src/java/org/apache/commons/collections/functors/IdentityPredicate.java b/src/java/org/apache/commons/collections/functors/IdentityPredicate.java index 90308f443..5768259ab 100644 --- a/src/java/org/apache/commons/collections/functors/IdentityPredicate.java +++ b/src/java/org/apache/commons/collections/functors/IdentityPredicate.java @@ -29,36 +29,35 @@ import org.apache.commons.collections.Predicate; * * @author Stephen Colebourne */ -public final class IdentityPredicate implements Predicate, Serializable { +public final class IdentityPredicate implements Predicate, 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 Predicate getInstance(T object) { if (object == null) { - return NullPredicate.INSTANCE; + return NullPredicate.nullPredicate(); } - return new IdentityPredicate(object); + return new IdentityPredicate(object); } /** * Constructor that performs no validation. * Use getInstance 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; } diff --git a/src/java/org/apache/commons/collections/functors/IfClosure.java b/src/java/org/apache/commons/collections/functors/IfClosure.java index a4b5ee22e..733af1341 100644 --- a/src/java/org/apache/commons/collections/functors/IfClosure.java +++ b/src/java/org/apache/commons/collections/functors/IfClosure.java @@ -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 implements Closure, Serializable { /** Serial version UID */ private static final long serialVersionUID = 3518477308466486130L; /** The test */ - private final Predicate iPredicate; + private final Predicate iPredicate; /** The closure to use if true */ - private final Closure iTrueClosure; + private final Closure iTrueClosure; /** The closure to use if false */ - private final Closure iFalseClosure; + private final Closure 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 Closure getInstance(Predicate predicate, Closure trueClosure) { + return IfClosure.getInstance(predicate, trueClosure, NOPClosure.getInstance()); } /** @@ -68,14 +68,14 @@ public class IfClosure implements Closure, Serializable { * @return the if closure * @throws IllegalArgumentException if any argument is null */ - public static Closure getInstance(Predicate predicate, Closure trueClosure, Closure falseClosure) { + public static Closure getInstance(Predicate predicate, Closure trueClosure, Closure 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(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 predicate, Closure 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 predicate, Closure trueClosure, Closure 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 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 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 getFalseClosure() { return iFalseClosure; } diff --git a/src/java/org/apache/commons/collections/functors/InstanceofPredicate.java b/src/java/org/apache/commons/collections/functors/InstanceofPredicate.java index 2202aac2f..58fbe860e 100644 --- a/src/java/org/apache/commons/collections/functors/InstanceofPredicate.java +++ b/src/java/org/apache/commons/collections/functors/InstanceofPredicate.java @@ -29,22 +29,22 @@ import org.apache.commons.collections.Predicate; * * @author Stephen Colebourne */ -public final class InstanceofPredicate implements Predicate, Serializable { +public final class InstanceofPredicate implements Predicate, 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 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 getInstance 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; } diff --git a/src/java/org/apache/commons/collections/functors/InstantiateTransformer.java b/src/java/org/apache/commons/collections/functors/InstantiateTransformer.java index 991aaa773..ab1d0982b 100644 --- a/src/java/org/apache/commons/collections/functors/InstantiateTransformer.java +++ b/src/java/org/apache/commons/collections/functors/InstantiateTransformer.java @@ -31,27 +31,36 @@ import org.apache.commons.collections.Transformer; * * @author Stephen Colebourne */ -public class InstantiateTransformer implements Transformer, Serializable { +public class InstantiateTransformer implements Transformer, 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, ?> NO_ARG_INSTANCE = new InstantiateTransformer(); /** 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 + * @return Transformer, T> + */ + public static Transformer, T> getInstance() { + return new InstantiateTransformer(); + } + /** * 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 Transformer, 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(); } - return new InstantiateTransformer(paramTypes, args); + paramTypes = (Class[]) paramTypes.clone(); + args = (Object[]) args.clone(); + return new InstantiateTransformer(paramTypes, args); } /** @@ -79,11 +87,11 @@ public class InstantiateTransformer implements Transformer, Serializable { /** * Constructor that performs no validation. * Use getInstance 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 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 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) { diff --git a/src/java/org/apache/commons/collections/functors/InvokerTransformer.java b/src/java/org/apache/commons/collections/functors/InvokerTransformer.java index 2853276ee..b3a2294f3 100644 --- a/src/java/org/apache/commons/collections/functors/InvokerTransformer.java +++ b/src/java/org/apache/commons/collections/functors/InvokerTransformer.java @@ -31,7 +31,7 @@ import org.apache.commons.collections.Transformer; * * @author Stephen Colebourne */ -public class InvokerTransformer implements Transformer, Serializable { +public class InvokerTransformer implements Transformer, 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 Transformer getInstance(String methodName) { if (methodName == null) { throw new IllegalArgumentException("The method to invoke must not be null"); } - return new InvokerTransformer(methodName); + return new InvokerTransformer(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 Transformer 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(methodName); } else { paramTypes = (Class[]) paramTypes.clone(); args = (Object[]) args.clone(); - return new InvokerTransformer(methodName, paramTypes, args); + return new InvokerTransformer(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) { diff --git a/src/java/org/apache/commons/collections/functors/MapTransformer.java b/src/java/org/apache/commons/collections/functors/MapTransformer.java index 2f9567f0e..2bdaa9818 100644 --- a/src/java/org/apache/commons/collections/functors/MapTransformer.java +++ b/src/java/org/apache/commons/collections/functors/MapTransformer.java @@ -30,57 +30,57 @@ import org.apache.commons.collections.Transformer; * * @author Stephen Colebourne */ -public final class MapTransformer implements Transformer, Serializable { +public final class MapTransformer implements Transformer, Serializable { /** Serial version UID */ private static final long serialVersionUID = 862391807045468939L; - + /** The map of data to lookup in */ - private final Map iMap; + private final Map iMap; /** * Factory to create the transformer. *

* 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 Transformer getInstance(Map map) { if (map == null) { - return ConstantTransformer.NULL_INSTANCE; + return ConstantTransformer.getNullInstance(); } - return new MapTransformer(map); + return new MapTransformer(map); } /** * Constructor that performs no validation. * Use getInstance if you want that. - * + * * @param map the map to use for lookup, not cloned */ - private MapTransformer(Map map) { + private MapTransformer(Map map) { super(); iMap = map; } /** * Transforms the input to result by looking it up in a Map. - * + * * @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 getMap() { return iMap; } diff --git a/src/java/org/apache/commons/collections/functors/NOPClosure.java b/src/java/org/apache/commons/collections/functors/NOPClosure.java index a76415a1f..c8443198c 100644 --- a/src/java/org/apache/commons/collections/functors/NOPClosure.java +++ b/src/java/org/apache/commons/collections/functors/NOPClosure.java @@ -28,13 +28,13 @@ import org.apache.commons.collections.Closure; * * @author Stephen Colebourne */ -public class NOPClosure implements Closure, Serializable { +public class NOPClosure implements Closure, Serializable { /** Serial version UID */ private static final long serialVersionUID = 3518477308466486130L; /** Singleton predicate instance */ - public static final Closure INSTANCE = new NOPClosure(); + public static final Closure INSTANCE = new NOPClosure(); /** * 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 Closure getInstance() { + return (Closure) 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); + } } diff --git a/src/java/org/apache/commons/collections/functors/NOPTransformer.java b/src/java/org/apache/commons/collections/functors/NOPTransformer.java index 5869070ba..eedf67e6d 100644 --- a/src/java/org/apache/commons/collections/functors/NOPTransformer.java +++ b/src/java/org/apache/commons/collections/functors/NOPTransformer.java @@ -28,13 +28,13 @@ import org.apache.commons.collections.Transformer; * * @author Stephen Colebourne */ -public class NOPTransformer implements Transformer, Serializable { +public class NOPTransformer implements Transformer, Serializable { /** Serial version UID */ private static final long serialVersionUID = 2133891748318574490L; /** Singleton predicate instance */ - public static final Transformer INSTANCE = new NOPTransformer(); + public static final Transformer INSTANCE = new NOPTransformer(); /** * 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 Transformer getInstance() { + return (Transformer) 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; } diff --git a/src/java/org/apache/commons/collections/functors/NonePredicate.java b/src/java/org/apache/commons/collections/functors/NonePredicate.java index dbaefe65b..11b07a19f 100644 --- a/src/java/org/apache/commons/collections/functors/NonePredicate.java +++ b/src/java/org/apache/commons/collections/functors/NonePredicate.java @@ -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 implements Predicate, PredicateDecorator, Serializable { /** Serial version UID */ private static final long serialVersionUID = 2007613066565892961L; - + /** The array of predicates to call */ - private final Predicate[] iPredicates; - + private final Predicate[] iPredicates; + /** * Factory to create the predicate. *

@@ -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 Predicate getInstance(Predicate[] predicates) { FunctorUtils.validate(predicates); if (predicates.length == 0) { - return TruePredicate.INSTANCE; + return TruePredicate.truePredicate(); } predicates = FunctorUtils.copy(predicates); - return new NonePredicate(predicates); + return new NonePredicate(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 Predicate getInstance(Collection> predicates) { + Predicate[] preds = FunctorUtils.validate(predicates); if (preds.length == 0) { - return TruePredicate.INSTANCE; + return TruePredicate.truePredicate(); } - return new NonePredicate(preds); + return new NonePredicate(preds); } /** * Constructor that performs no validation. * Use getInstance if you want that. - * + * * @param predicates the predicates to check, not cloned, not null */ - public NonePredicate(Predicate[] predicates) { + public NonePredicate(Predicate[] 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[] getPredicates() { return iPredicates; } diff --git a/src/java/org/apache/commons/collections/functors/NotNullPredicate.java b/src/java/org/apache/commons/collections/functors/NotNullPredicate.java index 2f279acf0..545265b3e 100644 --- a/src/java/org/apache/commons/collections/functors/NotNullPredicate.java +++ b/src/java/org/apache/commons/collections/functors/NotNullPredicate.java @@ -28,13 +28,13 @@ import org.apache.commons.collections.Predicate; * * @author Stephen Colebourne */ -public final class NotNullPredicate implements Predicate, Serializable { +public final class NotNullPredicate implements Predicate, Serializable { /** Serial version UID */ private static final long serialVersionUID = 7533784454832764388L; /** Singleton predicate instance */ - public static final Predicate INSTANCE = new NotNullPredicate(); + public static final Predicate INSTANCE = new NotNullPredicate(); /** * 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 Predicate getInstance() { + return (Predicate) 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); } diff --git a/src/java/org/apache/commons/collections/functors/NotPredicate.java b/src/java/org/apache/commons/collections/functors/NotPredicate.java index 437b5d5d6..4f32af35a 100644 --- a/src/java/org/apache/commons/collections/functors/NotPredicate.java +++ b/src/java/org/apache/commons/collections/functors/NotPredicate.java @@ -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 implements Predicate, PredicateDecorator, Serializable { /** Serial version UID */ private static final long serialVersionUID = -2654603322338049674L; /** The predicate to decorate */ - private final Predicate iPredicate; + private final Predicate 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 Predicate getInstance(Predicate predicate) { if (predicate == null) { throw new IllegalArgumentException("Predicate must not be null"); } - return new NotPredicate(predicate); + return new NotPredicate(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 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[] getPredicates() { return new Predicate[] {iPredicate}; } diff --git a/src/java/org/apache/commons/collections/functors/NullIsExceptionPredicate.java b/src/java/org/apache/commons/collections/functors/NullIsExceptionPredicate.java index afbb0cf19..e9635f37e 100644 --- a/src/java/org/apache/commons/collections/functors/NullIsExceptionPredicate.java +++ b/src/java/org/apache/commons/collections/functors/NullIsExceptionPredicate.java @@ -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 implements Predicate, PredicateDecorator, Serializable { /** Serial version UID */ private static final long serialVersionUID = 3243449850504576071L; /** The predicate to decorate */ - private final Predicate iPredicate; + private final Predicate 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 Predicate getInstance(Predicate predicate) { if (predicate == null) { throw new IllegalArgumentException("Predicate must not be null"); } - return new NullIsExceptionPredicate(predicate); + return new NullIsExceptionPredicate(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 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[] getPredicates() { + return new Predicate[] { iPredicate }; } } diff --git a/src/java/org/apache/commons/collections/functors/NullIsFalsePredicate.java b/src/java/org/apache/commons/collections/functors/NullIsFalsePredicate.java index 10c0b2025..217422c17 100644 --- a/src/java/org/apache/commons/collections/functors/NullIsFalsePredicate.java +++ b/src/java/org/apache/commons/collections/functors/NullIsFalsePredicate.java @@ -28,35 +28,35 @@ import org.apache.commons.collections.Predicate; * * @author Stephen Colebourne */ -public final class NullIsFalsePredicate implements Predicate, PredicateDecorator, Serializable { +public final class NullIsFalsePredicate implements Predicate, PredicateDecorator, Serializable { /** Serial version UID */ private static final long serialVersionUID = -2997501534564735525L; - + /** The predicate to decorate */ - private final Predicate iPredicate; - + private final Predicate 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 Predicate getInstance(Predicate predicate) { if (predicate == null) { throw new IllegalArgumentException("Predicate must not be null"); } - return new NullIsFalsePredicate(predicate); + return new NullIsFalsePredicate(predicate); } /** * Constructor that performs no validation. * Use getInstance if you want that. - * + * * @param predicate the predicate to call after the null check */ - public NullIsFalsePredicate(Predicate predicate) { + public NullIsFalsePredicate(Predicate 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[] getPredicates() { + return new Predicate[] { iPredicate }; } } diff --git a/src/java/org/apache/commons/collections/functors/NullIsTruePredicate.java b/src/java/org/apache/commons/collections/functors/NullIsTruePredicate.java index f22b970e4..e7160a37d 100644 --- a/src/java/org/apache/commons/collections/functors/NullIsTruePredicate.java +++ b/src/java/org/apache/commons/collections/functors/NullIsTruePredicate.java @@ -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 implements Predicate, PredicateDecorator, Serializable { /** Serial version UID */ private static final long serialVersionUID = -7625133768987126273L; /** The predicate to decorate */ - private final Predicate iPredicate; + private final Predicate 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 Predicate getInstance(Predicate predicate) { if (predicate == null) { throw new IllegalArgumentException("Predicate must not be null"); } - return new NullIsTruePredicate(predicate); + return new NullIsTruePredicate(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 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[] getPredicates() { + return new Predicate[] { iPredicate }; } } diff --git a/src/java/org/apache/commons/collections/functors/OnePredicate.java b/src/java/org/apache/commons/collections/functors/OnePredicate.java index 345b0b0d3..83fe86411 100644 --- a/src/java/org/apache/commons/collections/functors/OnePredicate.java +++ b/src/java/org/apache/commons/collections/functors/OnePredicate.java @@ -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 implements Predicate, PredicateDecorator, Serializable { /** Serial version UID */ private static final long serialVersionUID = -8125389089924745785L; /** The array of predicates to call */ - private final Predicate[] iPredicates; + private final Predicate[] 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 Predicate getInstance(Predicate[] predicates) { FunctorUtils.validate(predicates); if (predicates.length == 0) { - return FalsePredicate.INSTANCE; + return FalsePredicate.falsePredicate(); } if (predicates.length == 1) { - return predicates[0]; + return (Predicate) predicates[0]; } predicates = FunctorUtils.copy(predicates); - return new OnePredicate(predicates); + return new OnePredicate(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 Predicate getInstance(Collection> predicates) { + Predicate[] preds = FunctorUtils.validate(predicates); + return new OnePredicate(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[] 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[] getPredicates() { return iPredicates; } diff --git a/src/java/org/apache/commons/collections/functors/OrPredicate.java b/src/java/org/apache/commons/collections/functors/OrPredicate.java index 749c753dc..e87edbd5d 100644 --- a/src/java/org/apache/commons/collections/functors/OrPredicate.java +++ b/src/java/org/apache/commons/collections/functors/OrPredicate.java @@ -28,39 +28,39 @@ import org.apache.commons.collections.Predicate; * * @author Stephen Colebourne */ -public final class OrPredicate implements Predicate, PredicateDecorator, Serializable { +public final class OrPredicate implements Predicate, PredicateDecorator, Serializable { /** Serial version UID */ private static final long serialVersionUID = -8791518325735182855L; - + /** The array of predicates to call */ - private final Predicate iPredicate1; + private final Predicate iPredicate1; /** The array of predicates to call */ - private final Predicate iPredicate2; - + private final Predicate 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 and predicate * @throws IllegalArgumentException if either predicate is null */ - public static Predicate getInstance(Predicate predicate1, Predicate predicate2) { + public static Predicate getInstance(Predicate predicate1, Predicate predicate2) { if (predicate1 == null || predicate2 == null) { throw new IllegalArgumentException("Predicate must not be null"); } - return new OrPredicate(predicate1, predicate2); + return new OrPredicate(predicate1, predicate2); } /** * Constructor that performs no validation. * Use getInstance 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 predicate1, Predicate 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[] getPredicates() { return new Predicate[] {iPredicate1, iPredicate2}; } diff --git a/src/java/org/apache/commons/collections/functors/PredicateTransformer.java b/src/java/org/apache/commons/collections/functors/PredicateTransformer.java index 569b730dd..ee747d208 100644 --- a/src/java/org/apache/commons/collections/functors/PredicateTransformer.java +++ b/src/java/org/apache/commons/collections/functors/PredicateTransformer.java @@ -30,13 +30,13 @@ import org.apache.commons.collections.Transformer; * * @author Stephen Colebourne */ -public class PredicateTransformer implements Transformer, Serializable { +public class PredicateTransformer implements Transformer, Serializable { /** Serial version UID */ private static final long serialVersionUID = 5278818408044349346L; /** The closure to wrap */ - private final Predicate iPredicate; + private final Predicate iPredicate; /** * Factory method that performs validation. @@ -45,11 +45,11 @@ public class PredicateTransformer implements Transformer, Serializable { * @return the predicate transformer * @throws IllegalArgumentException if the predicate is null */ - public static Transformer getInstance(Predicate predicate) { + public static Transformer getInstance(Predicate predicate) { if (predicate == null) { throw new IllegalArgumentException("Predicate must not be null"); } - return new PredicateTransformer(predicate); + return new PredicateTransformer(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 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 getPredicate() { return iPredicate; } diff --git a/src/java/org/apache/commons/collections/functors/PrototypeFactory.java b/src/java/org/apache/commons/collections/functors/PrototypeFactory.java index 5242803b2..6063d36a5 100644 --- a/src/java/org/apache/commons/collections/functors/PrototypeFactory.java +++ b/src/java/org/apache/commons/collections/functors/PrototypeFactory.java @@ -55,22 +55,22 @@ public class PrototypeFactory { * @throws IllegalArgumentException if the prototype is null * @throws IllegalArgumentException if the prototype cannot be cloned */ - public static Factory getInstance(Object prototype) { + @SuppressWarnings("unchecked") + public static Factory getInstance(T prototype) { if (prototype == null) { - return ConstantFactory.NULL_INSTANCE; + return ConstantFactory.getInstance(null); } try { Method method = prototype.getClass().getMethod("clone", (Class[]) null); - return new PrototypeCloneFactory(prototype, method); + return new PrototypeCloneFactory(prototype, method); } catch (NoSuchMethodException ex) { try { - prototype.getClass().getConstructor(new Class[] { prototype.getClass()}); - return new InstantiateFactory( - prototype.getClass(), - new Class[] { prototype.getClass()}, + prototype.getClass().getConstructor(new Class[] { prototype.getClass() }); + return new InstantiateFactory( + (Class) prototype.getClass(), + new Class[] { prototype.getClass() }, new Object[] { prototype }); - } catch (NoSuchMethodException ex2) { if (prototype instanceof Serializable) { return new PrototypeSerializationFactory((Serializable) prototype); @@ -93,20 +93,20 @@ public class PrototypeFactory { /** * PrototypeCloneFactory creates objects by copying a prototype using the clone method. */ - static class PrototypeCloneFactory implements Factory, Serializable { + static class PrototypeCloneFactory implements Factory, Serializable { /** The serial version */ private static final long serialVersionUID = 5604271422565175555L; /** The object to clone each time */ - private final Object iPrototype; + private final T iPrototype; /** The method used to clone */ private transient Method iCloneMethod; /** * Constructor to store prototype. */ - private PrototypeCloneFactory(Object prototype, Method method) { + private PrototypeCloneFactory(T prototype, Method method) { super(); iPrototype = prototype; iCloneMethod = method; @@ -118,7 +118,6 @@ public class PrototypeFactory { private void findCloneMethod() { try { iCloneMethod = iPrototype.getClass().getMethod("clone", (Class[]) null); - } catch (NoSuchMethodException ex) { throw new IllegalArgumentException("PrototypeCloneFactory: The clone method must exist and be public "); } @@ -129,15 +128,15 @@ public class PrototypeFactory { * * @return the new object */ - public Object create() { + @SuppressWarnings("unchecked") + public T create() { // needed for post-serialization if (iCloneMethod == null) { findCloneMethod(); } try { - return iCloneMethod.invoke(iPrototype, (Object[])null); - + return (T) iCloneMethod.invoke(iPrototype, (Object[]) null); } catch (IllegalAccessException ex) { throw new FunctorException("PrototypeCloneFactory: Clone method must be public", ex); } catch (InvocationTargetException ex) { @@ -151,18 +150,18 @@ public class PrototypeFactory { /** * PrototypeSerializationFactory creates objects by cloning a prototype using serialization. */ - static class PrototypeSerializationFactory implements Factory, Serializable { + static class PrototypeSerializationFactory implements Factory, Serializable { /** The serial version */ private static final long serialVersionUID = -8704966966139178833L; /** The object to clone via serialization each time */ - private final Serializable iPrototype; + private final T iPrototype; /** * Constructor to store prototype */ - private PrototypeSerializationFactory(Serializable prototype) { + private PrototypeSerializationFactory(T prototype) { super(); iPrototype = prototype; } @@ -172,7 +171,8 @@ public class PrototypeFactory { * * @return the new object */ - public Object create() { + @SuppressWarnings("unchecked") + public T create() { ByteArrayOutputStream baos = new ByteArrayOutputStream(512); ByteArrayInputStream bais = null; try { @@ -181,7 +181,7 @@ public class PrototypeFactory { bais = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream in = new ObjectInputStream(bais); - return in.readObject(); + return (T) in.readObject(); } catch (ClassNotFoundException ex) { throw new FunctorException(ex); diff --git a/src/java/org/apache/commons/collections/functors/StringValueTransformer.java b/src/java/org/apache/commons/collections/functors/StringValueTransformer.java index 6c7ad923b..fb27dfe83 100644 --- a/src/java/org/apache/commons/collections/functors/StringValueTransformer.java +++ b/src/java/org/apache/commons/collections/functors/StringValueTransformer.java @@ -29,13 +29,13 @@ import org.apache.commons.collections.Transformer; * * @author Stephen Colebourne */ -public final class StringValueTransformer implements Transformer, Serializable { +public final class StringValueTransformer implements Transformer, Serializable { /** Serial version UID */ private static final long serialVersionUID = 7511110693171758606L; /** Singleton predicate instance */ - public static final Transformer INSTANCE = new StringValueTransformer(); + public static final Transformer INSTANCE = new StringValueTransformer(); /** * Factory returning the singleton instance. @@ -43,8 +43,9 @@ public final class StringValueTransformer implements Transformer, Serializable { * @return the singleton instance * @since Commons Collections 3.1 */ - public static Transformer getInstance() { - return INSTANCE; + @SuppressWarnings("unchecked") + public static Transformer getInstance() { + return (Transformer) INSTANCE; } /** @@ -60,7 +61,7 @@ public final class StringValueTransformer implements Transformer, Serializable { * @param input the input object to transform * @return the transformed result */ - public Object transform(Object input) { + public String transform(T input) { return String.valueOf(input); } diff --git a/src/java/org/apache/commons/collections/functors/SwitchClosure.java b/src/java/org/apache/commons/collections/functors/SwitchClosure.java index 24c902942..1ee7806d4 100644 --- a/src/java/org/apache/commons/collections/functors/SwitchClosure.java +++ b/src/java/org/apache/commons/collections/functors/SwitchClosure.java @@ -17,7 +17,6 @@ package org.apache.commons.collections.functors; import java.io.Serializable; -import java.util.Iterator; import java.util.Map; import org.apache.commons.collections.Closure; @@ -32,21 +31,21 @@ import org.apache.commons.collections.Predicate; * * @author Stephen Colebourne */ -public class SwitchClosure implements Closure, Serializable { +public class SwitchClosure implements Closure, Serializable { /** Serial version UID */ private static final long serialVersionUID = 3518477308466486130L; /** The tests to consider */ - private final Predicate[] iPredicates; + private final Predicate[] iPredicates; /** The matching closures to call */ - private final Closure[] iClosures; + private final Closure[] iClosures; /** The default closure to call if no tests match */ - private final Closure iDefault; + private final Closure iDefault; /** * Factory method that performs validation and copies the parameter arrays. - * + * * @param predicates array of predicates, cloned, no nulls * @param closures matching array of closures, cloned, no nulls * @param defaultClosure the closure to use if no match, null means nop @@ -54,85 +53,82 @@ public class SwitchClosure implements Closure, Serializable { * @throws IllegalArgumentException if array is null * @throws IllegalArgumentException if any element in the array is null */ - public static Closure getInstance(Predicate[] predicates, Closure[] closures, Closure defaultClosure) { + @SuppressWarnings("unchecked") + public static Closure getInstance(Predicate[] predicates, Closure[] closures, Closure defaultClosure) { FunctorUtils.validate(predicates); FunctorUtils.validate(closures); if (predicates.length != closures.length) { throw new IllegalArgumentException("The predicate and closure arrays must be the same size"); } if (predicates.length == 0) { - return (defaultClosure == null ? NOPClosure.INSTANCE : defaultClosure); + return (Closure) (defaultClosure == null ? NOPClosure.getInstance(): defaultClosure); } predicates = FunctorUtils.copy(predicates); closures = FunctorUtils.copy(closures); - return new SwitchClosure(predicates, closures, defaultClosure); + return new SwitchClosure(predicates, closures, defaultClosure); } /** - * Create a new Closure that calls one of the closures depending - * on the predicates. + * Create a new Closure that calls one of the closures depending + * on the predicates. *

- * The Map consists of Predicate keys and Closure values. A closure + * The Map consists of Predicate keys and Closure values. A closure * is called if its matching predicate returns true. Each predicate is evaluated * until one returns true. If no predicates evaluate to true, the default - * closure is called. The default closure is set in the map with a - * null key. The ordering is that of the iterator() method on the entryset + * closure is called. The default closure is set in the map with a + * null key. The ordering is that of the iterator() method on the entryset * collection of the map. - * + * * @param predicatesAndClosures a map of predicates to closures * @return the switch closure * @throws IllegalArgumentException if the map is null * @throws IllegalArgumentException if any closure in the map is null * @throws ClassCastException if the map elements are of the wrong type */ - public static Closure getInstance(Map predicatesAndClosures) { - Closure[] closures = null; - Predicate[] preds = null; + @SuppressWarnings("unchecked") + public static Closure getInstance(Map, Closure> predicatesAndClosures) { if (predicatesAndClosures == null) { throw new IllegalArgumentException("The predicate and closure map must not be null"); } - if (predicatesAndClosures.size() == 0) { - return NOPClosure.INSTANCE; - } // convert to array like this to guarantee iterator() ordering - Closure defaultClosure = (Closure) predicatesAndClosures.remove(null); + Closure defaultClosure = predicatesAndClosures.remove(null); int size = predicatesAndClosures.size(); if (size == 0) { - return (defaultClosure == null ? NOPClosure.INSTANCE : defaultClosure); + return (Closure) (defaultClosure == null ? NOPClosure.getInstance() : defaultClosure); } - closures = new Closure[size]; - preds = new Predicate[size]; + Closure[] closures = new Closure[size]; + Predicate[] preds = new Predicate[size]; int i = 0; - for (Iterator it = predicatesAndClosures.entrySet().iterator(); it.hasNext();) { - Map.Entry entry = (Map.Entry) it.next(); - preds[i] = (Predicate) entry.getKey(); - closures[i] = (Closure) entry.getValue(); + for (Map.Entry, Closure> entry : predicatesAndClosures.entrySet()) { + preds[i] = entry.getKey(); + closures[i] = entry.getValue(); i++; } - return new SwitchClosure(preds, closures, defaultClosure); + return new SwitchClosure(preds, closures, defaultClosure); } - + /** * Constructor that performs no validation. * Use getInstance if you want that. - * + * * @param predicates array of predicates, not cloned, no nulls * @param closures matching array of closures, not cloned, no nulls * @param defaultClosure the closure to use if no match, null means nop */ - public SwitchClosure(Predicate[] predicates, Closure[] closures, Closure defaultClosure) { + @SuppressWarnings("unchecked") + public SwitchClosure(Predicate[] predicates, Closure[] closures, Closure defaultClosure) { super(); iPredicates = predicates; iClosures = closures; - iDefault = (defaultClosure == null ? NOPClosure.INSTANCE : defaultClosure); + iDefault = (Closure) (defaultClosure == null ? NOPClosure.getInstance() : defaultClosure); } /** * Executes the closure whose matching predicate returns true - * + * * @param input the input object */ - public void execute(Object input) { + public void execute(E input) { for (int i = 0; i < iPredicates.length; i++) { if (iPredicates[i].evaluate(input) == true) { iClosures[i].execute(input); @@ -144,32 +140,32 @@ public class SwitchClosure implements Closure, Serializable { /** * Gets the predicates, do not modify the array. - * + * * @return the predicates * @since Commons Collections 3.1 */ - public Predicate[] getPredicates() { + public Predicate[] getPredicates() { return iPredicates; } /** * Gets the closures, do not modify the array. - * + * * @return the closures * @since Commons Collections 3.1 */ - public Closure[] getClosures() { + public Closure[] getClosures() { return iClosures; } /** * Gets the default closure. - * + * * @return the default closure * @since Commons Collections 3.1 */ - public Closure getDefaultClosure() { + public Closure getDefaultClosure() { return iDefault; } - + } diff --git a/src/java/org/apache/commons/collections/functors/SwitchTransformer.java b/src/java/org/apache/commons/collections/functors/SwitchTransformer.java index e84a357bd..0fc71cc62 100644 --- a/src/java/org/apache/commons/collections/functors/SwitchTransformer.java +++ b/src/java/org/apache/commons/collections/functors/SwitchTransformer.java @@ -17,7 +17,6 @@ package org.apache.commons.collections.functors; import java.io.Serializable; -import java.util.Iterator; import java.util.Map; import org.apache.commons.collections.Predicate; @@ -32,17 +31,17 @@ import org.apache.commons.collections.Transformer; * * @author Stephen Colebourne */ -public class SwitchTransformer implements Transformer, Serializable { +public class SwitchTransformer implements Transformer, Serializable { /** Serial version UID */ private static final long serialVersionUID = -6404460890903469332L; /** The tests to consider */ - private final Predicate[] iPredicates; + private final Predicate[] iPredicates; /** The matching transformers to call */ - private final Transformer[] iTransformers; + private final Transformer[] iTransformers; /** The default transformer to call if no tests match */ - private final Transformer iDefault; + private final Transformer iDefault; /** * Factory method that performs validation and copies the parameter arrays. @@ -54,18 +53,21 @@ public class SwitchTransformer implements Transformer, Serializable { * @throws IllegalArgumentException if array is null * @throws IllegalArgumentException if any element in the array is null */ - public static Transformer getInstance(Predicate[] predicates, Transformer[] transformers, Transformer defaultTransformer) { + @SuppressWarnings("unchecked") + public static Transformer getInstance(Predicate[] predicates, + Transformer[] transformers, + Transformer defaultTransformer) { FunctorUtils.validate(predicates); FunctorUtils.validate(transformers); if (predicates.length != transformers.length) { throw new IllegalArgumentException("The predicate and transformer arrays must be the same size"); } if (predicates.length == 0) { - return (defaultTransformer == null ? ConstantTransformer.NULL_INSTANCE : defaultTransformer); + return (Transformer) (defaultTransformer == null ? ConstantTransformer.getNullInstance() : defaultTransformer); } predicates = FunctorUtils.copy(predicates); transformers = FunctorUtils.copy(transformers); - return new SwitchTransformer(predicates, transformers, defaultTransformer); + return new SwitchTransformer(predicates, transformers, defaultTransformer); } /** @@ -85,31 +87,30 @@ public class SwitchTransformer implements Transformer, Serializable { * @throws IllegalArgumentException if any transformer in the map is null * @throws ClassCastException if the map elements are of the wrong type */ - public static Transformer getInstance(Map predicatesAndTransformers) { - Transformer[] transformers = null; - Predicate[] preds = null; + @SuppressWarnings("unchecked") + public static Transformer getInstance( + Map, ? extends Transformer> predicatesAndTransformers) { if (predicatesAndTransformers == null) { throw new IllegalArgumentException("The predicate and transformer map must not be null"); } if (predicatesAndTransformers.size() == 0) { - return ConstantTransformer.NULL_INSTANCE; + return ConstantTransformer.getNullInstance(); } // convert to array like this to guarantee iterator() ordering - Transformer defaultTransformer = (Transformer) predicatesAndTransformers.remove(null); + Transformer defaultTransformer = predicatesAndTransformers.remove(null); int size = predicatesAndTransformers.size(); if (size == 0) { - return (defaultTransformer == null ? ConstantTransformer.NULL_INSTANCE : defaultTransformer); + return (Transformer) (defaultTransformer == null ? ConstantTransformer.getNullInstance() : defaultTransformer); } - transformers = new Transformer[size]; - preds = new Predicate[size]; + Transformer[] transformers = new Transformer[size]; + Predicate[] preds = new Predicate[size]; int i = 0; - for (Iterator it = predicatesAndTransformers.entrySet().iterator(); it.hasNext();) { - Map.Entry entry = (Map.Entry) it.next(); - preds[i] = (Predicate) entry.getKey(); - transformers[i] = (Transformer) entry.getValue(); + for (Map.Entry, ? extends Transformer> entry : predicatesAndTransformers.entrySet()) { + preds[i] = entry.getKey(); + transformers[i] = entry.getValue(); i++; } - return new SwitchTransformer(preds, transformers, defaultTransformer); + return new SwitchTransformer(preds, transformers, defaultTransformer); } /** @@ -120,11 +121,14 @@ public class SwitchTransformer implements Transformer, Serializable { * @param transformers matching array of transformers, not cloned, no nulls * @param defaultTransformer the transformer to use if no match, null means return null */ - public SwitchTransformer(Predicate[] predicates, Transformer[] transformers, Transformer defaultTransformer) { + @SuppressWarnings("unchecked") + public SwitchTransformer(Predicate[] predicates, + Transformer[] transformers, + Transformer defaultTransformer) { super(); iPredicates = predicates; iTransformers = transformers; - iDefault = (defaultTransformer == null ? ConstantTransformer.NULL_INSTANCE : defaultTransformer); + iDefault = (Transformer) (defaultTransformer == null ? ConstantTransformer.getNullInstance() : defaultTransformer); } /** @@ -134,7 +138,7 @@ public class SwitchTransformer implements Transformer, Serializable { * @param input the input object to transform * @return the transformed result */ - public Object transform(Object input) { + public O transform(I input) { for (int i = 0; i < iPredicates.length; i++) { if (iPredicates[i].evaluate(input) == true) { return iTransformers[i].transform(input); @@ -149,7 +153,7 @@ public class SwitchTransformer implements Transformer, Serializable { * @return the predicates * @since Commons Collections 3.1 */ - public Predicate[] getPredicates() { + public Predicate[] getPredicates() { return iPredicates; } @@ -159,7 +163,7 @@ public class SwitchTransformer implements Transformer, Serializable { * @return the transformers * @since Commons Collections 3.1 */ - public Transformer[] getTransformers() { + public Transformer[] getTransformers() { return iTransformers; } @@ -169,7 +173,7 @@ public class SwitchTransformer implements Transformer, Serializable { * @return the default transformer * @since Commons Collections 3.1 */ - public Transformer getDefaultTransformer() { + public Transformer getDefaultTransformer() { return iDefault; } diff --git a/src/java/org/apache/commons/collections/functors/TransformedPredicate.java b/src/java/org/apache/commons/collections/functors/TransformedPredicate.java index cea28991a..5b5d3ed24 100644 --- a/src/java/org/apache/commons/collections/functors/TransformedPredicate.java +++ b/src/java/org/apache/commons/collections/functors/TransformedPredicate.java @@ -30,74 +30,76 @@ import org.apache.commons.collections.Transformer; * @author Alban Peignier * @author Stephen Colebourne */ -public final class TransformedPredicate implements Predicate, PredicateDecorator, Serializable { +public final class TransformedPredicate implements Predicate, PredicateDecorator, Serializable { /** Serial version UID */ private static final long serialVersionUID = -5596090919668315834L; - + /** The transformer to call */ - private final Transformer iTransformer; + private final Transformer iTransformer; + /** The predicate to call */ - private final Predicate iPredicate; + private final Predicate iPredicate; /** * Factory to create the predicate. - * + * * @param transformer the transformer to call * @param predicate the predicate to call with the result of the transform * @return the predicate * @throws IllegalArgumentException if the transformer or the predicate is null */ - public static Predicate getInstance(Transformer transformer, Predicate predicate) { + public static Predicate getInstance(Transformer transformer, Predicate predicate) { if (transformer == null) { throw new IllegalArgumentException("The transformer to call must not be null"); } if (predicate == null) { throw new IllegalArgumentException("The predicate to call must not be null"); } - return new TransformedPredicate(transformer, predicate); + return new TransformedPredicate(transformer, predicate); } /** * Constructor that performs no validation. * Use getInstance if you want that. - * + * * @param transformer the transformer to use * @param predicate the predicate to decorate */ - public TransformedPredicate(Transformer transformer, Predicate predicate) { + public TransformedPredicate(Transformer transformer, Predicate predicate) { iTransformer = transformer; iPredicate = predicate; } - + /** * Evaluates the predicate returning the result of the decorated predicate * once the input has been transformed - * + * * @param object the input object which will be transformed * @return true if decorated predicate returns true */ - public boolean evaluate(Object object) { - Object result = iTransformer.transform(object); + public boolean evaluate(T object) { + T result = iTransformer.transform(object); return iPredicate.evaluate(result); } /** * Gets the predicate being decorated. - * + * * @return the predicate as the only element in an array * @since Commons Collections 3.1 */ - public Predicate[] getPredicates() { + @SuppressWarnings("unchecked") + public Predicate[] getPredicates() { return new Predicate[] {iPredicate}; } /** * Gets the transformer in use. - * + * * @return the transformer */ - public Transformer getTransformer() { + public Transformer getTransformer() { return iTransformer; } diff --git a/src/java/org/apache/commons/collections/functors/TransformerClosure.java b/src/java/org/apache/commons/collections/functors/TransformerClosure.java index 89a231566..79c41bbde 100644 --- a/src/java/org/apache/commons/collections/functors/TransformerClosure.java +++ b/src/java/org/apache/commons/collections/functors/TransformerClosure.java @@ -30,13 +30,13 @@ import org.apache.commons.collections.Transformer; * * @author Stephen Colebourne */ -public class TransformerClosure implements Closure, Serializable { +public class TransformerClosure implements Closure, Serializable { /** Serial version UID */ private static final long serialVersionUID = -5194992589193388969L; /** The transformer to wrap */ - private final Transformer iTransformer; + private final Transformer iTransformer; /** * Factory method that performs validation. @@ -46,11 +46,11 @@ public class TransformerClosure implements Closure, Serializable { * @param transformer the transformer to call, null means nop * @return the transformer closure */ - public static Closure getInstance(Transformer transformer) { + public static Closure getInstance(Transformer transformer) { if (transformer == null) { - return NOPClosure.INSTANCE; + return NOPClosure.getInstance(); } - return new TransformerClosure(transformer); + return new TransformerClosure(transformer); } /** @@ -59,7 +59,7 @@ public class TransformerClosure implements Closure, Serializable { * * @param transformer the transformer to call, not null */ - public TransformerClosure(Transformer transformer) { + public TransformerClosure(Transformer transformer) { super(); iTransformer = transformer; } @@ -69,7 +69,7 @@ public class TransformerClosure implements Closure, Serializable { * * @param input the input object */ - public void execute(Object input) { + public void execute(E input) { iTransformer.transform(input); } @@ -79,7 +79,7 @@ public class TransformerClosure implements Closure, Serializable { * @return the transformer * @since Commons Collections 3.1 */ - public Transformer getTransformer() { + public Transformer getTransformer() { return iTransformer; } diff --git a/src/java/org/apache/commons/collections/functors/TransformerPredicate.java b/src/java/org/apache/commons/collections/functors/TransformerPredicate.java index a9c784681..396ed421f 100644 --- a/src/java/org/apache/commons/collections/functors/TransformerPredicate.java +++ b/src/java/org/apache/commons/collections/functors/TransformerPredicate.java @@ -30,63 +30,62 @@ import org.apache.commons.collections.Transformer; * * @author Stephen Colebourne */ -public final class TransformerPredicate implements Predicate, Serializable { +public final class TransformerPredicate implements Predicate, Serializable { /** Serial version UID */ private static final long serialVersionUID = -2407966402920578741L; - + /** The transformer to call */ - private final Transformer iTransformer; - + private final Transformer iTransformer; + /** * Factory to create the predicate. - * + * * @param transformer the transformer to decorate * @return the predicate * @throws IllegalArgumentException if the transformer is null */ - public static Predicate getInstance(Transformer transformer) { + public static Predicate getInstance(Transformer transformer) { if (transformer == null) { throw new IllegalArgumentException("The transformer to call must not be null"); } - return new TransformerPredicate(transformer); + return new TransformerPredicate(transformer); } /** * Constructor that performs no validation. * Use getInstance if you want that. - * + * * @param transformer the transformer to decorate */ - public TransformerPredicate(Transformer transformer) { + public TransformerPredicate(Transformer transformer) { super(); iTransformer = transformer; } /** * Evaluates the predicate returning the result of the decorated transformer. - * + * * @param object the input object * @return true if decorated transformer returns Boolean.TRUE * @throws FunctorException if the transformer returns an invalid type */ - public boolean evaluate(Object object) { - Object result = iTransformer.transform(object); - if (result instanceof Boolean == false) { + public boolean evaluate(T object) { + Boolean result = iTransformer.transform(object); + if (result == null) { throw new FunctorException( - "Transformer must return an instanceof Boolean, it was a " - + (result == null ? "null object" : result.getClass().getName())); + "Transformer must return an instanceof Boolean, it was a null object"); } - return ((Boolean) result).booleanValue(); + return result; } /** * Gets the transformer. - * + * * @return the transformer * @since Commons Collections 3.1 */ - public Transformer getTransformer() { + public Transformer getTransformer() { return iTransformer; } diff --git a/src/java/org/apache/commons/collections/functors/UniquePredicate.java b/src/java/org/apache/commons/collections/functors/UniquePredicate.java index bda01b272..22f189f3e 100644 --- a/src/java/org/apache/commons/collections/functors/UniquePredicate.java +++ b/src/java/org/apache/commons/collections/functors/UniquePredicate.java @@ -31,22 +31,22 @@ import org.apache.commons.collections.Predicate; * * @author Stephen Colebourne */ -public final class UniquePredicate implements Predicate, Serializable { +public final class UniquePredicate implements Predicate, Serializable { /** Serial version UID */ private static final long serialVersionUID = -3319417438027438040L; - + /** The set of previously seen objects */ - private final Set iSet = new HashSet(); - + private final Set iSet = new HashSet(); + /** * Factory to create the predicate. - * + * * @return the predicate * @throws IllegalArgumentException if the predicate is null */ - public static Predicate getInstance() { - return new UniquePredicate(); + public static Predicate getInstance() { + return new UniquePredicate(); } /** @@ -60,11 +60,11 @@ public final class UniquePredicate implements Predicate, Serializable { /** * Evaluates the predicate returning true if the input object hasn't been * received yet. - * + * * @param object the input object * @return true if this is the first time the object is seen */ - public boolean evaluate(Object object) { + public boolean evaluate(T object) { return iSet.add(object); } diff --git a/src/java/org/apache/commons/collections/functors/WhileClosure.java b/src/java/org/apache/commons/collections/functors/WhileClosure.java index 21fc038e8..a1bf7cb9d 100644 --- a/src/java/org/apache/commons/collections/functors/WhileClosure.java +++ b/src/java/org/apache/commons/collections/functors/WhileClosure.java @@ -30,15 +30,15 @@ import org.apache.commons.collections.Predicate; * * @author Stephen Colebourne */ -public class WhileClosure implements Closure, Serializable { +public class WhileClosure implements Closure, Serializable { /** Serial version UID */ private static final long serialVersionUID = -3110538116913760108L; /** The test condition */ - private final Predicate iPredicate; + private final Predicate iPredicate; /** The closure to call */ - private final Closure iClosure; + private final Closure iClosure; /** The flag, true is a do loop, false is a while */ private final boolean iDoLoop; @@ -51,14 +51,14 @@ public class WhileClosure implements Closure, Serializable { * @return the while closure * @throws IllegalArgumentException if the predicate or closure is null */ - public static Closure getInstance(Predicate predicate, Closure closure, boolean doLoop) { + public static Closure getInstance(Predicate predicate, Closure closure, boolean doLoop) { if (predicate == null) { throw new IllegalArgumentException("Predicate must not be null"); } if (closure == null) { throw new IllegalArgumentException("Closure must not be null"); } - return new WhileClosure(predicate, closure, doLoop); + return new WhileClosure(predicate, closure, doLoop); } /** @@ -69,7 +69,7 @@ public class WhileClosure implements Closure, Serializable { * @param closure the closure the execute, not null * @param doLoop true to act as a do-while loop, always executing the closure once */ - public WhileClosure(Predicate predicate, Closure closure, boolean doLoop) { + public WhileClosure(Predicate predicate, Closure closure, boolean doLoop) { super(); iPredicate = predicate; iClosure = closure; @@ -81,7 +81,7 @@ public class WhileClosure implements Closure, Serializable { * * @param input the input object */ - public void execute(Object input) { + public void execute(E input) { if (iDoLoop) { iClosure.execute(input); } @@ -96,7 +96,7 @@ public class WhileClosure implements Closure, Serializable { * @return the predicate * @since Commons Collections 3.1 */ - public Predicate getPredicate() { + public Predicate getPredicate() { return iPredicate; } @@ -106,7 +106,7 @@ public class WhileClosure implements Closure, Serializable { * @return the closure * @since Commons Collections 3.1 */ - public Closure getClosure() { + public Closure getClosure() { return iClosure; } diff --git a/src/java/org/apache/commons/collections/iterators/AbstractEmptyIterator.java b/src/java/org/apache/commons/collections/iterators/AbstractEmptyIterator.java index 61075b76e..0f21ecdf1 100644 --- a/src/java/org/apache/commons/collections/iterators/AbstractEmptyIterator.java +++ b/src/java/org/apache/commons/collections/iterators/AbstractEmptyIterator.java @@ -26,7 +26,7 @@ import java.util.NoSuchElementException; * * @author Stephen Colebourne */ -abstract class AbstractEmptyIterator { +abstract class AbstractEmptyIterator { /** * Constructor. @@ -39,7 +39,7 @@ abstract class AbstractEmptyIterator { return false; } - public Object next() { + public E next() { throw new NoSuchElementException("Iterator contains no elements"); } @@ -47,7 +47,7 @@ abstract class AbstractEmptyIterator { return false; } - public Object previous() { + public E previous() { throw new NoSuchElementException("Iterator contains no elements"); } @@ -59,11 +59,11 @@ abstract class AbstractEmptyIterator { return -1; } - public void add(Object obj) { + public void add(E obj) { throw new UnsupportedOperationException("add() not supported for empty Iterator"); } - public void set(Object obj) { + public void set(E obj) { throw new IllegalStateException("Iterator contains no elements"); } @@ -71,18 +71,6 @@ abstract class AbstractEmptyIterator { throw new IllegalStateException("Iterator contains no elements"); } - public Object getKey() { - throw new IllegalStateException("Iterator contains no elements"); - } - - public Object getValue() { - throw new IllegalStateException("Iterator contains no elements"); - } - - public Object setValue(Object value) { - throw new IllegalStateException("Iterator contains no elements"); - } - public void reset() { // do nothing } diff --git a/src/java/org/apache/commons/collections/iterators/AbstractIteratorDecorator.java b/src/java/org/apache/commons/collections/iterators/AbstractIteratorDecorator.java index 2cc547cdc..9e0d35921 100644 --- a/src/java/org/apache/commons/collections/iterators/AbstractIteratorDecorator.java +++ b/src/java/org/apache/commons/collections/iterators/AbstractIteratorDecorator.java @@ -18,7 +18,7 @@ package org.apache.commons.collections.iterators; import java.util.Iterator; -/** +/** * Provides basic behaviour for decorating an iterator with extra functionality. *

* All methods are forwarded to the decorated iterator. @@ -29,10 +29,7 @@ import java.util.Iterator; * @author James Strachan * @author Stephen Colebourne */ -public class AbstractIteratorDecorator implements Iterator { - - /** The iterator being decorated */ - protected final Iterator iterator; +public abstract class AbstractIteratorDecorator extends AbstractUntypedIteratorDecorator { //----------------------------------------------------------------------- /** @@ -41,34 +38,12 @@ public class AbstractIteratorDecorator implements Iterator { * @param iterator the iterator to decorate, must not be null * @throws IllegalArgumentException if the collection is null */ - public AbstractIteratorDecorator(Iterator iterator) { - super(); - if (iterator == null) { - throw new IllegalArgumentException("Iterator must not be null"); - } - this.iterator = iterator; + protected AbstractIteratorDecorator(Iterator iterator) { + super(iterator); } - /** - * Gets the iterator being decorated. - * - * @return the decorated iterator - */ - protected Iterator getIterator() { - return iterator; - } - - //----------------------------------------------------------------------- - public boolean hasNext() { - return iterator.hasNext(); - } - - public Object next() { - return iterator.next(); - } - - public void remove() { - iterator.remove(); + public E next() { + return getIterator().next(); } } diff --git a/src/java/org/apache/commons/collections/iterators/AbstractMapIteratorDecorator.java b/src/java/org/apache/commons/collections/iterators/AbstractMapIteratorDecorator.java index bbcf01d52..76b7c6d15 100644 --- a/src/java/org/apache/commons/collections/iterators/AbstractMapIteratorDecorator.java +++ b/src/java/org/apache/commons/collections/iterators/AbstractMapIteratorDecorator.java @@ -28,10 +28,10 @@ import org.apache.commons.collections.MapIterator; * * @author Stephen Colebourne */ -public class AbstractMapIteratorDecorator implements MapIterator { +public class AbstractMapIteratorDecorator implements MapIterator { /** The iterator being decorated */ - protected final MapIterator iterator; + protected final MapIterator iterator; //----------------------------------------------------------------------- /** @@ -40,7 +40,7 @@ public class AbstractMapIteratorDecorator implements MapIterator { * @param iterator the iterator to decorate, must not be null * @throws IllegalArgumentException if the collection is null */ - public AbstractMapIteratorDecorator(MapIterator iterator) { + public AbstractMapIteratorDecorator(MapIterator iterator) { super(); if (iterator == null) { throw new IllegalArgumentException("MapIterator must not be null"); @@ -53,7 +53,7 @@ public class AbstractMapIteratorDecorator implements MapIterator { * * @return the decorated iterator */ - protected MapIterator getMapIterator() { + protected MapIterator getMapIterator() { return iterator; } @@ -62,7 +62,7 @@ public class AbstractMapIteratorDecorator implements MapIterator { return iterator.hasNext(); } - public Object next() { + public K next() { return iterator.next(); } @@ -70,15 +70,15 @@ public class AbstractMapIteratorDecorator implements MapIterator { iterator.remove(); } - public Object getKey() { + public K getKey() { return iterator.getKey(); } - public Object getValue() { + public V getValue() { return iterator.getValue(); } - public Object setValue(Object obj) { + public V setValue(V obj) { return iterator.setValue(obj); } diff --git a/src/java/org/apache/commons/collections/iterators/AbstractOrderedMapIteratorDecorator.java b/src/java/org/apache/commons/collections/iterators/AbstractOrderedMapIteratorDecorator.java index ff0924523..c1be869fc 100644 --- a/src/java/org/apache/commons/collections/iterators/AbstractOrderedMapIteratorDecorator.java +++ b/src/java/org/apache/commons/collections/iterators/AbstractOrderedMapIteratorDecorator.java @@ -28,10 +28,10 @@ import org.apache.commons.collections.OrderedMapIterator; * * @author Stephen Colebourne */ -public class AbstractOrderedMapIteratorDecorator implements OrderedMapIterator { +public class AbstractOrderedMapIteratorDecorator implements OrderedMapIterator { /** The iterator being decorated */ - protected final OrderedMapIterator iterator; + protected final OrderedMapIterator iterator; //----------------------------------------------------------------------- /** @@ -40,7 +40,7 @@ public class AbstractOrderedMapIteratorDecorator implements OrderedMapIterator { * @param iterator the iterator to decorate, must not be null * @throws IllegalArgumentException if the collection is null */ - public AbstractOrderedMapIteratorDecorator(OrderedMapIterator iterator) { + public AbstractOrderedMapIteratorDecorator(OrderedMapIterator iterator) { super(); if (iterator == null) { throw new IllegalArgumentException("OrderedMapIterator must not be null"); @@ -53,7 +53,7 @@ public class AbstractOrderedMapIteratorDecorator implements OrderedMapIterator { * * @return the decorated iterator */ - protected OrderedMapIterator getOrderedMapIterator() { + protected OrderedMapIterator getOrderedMapIterator() { return iterator; } @@ -62,7 +62,7 @@ public class AbstractOrderedMapIteratorDecorator implements OrderedMapIterator { return iterator.hasNext(); } - public Object next() { + public K next() { return iterator.next(); } @@ -70,7 +70,7 @@ public class AbstractOrderedMapIteratorDecorator implements OrderedMapIterator { return iterator.hasPrevious(); } - public Object previous() { + public K previous() { return iterator.previous(); } @@ -78,15 +78,15 @@ public class AbstractOrderedMapIteratorDecorator implements OrderedMapIterator { iterator.remove(); } - public Object getKey() { + public K getKey() { return iterator.getKey(); } - public Object getValue() { + public V getValue() { return iterator.getValue(); } - public Object setValue(Object obj) { + public V setValue(V obj) { return iterator.setValue(obj); } diff --git a/src/java/org/apache/commons/collections/iterators/CollatingIterator.java b/src/java/org/apache/commons/collections/iterators/CollatingIterator.java index 4b9fdc140..eca54c2e0 100644 --- a/src/java/org/apache/commons/collections/iterators/CollatingIterator.java +++ b/src/java/org/apache/commons/collections/iterators/CollatingIterator.java @@ -27,12 +27,12 @@ import java.util.NoSuchElementException; import org.apache.commons.collections.list.UnmodifiableList; /** - * Provides an ordered iteration over the elements contained in - * a collection of ordered Iterators. + * Provides an ordered iteration over the elements contained in a collection of + * ordered Iterators. *

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

- * This class provides an implementation of an empty list iterator. - * This class provides for binary compatability between Commons Collections - * 2.1.1 and 3.1 due to issues with IteratorUtils. + * This class provides an implementation of an empty list iterator. This class + * provides for binary compatability between Commons Collections 2.1.1 and 3.1 + * due to issues with IteratorUtils. * * @since Commons Collections 2.1.1 and 3.1 * @version $Revision$ $Date$ * * @author Stephen Colebourne */ -public class EmptyListIterator extends AbstractEmptyIterator implements ResettableListIterator { +public class EmptyListIterator extends AbstractEmptyIterator implements + ResettableListIterator { /** * Singleton instance of the iterator. * @since Commons Collections 3.1 */ - public static final ResettableListIterator RESETTABLE_INSTANCE = new EmptyListIterator(); + public static final ResettableListIterator RESETTABLE_INSTANCE = new EmptyListIterator(); + /** * Singleton instance of the iterator. * @since Commons Collections 2.1.1 and 3.1 */ - public static final ListIterator INSTANCE = RESETTABLE_INSTANCE; + public static final ListIterator INSTANCE = RESETTABLE_INSTANCE; + + /** + * Get a typed instance of the iterator. + * @param + * @return {@link ResettableListIterator} + */ + @SuppressWarnings("unchecked") + public static ResettableListIterator getResettableInstance() { + return (ResettableListIterator) RESETTABLE_INSTANCE; + } + + /** + * Get a typed instance of the iterator. + * @param + * @return {@link ListIterator} + */ + @SuppressWarnings("unchecked") + public static ListIterator getInstance() { + return (ListIterator) INSTANCE; + } /** * Constructor. diff --git a/src/java/org/apache/commons/collections/iterators/EmptyMapIterator.java b/src/java/org/apache/commons/collections/iterators/EmptyMapIterator.java index 0e0d98235..507d5dc3b 100644 --- a/src/java/org/apache/commons/collections/iterators/EmptyMapIterator.java +++ b/src/java/org/apache/commons/collections/iterators/EmptyMapIterator.java @@ -27,13 +27,25 @@ import org.apache.commons.collections.ResettableIterator; * * @author Stephen Colebourne */ -public class EmptyMapIterator extends AbstractEmptyIterator implements MapIterator, ResettableIterator { +public class EmptyMapIterator extends AbstractEmptyMapIterator implements + MapIterator, ResettableIterator { /** * Singleton instance of the iterator. * @since Commons Collections 3.1 */ - public static final MapIterator INSTANCE = new EmptyMapIterator(); + public static final MapIterator INSTANCE = new EmptyMapIterator(); + + /** + * Get a typed instance of the iterator. + * @param + * @param + * @return {@link MapIterator} + */ + @SuppressWarnings("unchecked") + public static MapIterator getInstance() { + return (MapIterator) INSTANCE; + } /** * Constructor. diff --git a/src/java/org/apache/commons/collections/iterators/EmptyOrderedIterator.java b/src/java/org/apache/commons/collections/iterators/EmptyOrderedIterator.java index 3b642674c..35406f811 100644 --- a/src/java/org/apache/commons/collections/iterators/EmptyOrderedIterator.java +++ b/src/java/org/apache/commons/collections/iterators/EmptyOrderedIterator.java @@ -27,13 +27,23 @@ import org.apache.commons.collections.ResettableIterator; * * @author Stephen Colebourne */ -public class EmptyOrderedIterator extends AbstractEmptyIterator implements OrderedIterator, ResettableIterator { +public class EmptyOrderedIterator extends AbstractEmptyIterator implements OrderedIterator, ResettableIterator { /** * Singleton instance of the iterator. * @since Commons Collections 3.1 */ - public static final OrderedIterator INSTANCE = new EmptyOrderedIterator(); + public static final OrderedIterator INSTANCE = new EmptyOrderedIterator(); + + /** + * Typed instance of the iterator. + * @param + * @return OrderedIterator + */ + @SuppressWarnings("unchecked") + public static OrderedIterator getInstance() { + return (OrderedIterator) INSTANCE; + } /** * Constructor. diff --git a/src/java/org/apache/commons/collections/iterators/EmptyOrderedMapIterator.java b/src/java/org/apache/commons/collections/iterators/EmptyOrderedMapIterator.java index 3db3daa5b..0f029dc5e 100644 --- a/src/java/org/apache/commons/collections/iterators/EmptyOrderedMapIterator.java +++ b/src/java/org/apache/commons/collections/iterators/EmptyOrderedMapIterator.java @@ -27,13 +27,25 @@ import org.apache.commons.collections.ResettableIterator; * * @author Stephen Colebourne */ -public class EmptyOrderedMapIterator extends AbstractEmptyIterator implements OrderedMapIterator, ResettableIterator { +public class EmptyOrderedMapIterator extends AbstractEmptyMapIterator implements + OrderedMapIterator, ResettableIterator { /** * Singleton instance of the iterator. * @since Commons Collections 3.1 */ - public static final OrderedMapIterator INSTANCE = new EmptyOrderedMapIterator(); + public static final OrderedMapIterator INSTANCE = new EmptyOrderedMapIterator(); + + /** + * Get a typed instance of the iterator. + * @param + * @param + * @return {@link OrderedMapIterator} + */ + @SuppressWarnings("unchecked") + public static OrderedMapIterator getInstance() { + return (OrderedMapIterator) INSTANCE; + } /** * Constructor. diff --git a/src/java/org/apache/commons/collections/iterators/EntrySetMapIterator.java b/src/java/org/apache/commons/collections/iterators/EntrySetMapIterator.java index 8ff9a10d6..da5ba733d 100644 --- a/src/java/org/apache/commons/collections/iterators/EntrySetMapIterator.java +++ b/src/java/org/apache/commons/collections/iterators/EntrySetMapIterator.java @@ -39,11 +39,11 @@ import org.apache.commons.collections.ResettableIterator; * * @author Stephen Colebourne */ -public class EntrySetMapIterator implements MapIterator, ResettableIterator { +public class EntrySetMapIterator implements MapIterator, ResettableIterator { - private final Map map; - private Iterator iterator; - private Map.Entry last; + private final Map map; + private Iterator> iterator; + private Map.Entry last; private boolean canRemove = false; /** @@ -51,7 +51,7 @@ public class EntrySetMapIterator implements MapIterator, ResettableIterator { * * @param map the map to iterate over */ - public EntrySetMapIterator(Map map) { + public EntrySetMapIterator(Map map) { super(); this.map = map; this.iterator = map.entrySet().iterator(); @@ -73,8 +73,8 @@ public class EntrySetMapIterator implements MapIterator, ResettableIterator { * @return the next key in the iteration * @throws java.util.NoSuchElementException if the iteration is finished */ - public Object next() { - last = (Map.Entry) iterator.next(); + public K next() { + last = (Map.Entry) iterator.next(); canRemove = true; return last.getKey(); } @@ -107,7 +107,7 @@ public class EntrySetMapIterator implements MapIterator, ResettableIterator { * @return the current key * @throws IllegalStateException if next() has not yet been called */ - public Object getKey() { + public K getKey() { if (last == null) { throw new IllegalStateException("Iterator getKey() can only be called after next() and before remove()"); } @@ -121,7 +121,7 @@ public class EntrySetMapIterator implements MapIterator, ResettableIterator { * @return the current value * @throws IllegalStateException if next() has not yet been called */ - public Object getValue() { + public V getValue() { if (last == null) { throw new IllegalStateException("Iterator getValue() can only be called after next() and before remove()"); } @@ -138,7 +138,7 @@ public class EntrySetMapIterator implements MapIterator, ResettableIterator { * @throws IllegalStateException if remove() has been called since the * last call to next() */ - public Object setValue(Object value) { + public V setValue(V value) { if (last == null) { throw new IllegalStateException("Iterator setValue() can only be called after next() and before remove()"); } @@ -163,9 +163,8 @@ public class EntrySetMapIterator implements MapIterator, ResettableIterator { public String toString() { if (last != null) { return "MapIterator[" + getKey() + "=" + getValue() + "]"; - } else { - return "MapIterator[]"; } + return "MapIterator[]"; } } diff --git a/src/java/org/apache/commons/collections/iterators/EnumerationIterator.java b/src/java/org/apache/commons/collections/iterators/EnumerationIterator.java index 262285cc5..f8ca1dde8 100644 --- a/src/java/org/apache/commons/collections/iterators/EnumerationIterator.java +++ b/src/java/org/apache/commons/collections/iterators/EnumerationIterator.java @@ -30,14 +30,14 @@ import java.util.Iterator; * @author James Strachan * @author Daniel Rall */ -public class EnumerationIterator implements Iterator { +public class EnumerationIterator implements Iterator { /** The collection to remove elements from */ - private Collection collection; + private Collection collection; /** The enumeration being converted */ - private Enumeration enumeration; + private Enumeration enumeration; /** The last object retrieved */ - private Object last; + private E last; // Constructors //----------------------------------------------------------------------- @@ -55,7 +55,7 @@ public class EnumerationIterator implements Iterator { * * @param enumeration the enumeration to use */ - public EnumerationIterator(final Enumeration enumeration) { + public EnumerationIterator(final Enumeration enumeration) { this(enumeration, null); } @@ -64,9 +64,9 @@ public class EnumerationIterator implements Iterator { * elements from the specified collection. * * @param enumeration the enumeration to use - * @param collection the collection to remove elements form + * @param collection the collection to remove elements from */ - public EnumerationIterator(final Enumeration enumeration, final Collection collection) { + public EnumerationIterator(final Enumeration enumeration, final Collection collection) { super(); this.enumeration = enumeration; this.collection = collection; @@ -91,7 +91,7 @@ public class EnumerationIterator implements Iterator { * @return the next object from the enumeration * @throws NullPointerException if the enumeration is null */ - public Object next() { + public E next() { last = enumeration.nextElement(); return last; } @@ -125,7 +125,7 @@ public class EnumerationIterator implements Iterator { * * @return the underlying enumeration */ - public Enumeration getEnumeration() { + public Enumeration getEnumeration() { return enumeration; } @@ -134,7 +134,7 @@ public class EnumerationIterator implements Iterator { * * @param enumeration the new underlying enumeration */ - public void setEnumeration(final Enumeration enumeration) { + public void setEnumeration(final Enumeration enumeration) { this.enumeration = enumeration; } diff --git a/src/java/org/apache/commons/collections/iterators/FilterIterator.java b/src/java/org/apache/commons/collections/iterators/FilterIterator.java index b32ff0518..22de8e38c 100644 --- a/src/java/org/apache/commons/collections/iterators/FilterIterator.java +++ b/src/java/org/apache/commons/collections/iterators/FilterIterator.java @@ -35,14 +35,14 @@ import org.apache.commons.collections.Predicate; * @author Ralph Wagner * @author Stephen Colebourne */ -public class FilterIterator implements Iterator { +public class FilterIterator implements Iterator { /** The iterator being used */ - private Iterator iterator; + private Iterator iterator; /** The predicate being used */ - private Predicate predicate; + private Predicate predicate; /** The next object in the iteration */ - private Object nextObject; + private E nextObject; /** Whether the next object has been calculated yet */ private boolean nextObjectSet = false; @@ -61,7 +61,7 @@ public class FilterIterator implements Iterator { * * @param iterator the iterator to use */ - public FilterIterator(Iterator iterator) { + public FilterIterator(Iterator iterator) { super(); this.iterator = iterator; } @@ -73,7 +73,7 @@ public class FilterIterator implements Iterator { * @param iterator the iterator to use * @param predicate the predicate to use */ - public FilterIterator(Iterator iterator, Predicate predicate) { + public FilterIterator(Iterator iterator, Predicate predicate) { super(); this.iterator = iterator; this.predicate = predicate; @@ -88,11 +88,7 @@ public class FilterIterator implements Iterator { * @throws NullPointerException if either the iterator or predicate are null */ public boolean hasNext() { - if (nextObjectSet) { - return true; - } else { - return setNextObject(); - } + return nextObjectSet || setNextObject(); } /** @@ -103,7 +99,7 @@ public class FilterIterator implements Iterator { * @throws NoSuchElementException if there are no more elements that * match the predicate */ - public Object next() { + public E next() { if (!nextObjectSet) { if (!setNextObject()) { throw new NoSuchElementException(); @@ -137,7 +133,7 @@ public class FilterIterator implements Iterator { * * @return the iterator */ - public Iterator getIterator() { + public Iterator getIterator() { return iterator; } @@ -147,7 +143,7 @@ public class FilterIterator implements Iterator { * * @param iterator the iterator to use */ - public void setIterator(Iterator iterator) { + public void setIterator(Iterator iterator) { this.iterator = iterator; nextObject = null; nextObjectSet = false; @@ -159,7 +155,7 @@ public class FilterIterator implements Iterator { * * @return the predicate */ - public Predicate getPredicate() { + public Predicate getPredicate() { return predicate; } @@ -168,7 +164,7 @@ public class FilterIterator implements Iterator { * * @param predicate the predicate to use */ - public void setPredicate(Predicate predicate) { + public void setPredicate(Predicate predicate) { this.predicate = predicate; nextObject = null; nextObjectSet = false; @@ -181,7 +177,7 @@ public class FilterIterator implements Iterator { */ private boolean setNextObject() { while (iterator.hasNext()) { - Object object = iterator.next(); + E object = iterator.next(); if (predicate.evaluate(object)) { nextObject = object; nextObjectSet = true; diff --git a/src/java/org/apache/commons/collections/iterators/FilterListIterator.java b/src/java/org/apache/commons/collections/iterators/FilterListIterator.java index 4faffb655..7e9b4bf80 100644 --- a/src/java/org/apache/commons/collections/iterators/FilterListIterator.java +++ b/src/java/org/apache/commons/collections/iterators/FilterListIterator.java @@ -32,19 +32,19 @@ import org.apache.commons.collections.Predicate; * * @author Rodney Waldhoff */ -public class FilterListIterator implements ListIterator { +public class FilterListIterator implements ListIterator { /** The iterator being used */ - private ListIterator iterator; + private ListIterator iterator; /** The predicate being used */ - private Predicate predicate; + private Predicate predicate; /** * The value of the next (matching) object, when * {@link #nextObjectSet} is true. */ - private Object nextObject; + private E nextObject; /** * Whether or not the {@link #nextObject} has been set @@ -56,7 +56,7 @@ public class FilterListIterator implements ListIterator { * The value of the previous (matching) object, when * {@link #previousObjectSet} is true. */ - private Object previousObject; + private E previousObject; /** * Whether or not the {@link #previousObject} has been set @@ -85,7 +85,7 @@ public class FilterListIterator implements ListIterator { * * @param iterator the iterator to use */ - public FilterListIterator(ListIterator iterator ) { + public FilterListIterator(ListIterator iterator ) { super(); this.iterator = iterator; } @@ -96,7 +96,7 @@ public class FilterListIterator implements ListIterator { * @param iterator the iterator to use * @param predicate the predicate to use */ - public FilterListIterator(ListIterator iterator, Predicate predicate) { + public FilterListIterator(ListIterator iterator, Predicate predicate) { super(); this.iterator = iterator; this.predicate = predicate; @@ -108,41 +108,33 @@ public class FilterListIterator implements ListIterator { * * @param predicate the predicate to use. */ - public FilterListIterator(Predicate predicate) { + public FilterListIterator(Predicate predicate) { super(); this.predicate = predicate; } //----------------------------------------------------------------------- /** Not supported. */ - public void add(Object o) { + public void add(E o) { throw new UnsupportedOperationException("FilterListIterator.add(Object) is not supported."); } public boolean hasNext() { - if(nextObjectSet) { - return true; - } else { - return setNextObject(); - } + return nextObjectSet || setNextObject(); } public boolean hasPrevious() { - if(previousObjectSet) { - return true; - } else { - return setPreviousObject(); - } + return previousObjectSet || setPreviousObject(); } - public Object next() { - if(!nextObjectSet) { - if(!setNextObject()) { + public E next() { + if (!nextObjectSet) { + if (!setNextObject()) { throw new NoSuchElementException(); } } nextIndex++; - Object temp = nextObject; + E temp = nextObject; clearNextObject(); return temp; } @@ -151,14 +143,14 @@ public class FilterListIterator implements ListIterator { return nextIndex; } - public Object previous() { - if(!previousObjectSet) { - if(!setPreviousObject()) { + public E previous() { + if (!previousObjectSet) { + if (!setPreviousObject()) { throw new NoSuchElementException(); } } nextIndex--; - Object temp = previousObject; + E temp = previousObject; clearPreviousObject(); return temp; } @@ -173,7 +165,7 @@ public class FilterListIterator implements ListIterator { } /** Not supported. */ - public void set(Object o) { + public void set(E o) { throw new UnsupportedOperationException("FilterListIterator.set(Object) is not supported."); } @@ -183,7 +175,7 @@ public class FilterListIterator implements ListIterator { * * @return the iterator. */ - public ListIterator getListIterator() { + public ListIterator getListIterator() { return iterator; } @@ -193,7 +185,7 @@ public class FilterListIterator implements ListIterator { * * @param iterator the iterator to use */ - public void setListIterator(ListIterator iterator) { + public void setListIterator(ListIterator iterator) { this.iterator = iterator; } @@ -203,7 +195,7 @@ public class FilterListIterator implements ListIterator { * * @return the predicate. */ - public Predicate getPredicate() { + public Predicate getPredicate() { return predicate; } @@ -212,7 +204,7 @@ public class FilterListIterator implements ListIterator { * * @param predicate the transformer to use */ - public void setPredicate(Predicate predicate) { + public void setPredicate(Predicate predicate) { this.predicate = predicate; } @@ -227,18 +219,17 @@ public class FilterListIterator implements ListIterator { // then we've walked back one step in the // underlying list (due to a hasPrevious() call) // so skip ahead one matching object - if(previousObjectSet) { + if (previousObjectSet) { clearPreviousObject(); - if(!setNextObject()) { + if (!setNextObject()) { return false; - } else { - clearNextObject(); } + clearNextObject(); } - while(iterator.hasNext()) { - Object object = iterator.next(); - if(predicate.evaluate(object)) { + while (iterator.hasNext()) { + E object = iterator.next(); + if (predicate.evaluate(object)) { nextObject = object; nextObjectSet = true; return true; @@ -257,18 +248,17 @@ public class FilterListIterator implements ListIterator { // then we've walked back one step in the // underlying list (due to a hasNext() call) // so skip ahead one matching object - if(nextObjectSet) { + if (nextObjectSet) { clearNextObject(); - if(!setPreviousObject()) { + if (!setPreviousObject()) { return false; - } else { - clearPreviousObject(); } + clearPreviousObject(); } - while(iterator.hasPrevious()) { - Object object = iterator.previous(); - if(predicate.evaluate(object)) { + while (iterator.hasPrevious()) { + E object = iterator.previous(); + if (predicate.evaluate(object)) { previousObject = object; previousObjectSet = true; return true; diff --git a/src/java/org/apache/commons/collections/iterators/IteratorChain.java b/src/java/org/apache/commons/collections/iterators/IteratorChain.java index 4d93dd590..8d33c101c 100644 --- a/src/java/org/apache/commons/collections/iterators/IteratorChain.java +++ b/src/java/org/apache/commons/collections/iterators/IteratorChain.java @@ -26,45 +26,50 @@ import org.apache.commons.collections.list.UnmodifiableList; /** * An IteratorChain is an Iterator that wraps a number of Iterators. *

- * This class makes multiple iterators look like one to the caller - * When any method from the Iterator interface is called, the IteratorChain - * will delegate to a single underlying Iterator. The IteratorChain will - * invoke the Iterators in sequence until all Iterators are exhausted. + * This class makes multiple iterators look like one to the caller When any + * method from the Iterator interface is called, the IteratorChain will delegate + * to a single underlying Iterator. The IteratorChain will invoke the Iterators + * in sequence until all Iterators are exhausted. *

- * Under many circumstances, linking Iterators together in this manner is - * more efficient (and convenient) than reading out the contents of each - * Iterator into a List and creating a new Iterator. + * Under many circumstances, linking Iterators together in this manner is more + * efficient (and convenient) than reading out the contents of each Iterator + * into a List and creating a new Iterator. *

* Calling a method that adds new Iteratorafter a method in the Iterator - * interface has been called will result in an UnsupportedOperationException. - * Subclasses should take care to not alter the underlying List of Iterators. + * interface has been called will result in an + * UnsupportedOperationException. Subclasses should take care to not + * alter the underlying List of Iterators. *

- * NOTE: As from version 3.0, the IteratorChain may contain no - * iterators. In this case the class will function as an empty iterator. + * NOTE: As from version 3.0, the IteratorChain may contain no iterators. In + * this case the class will function as an empty iterator. * * @since Commons Collections 2.1 - * @version $Revision$ $Date$ + * @version $Revision$ $Date: 2006-10-27 19:52:37 -0500 (Fri, 27 Oct + * 2006) $ * * @author Morgan Delagrange * @author Stephen Colebourne */ -public class IteratorChain implements Iterator { +public class IteratorChain implements Iterator { /** The chain of iterators */ - protected final List iteratorChain = new ArrayList(); + protected final List> iteratorChain = new ArrayList>(); + /** The index of the current iterator */ protected int currentIteratorIndex = 0; + /** The current iterator */ - protected Iterator currentIterator = null; + protected Iterator currentIterator = null; + /** - * The "last used" Iterator is the Iterator upon which - * next() or hasNext() was most recently called - * used for the remove() operation only + * The "last used" Iterator is the Iterator upon which next() or hasNext() + * was most recently called used for the remove() operation only */ - protected Iterator lastUsedIterator = null; + protected Iterator lastUsedIterator = null; + /** - * ComparatorChain is "locked" after the first time - * compare(Object,Object) is called + * ComparatorChain is "locked" after the first time compare(Object,Object) + * is called */ protected boolean isLocked = false; @@ -72,8 +77,8 @@ public class IteratorChain implements Iterator { /** * Construct an IteratorChain with no Iterators. *

- * You will normally use {@link #addIterator(Iterator)} to add - * some iterators after using this constructor. + * You will normally use {@link #addIterator(Iterator)} to add some + * iterators after using this constructor. */ public IteratorChain() { super(); @@ -82,49 +87,47 @@ public class IteratorChain implements Iterator { /** * Construct an IteratorChain with a single Iterator. *

- * This method takes one iterator. The newly constructed iterator - * will iterate through that iterator. Thus calling this constructor - * on its own will have no effect other than decorating the input iterator. + * This method takes one iterator. The newly constructed iterator will + * iterate through that iterator. Thus calling this constructor on its own + * will have no effect other than decorating the input iterator. *

- * You will normally use {@link #addIterator(Iterator)} to add - * some more iterators after using this constructor. - * - * @param iterator the first child iterator in the IteratorChain, not null + * You will normally use {@link #addIterator(Iterator)} to add some more + * iterators after using this constructor. + * + * @param iterator the first child iterator in the IteratorChain, not null * @throws NullPointerException if the iterator is null */ - public IteratorChain(Iterator iterator) { + public IteratorChain(Iterator iterator) { super(); addIterator(iterator); } /** - * Constructs a new IteratorChain over the two - * given iterators. + * Constructs a new IteratorChain over the two given iterators. *

- * This method takes two iterators. The newly constructed iterator - * will iterate through each one of the input iterators in turn. - * - * @param first the first child iterator in the IteratorChain, not null - * @param second the second child iterator in the IteratorChain, not null + * This method takes two iterators. The newly constructed iterator will + * iterate through each one of the input iterators in turn. + * + * @param first the first child iterator in the IteratorChain, not null + * @param second the second child iterator in the IteratorChain, not null * @throws NullPointerException if either iterator is null */ - public IteratorChain(Iterator first, Iterator second) { + public IteratorChain(Iterator first, Iterator second) { super(); addIterator(first); addIterator(second); } /** - * Constructs a new IteratorChain over the array - * of iterators. + * Constructs a new IteratorChain over the array of iterators. *

* This method takes an array of iterators. The newly constructed iterator * will iterate through each one of the input iterators in turn. - * - * @param iteratorChain the array of iterators, not null + * + * @param iteratorChain the array of iterators, not null * @throws NullPointerException if iterators array is or contains null */ - public IteratorChain(Iterator[] iteratorChain) { + public IteratorChain(Iterator[] iteratorChain) { super(); for (int i = 0; i < iteratorChain.length; i++) { addIterator(iteratorChain[i]); @@ -132,33 +135,33 @@ public class IteratorChain implements Iterator { } /** - * Constructs a new IteratorChain over the collection - * of iterators. + * Constructs a new IteratorChain over the collection of + * iterators. *

- * This method takes a collection of iterators. The newly constructed iterator - * will iterate through each one of the input iterators in turn. - * - * @param iteratorChain the collection of iterators, not null + * This method takes a collection of iterators. The newly constructed + * iterator will iterate through each one of the input iterators in turn. + * + * @param iteratorChain the collection of iterators, not null * @throws NullPointerException if iterators collection is or contains null - * @throws ClassCastException if iterators collection doesn't contain an iterator + * @throws ClassCastException if iterators collection doesn't contain an + * iterator */ - public IteratorChain(Collection iteratorChain) { + public IteratorChain(Collection> iteratorChain) { super(); - for (Iterator it = iteratorChain.iterator(); it.hasNext();) { - Iterator item = (Iterator) it.next(); - addIterator(item); + for (Iterator iterator : iteratorChain) { + addIterator(iterator); } } //----------------------------------------------------------------------- /** * Add an Iterator to the end of the chain - * + * * @param iterator Iterator to add * @throws IllegalStateException if I've already started iterating * @throws NullPointerException if the iterator is null */ - public void addIterator(Iterator iterator) { + public void addIterator(Iterator iterator) { checkLocked(); if (iterator == null) { throw new NullPointerException("Iterator must not be null"); @@ -168,14 +171,15 @@ public class IteratorChain implements Iterator { /** * Set the Iterator at the given index - * - * @param index index of the Iterator to replace - * @param iterator Iterator to place at the given index + * + * @param index index of the Iterator to replace + * @param iterator Iterator to place at the given index * @throws IndexOutOfBoundsException if index < 0 or index > size() * @throws IllegalStateException if I've already started iterating * @throws NullPointerException if the iterator is null */ - public void setIterator(int index, Iterator iterator) throws IndexOutOfBoundsException { + public void setIterator(int index, Iterator iterator) + throws IndexOutOfBoundsException { checkLocked(); if (iterator == null) { throw new NullPointerException("Iterator must not be null"); @@ -185,16 +189,16 @@ public class IteratorChain implements Iterator { /** * Get the list of Iterators (unmodifiable) - * + * * @return the unmodifiable list of iterators added */ - public List getIterators() { + public List> getIterators() { return UnmodifiableList.decorate(iteratorChain); } /** * Number of Iterators in the current IteratorChain. - * + * * @return Iterator count */ public int size() { @@ -203,9 +207,9 @@ public class IteratorChain implements Iterator { /** * Determine if modifications can still be made to the IteratorChain. - * IteratorChains cannot be modified once they have executed a method - * from the Iterator interface. - * + * IteratorChains cannot be modified once they have executed a method from + * the Iterator interface. + * * @return true if IteratorChain cannot be modified, false if it can */ public boolean isLocked() { @@ -217,13 +221,14 @@ public class IteratorChain implements Iterator { */ private void checkLocked() { if (isLocked == true) { - throw new UnsupportedOperationException("IteratorChain cannot be changed after the first use of a method from the Iterator interface"); + throw new UnsupportedOperationException( + "IteratorChain cannot be changed after the first use of a method from the Iterator interface"); } } /** - * Lock the chain so no more iterators can be added. - * This must be called from all Iterator interface methods. + * Lock the chain so no more iterators can be added. This must be called + * from all Iterator interface methods. */ private void lockChain() { if (isLocked == false) { @@ -232,31 +237,32 @@ public class IteratorChain implements Iterator { } /** - * Updates the current iterator field to ensure that the current Iterator - * is not exhausted + * Updates the current iterator field to ensure that the current Iterator is + * not exhausted */ protected void updateCurrentIterator() { if (currentIterator == null) { if (iteratorChain.isEmpty()) { - currentIterator = EmptyIterator.INSTANCE; + currentIterator = EmptyIterator. getInstance(); } else { - currentIterator = (Iterator) iteratorChain.get(0); + currentIterator = iteratorChain.get(0); } // set last used iterator here, in case the user calls remove // before calling hasNext() or next() (although they shouldn't) lastUsedIterator = currentIterator; } - while (currentIterator.hasNext() == false && currentIteratorIndex < iteratorChain.size() - 1) { + while (currentIterator.hasNext() == false + && currentIteratorIndex < iteratorChain.size() - 1) { currentIteratorIndex++; - currentIterator = (Iterator) iteratorChain.get(currentIteratorIndex); + currentIterator = iteratorChain.get(currentIteratorIndex); } } //----------------------------------------------------------------------- /** * Return true if any Iterator in the IteratorChain has a remaining element. - * + * * @return true if elements remain */ public boolean hasNext() { @@ -269,11 +275,12 @@ public class IteratorChain implements Iterator { /** * Returns the next Object of the current Iterator - * + * * @return Object from the current Iterator - * @throws java.util.NoSuchElementException if all the Iterators are exhausted + * @throws java.util.NoSuchElementException if all the Iterators are + * exhausted */ - public Object next() { + public E next() { lockChain(); updateCurrentIterator(); lastUsedIterator = currentIterator; @@ -282,18 +289,17 @@ public class IteratorChain implements Iterator { } /** - * Removes from the underlying collection the last element - * returned by the Iterator. As with next() and hasNext(), - * this method calls remove() on the underlying Iterator. - * Therefore, this method may throw an - * UnsupportedOperationException if the underlying - * Iterator does not support this method. - * - * @throws UnsupportedOperationException - * if the remove operator is not supported by the underlying Iterator - * @throws IllegalStateException - * if the next method has not yet been called, or the remove method has - * already been called after the last call to the next method. + * Removes from the underlying collection the last element returned by the + * Iterator. As with next() and hasNext(), this method calls remove() on the + * underlying Iterator. Therefore, this method may throw an + * UnsupportedOperationException if the underlying Iterator does not support + * this method. + * + * @throws UnsupportedOperationException if the remove operator is not + * supported by the underlying Iterator + * @throws IllegalStateException if the next method has not yet been called, + * or the remove method has already been called after the last call to the + * next method. */ public void remove() { lockChain(); diff --git a/src/java/org/apache/commons/collections/iterators/IteratorEnumeration.java b/src/java/org/apache/commons/collections/iterators/IteratorEnumeration.java index b1a3eca98..a6e54daa6 100644 --- a/src/java/org/apache/commons/collections/iterators/IteratorEnumeration.java +++ b/src/java/org/apache/commons/collections/iterators/IteratorEnumeration.java @@ -19,36 +19,35 @@ package org.apache.commons.collections.iterators; import java.util.Enumeration; import java.util.Iterator; -/** - * Adapter to make an {@link Iterator Iterator} instance appear to be - * an {@link Enumeration Enumeration} instance. +/** + * Adapter to make an {@link Iterator Iterator} instance appear to be an + * {@link Enumeration Enumeration} instance. * * @since Commons Collections 1.0 * @version $Revision$ $Date$ * * @author James Strachan */ -public class IteratorEnumeration implements Enumeration { - +public class IteratorEnumeration implements Enumeration { + /** The iterator being decorated. */ - private Iterator iterator; - + private Iterator iterator; + /** - * Constructs a new IteratorEnumeration that will not - * function until {@link #setIterator(Iterator) setIterator} is - * invoked. + * Constructs a new IteratorEnumeration that will not function + * until {@link #setIterator(Iterator) setIterator} is invoked. */ public IteratorEnumeration() { super(); } /** - * Constructs a new IteratorEnumeration that will use - * the given iterator. + * Constructs a new IteratorEnumeration that will use the given + * iterator. * - * @param iterator the iterator to use + * @param iterator the iterator to use */ - public IteratorEnumeration( Iterator iterator ) { + public IteratorEnumeration(Iterator iterator) { super(); this.iterator = iterator; } @@ -57,22 +56,22 @@ public class IteratorEnumeration implements Enumeration { //------------------------------------------------------------------------- /** - * Returns true if the underlying iterator has more elements. - * - * @return true if the underlying iterator has more elements + * Returns true if the underlying iterator has more elements. + * + * @return true if the underlying iterator has more elements */ public boolean hasMoreElements() { return iterator.hasNext(); } /** - * Returns the next element from the underlying iterator. - * - * @return the next element from the underlying iterator. - * @throws java.util.NoSuchElementException if the underlying iterator has no - * more elements + * Returns the next element from the underlying iterator. + * + * @return the next element from the underlying iterator. + * @throws java.util.NoSuchElementException if the underlying iterator has + * no more elements */ - public Object nextElement() { + public E nextElement() { return iterator.next(); } @@ -80,21 +79,21 @@ public class IteratorEnumeration implements Enumeration { //------------------------------------------------------------------------- /** - * Returns the underlying iterator. + * Returns the underlying iterator. * - * @return the underlying iterator + * @return the underlying iterator */ - public Iterator getIterator() { + public Iterator getIterator() { return iterator; } /** - * Sets the underlying iterator. - * - * @param iterator the new underlying iterator + * Sets the underlying iterator. + * + * @param iterator the new underlying iterator */ - public void setIterator( Iterator iterator ) { + public void setIterator(Iterator iterator) { this.iterator = iterator; } - + } diff --git a/src/java/org/apache/commons/collections/iterators/LoopingIterator.java b/src/java/org/apache/commons/collections/iterators/LoopingIterator.java index 1ebbf111c..05721fcc2 100644 --- a/src/java/org/apache/commons/collections/iterators/LoopingIterator.java +++ b/src/java/org/apache/commons/collections/iterators/LoopingIterator.java @@ -38,12 +38,12 @@ import org.apache.commons.collections.ResettableIterator; * @author Jonathan Carlson * @author Stephen Colebourne */ -public class LoopingIterator implements ResettableIterator { +public class LoopingIterator implements ResettableIterator { /** The collection to base the iterator on */ - private Collection collection; + private Collection collection; /** The current iterator */ - private Iterator iterator; + private Iterator iterator; /** * Constructor that wraps a collection. @@ -54,7 +54,7 @@ public class LoopingIterator implements ResettableIterator { * @param coll the collection to wrap * @throws NullPointerException if the collection is null */ - public LoopingIterator(Collection coll) { + public LoopingIterator(Collection coll) { if (coll == null) { throw new NullPointerException("The collection must not be null"); } @@ -82,7 +82,7 @@ public class LoopingIterator implements ResettableIterator { * @throws NoSuchElementException if there are no elements * at all. Use {@link #hasNext} to avoid this error. */ - public Object next() { + public E next() { if (collection.size() == 0) { throw new NoSuchElementException("There are no elements for this iterator to loop on"); } diff --git a/src/java/org/apache/commons/collections/iterators/LoopingListIterator.java b/src/java/org/apache/commons/collections/iterators/LoopingListIterator.java index 9efc30a2c..80dc4b070 100644 --- a/src/java/org/apache/commons/collections/iterators/LoopingListIterator.java +++ b/src/java/org/apache/commons/collections/iterators/LoopingListIterator.java @@ -39,12 +39,12 @@ import org.apache.commons.collections.ResettableListIterator; * * @author Eric Crampton */ -public class LoopingListIterator implements ResettableListIterator { +public class LoopingListIterator implements ResettableListIterator { /** The list to base the iterator on */ - private List list; + private List list; /** The current list iterator */ - private ListIterator iterator; + private ListIterator iterator; /** * Constructor that wraps a list. @@ -56,7 +56,7 @@ public class LoopingListIterator implements ResettableListIterator { * @param list the list to wrap * @throws NullPointerException if the list it null */ - public LoopingListIterator(List list) { + public LoopingListIterator(List list) { if (list == null) { throw new NullPointerException("The list must not be null"); } @@ -84,7 +84,7 @@ public class LoopingListIterator implements ResettableListIterator { * @return the object after the last element returned * @throws NoSuchElementException if there are no elements in the list */ - public Object next() { + public E next() { if (list.isEmpty()) { throw new NoSuchElementException( "There are no elements for this iterator to loop on"); @@ -113,9 +113,8 @@ public class LoopingListIterator implements ResettableListIterator { } if (iterator.hasNext() == false) { return 0; - } else { - return iterator.nextIndex(); } + return iterator.nextIndex(); } /** @@ -139,21 +138,20 @@ public class LoopingListIterator implements ResettableListIterator { * @return the object before the last element returned * @throws NoSuchElementException if there are no elements in the list */ - public Object previous() { + public E previous() { if (list.isEmpty()) { throw new NoSuchElementException( "There are no elements for this iterator to loop on"); } if (iterator.hasPrevious() == false) { - Object result = null; + E result = null; while (iterator.hasNext()) { result = iterator.next(); } iterator.previous(); return result; - } else { - return iterator.previous(); } + return iterator.previous(); } /** @@ -174,9 +172,8 @@ public class LoopingListIterator implements ResettableListIterator { } if (iterator.hasPrevious() == false) { return list.size() - 1; - } else { - return iterator.previousIndex(); } + return iterator.previousIndex(); } /** @@ -216,7 +213,7 @@ public class LoopingListIterator implements ResettableListIterator { * @throws UnsupportedOperationException if the add method is not * supported by the iterator implementation of the underlying list */ - public void add(Object obj) { + public void add(E obj) { iterator.add(obj); } @@ -232,7 +229,7 @@ public class LoopingListIterator implements ResettableListIterator { * @throws UnsupportedOperationException if the set method is not * supported by the iterator implementation of the underlying list */ - public void set(Object obj) { + public void set(E obj) { iterator.set(obj); } diff --git a/src/java/org/apache/commons/collections/iterators/ObjectArrayIterator.java b/src/java/org/apache/commons/collections/iterators/ObjectArrayIterator.java index 1b249cbb7..344311c4e 100644 --- a/src/java/org/apache/commons/collections/iterators/ObjectArrayIterator.java +++ b/src/java/org/apache/commons/collections/iterators/ObjectArrayIterator.java @@ -40,11 +40,11 @@ import org.apache.commons.collections.ResettableIterator; * @author Stephen Colebourne * @author Phil Steitz */ -public class ObjectArrayIterator - implements Iterator, ResettableIterator { +public class ObjectArrayIterator + implements Iterator, ResettableIterator { /** The array */ - protected Object[] array = null; + protected E[] array = null; /** The start index to loop from */ protected int startIndex = 0; /** The end index to loop to */ @@ -69,7 +69,7 @@ public class ObjectArrayIterator * @param array the array to iterate over * @throws NullPointerException if array is null */ - public ObjectArrayIterator(Object[] array) { + public ObjectArrayIterator(E[] array) { this(array, 0, array.length); } @@ -82,7 +82,7 @@ public class ObjectArrayIterator * @throws NullPointerException if array is null * @throws IndexOutOfBoundsException if the start index is out of bounds */ - public ObjectArrayIterator(Object array[], int start) { + public ObjectArrayIterator(E array[], int start) { this(array, start, array.length); } @@ -97,7 +97,7 @@ public class ObjectArrayIterator * @throws IllegalArgumentException if end index is before the start * @throws NullPointerException if array is null */ - public ObjectArrayIterator(Object array[], int start, int end) { + public ObjectArrayIterator(E array[], int start, int end) { super(); if (start < 0) { throw new ArrayIndexOutOfBoundsException("Start index must not be less than zero"); @@ -136,7 +136,7 @@ public class ObjectArrayIterator * @throws NoSuchElementException if all the elements in the array * have already been returned */ - public Object next() { + public E next() { if (hasNext() == false) { throw new NoSuchElementException(); } @@ -162,7 +162,7 @@ public class ObjectArrayIterator * the no-arg constructor was used and {@link #setArray} has never * been called with a valid array. */ - public Object[] getArray() { + public E[] getArray() { return this.array; } @@ -178,7 +178,7 @@ public class ObjectArrayIterator * @throws IllegalStateException if the array was set in the constructor * @throws NullPointerException if array is null */ - public void setArray(Object[] array) { + public void setArray(E[] array) { if (this.array != null) { throw new IllegalStateException("The array to iterate over has already been set"); } diff --git a/src/java/org/apache/commons/collections/iterators/ReverseListIterator.java b/src/java/org/apache/commons/collections/iterators/ReverseListIterator.java index 3c25f3fb8..e3e0977ff 100644 --- a/src/java/org/apache/commons/collections/iterators/ReverseListIterator.java +++ b/src/java/org/apache/commons/collections/iterators/ReverseListIterator.java @@ -38,12 +38,12 @@ import org.apache.commons.collections.ResettableListIterator; * @since Commons Collections 3.2 * @version $Revision: $ $Date$ */ -public class ReverseListIterator implements ResettableListIterator { +public class ReverseListIterator implements ResettableListIterator { /** The list being wrapped. */ - private final List list; + private final List list; /** The list iterator being wrapped. */ - private ListIterator iterator; + private ListIterator iterator; /** Flag to indicate if updating is possible at the moment. */ private boolean validForUpdate = true; @@ -53,7 +53,7 @@ public class ReverseListIterator implements ResettableListIterator { * @param list the list to create a reversed iterator for * @throws NullPointerException if the list is null */ - public ReverseListIterator(List list) { + public ReverseListIterator(List list) { super(); this.list = list; iterator = list.listIterator(list.size()); @@ -75,8 +75,8 @@ public class ReverseListIterator implements ResettableListIterator { * * @return the next element in the iterator */ - public Object next() { - Object obj = iterator.previous(); + public E next() { + E obj = iterator.previous(); validForUpdate = true; return obj; } @@ -105,8 +105,8 @@ public class ReverseListIterator implements ResettableListIterator { * * @return the previous element in the iterator */ - public Object previous() { - Object obj = iterator.next(); + public E previous() { + E obj = iterator.next(); validForUpdate = true; return obj; } @@ -140,7 +140,7 @@ public class ReverseListIterator implements ResettableListIterator { * @throws UnsupportedOperationException if the list is unmodifiable * @throws IllegalStateException if the iterator is not in a valid state for set */ - public void set(Object obj) { + public void set(E obj) { if (validForUpdate == false) { throw new IllegalStateException("Cannot set to list until next() or previous() called"); } @@ -154,7 +154,7 @@ public class ReverseListIterator implements ResettableListIterator { * @throws UnsupportedOperationException if the list is unmodifiable * @throws IllegalStateException if the iterator is not in a valid state for set */ - public void add(Object obj) { + public void add(E obj) { // the validForUpdate flag is needed as the necessary previous() // method call re-enables remove and add if (validForUpdate == false) { diff --git a/src/java/org/apache/commons/collections/iterators/SingletonListIterator.java b/src/java/org/apache/commons/collections/iterators/SingletonListIterator.java index 9e292c12e..0600783d0 100644 --- a/src/java/org/apache/commons/collections/iterators/SingletonListIterator.java +++ b/src/java/org/apache/commons/collections/iterators/SingletonListIterator.java @@ -31,19 +31,19 @@ import org.apache.commons.collections.ResettableListIterator; * @author Stephen Colebourne * @author Rodney Waldhoff */ -public class SingletonListIterator implements ListIterator, ResettableListIterator { +public class SingletonListIterator implements ListIterator, ResettableListIterator { private boolean beforeFirst = true; private boolean nextCalled = false; private boolean removed = false; - private Object object; + private E object; /** * Constructs a new SingletonListIterator. * * @param object the single object to return from the iterator */ - public SingletonListIterator(Object object) { + public SingletonListIterator(E object) { super(); this.object = object; } @@ -100,7 +100,7 @@ public class SingletonListIterator implements ListIterator, ResettableListIterat * @throws NoSuchElementException if the single object has already * been returned */ - public Object next() { + public E next() { if (!beforeFirst || removed) { throw new NoSuchElementException(); } @@ -118,7 +118,7 @@ public class SingletonListIterator implements ListIterator, ResettableListIterat * @throws NoSuchElementException if the single object has not already * been returned */ - public Object previous() { + public E previous() { if (beforeFirst || removed) { throw new NoSuchElementException(); } @@ -147,7 +147,7 @@ public class SingletonListIterator implements ListIterator, ResettableListIterat * * @throws UnsupportedOperationException always */ - public void add(Object obj) { + public void add(E obj) { throw new UnsupportedOperationException("add() is not supported by this iterator"); } @@ -158,7 +158,7 @@ public class SingletonListIterator implements ListIterator, ResettableListIterat * @throws IllegalStateException if next has not been called * or the object has been removed */ - public void set(Object obj) { + public void set(E obj) { if (!nextCalled || removed) { throw new IllegalStateException(); } diff --git a/src/java/org/apache/commons/collections/iterators/TransformIterator.java b/src/java/org/apache/commons/collections/iterators/TransformIterator.java index 0f0d608e4..9f79a2be3 100644 --- a/src/java/org/apache/commons/collections/iterators/TransformIterator.java +++ b/src/java/org/apache/commons/collections/iterators/TransformIterator.java @@ -29,18 +29,18 @@ import org.apache.commons.collections.Transformer; * @author James Strachan * @author Stephen Colebourne */ -public class TransformIterator implements Iterator { +public class TransformIterator implements Iterator { /** The iterator being used */ - private Iterator iterator; + private Iterator iterator; /** The transformer being used */ - private Transformer transformer; + private Transformer transformer; //----------------------------------------------------------------------- /** * Constructs a new TransformIterator that will not function - * until the {@link #setIterator(Iterator) setIterator} method is - * invoked. + * until the {@link #setIterator(Iterator) setIterator} and + * {@link #setTransformer(Transformer)} methods are invoked. */ public TransformIterator() { super(); @@ -52,7 +52,7 @@ public class TransformIterator implements Iterator { * * @param iterator the iterator to use */ - public TransformIterator(Iterator iterator) { + public TransformIterator(Iterator iterator) { super(); this.iterator = iterator; } @@ -65,7 +65,7 @@ public class TransformIterator implements Iterator { * @param iterator the iterator to use * @param transformer the transformer to use */ - public TransformIterator(Iterator iterator, Transformer transformer) { + public TransformIterator(Iterator iterator, Transformer transformer) { super(); this.iterator = iterator; this.transformer = transformer; @@ -84,7 +84,7 @@ public class TransformIterator implements Iterator { * @return the next object * @throws java.util.NoSuchElementException if there are no more elements */ - public Object next() { + public O next() { return transform(iterator.next()); } @@ -98,7 +98,7 @@ public class TransformIterator implements Iterator { * * @return the iterator. */ - public Iterator getIterator() { + public Iterator getIterator() { return iterator; } @@ -108,7 +108,7 @@ public class TransformIterator implements Iterator { * * @param iterator the iterator to use */ - public void setIterator(Iterator iterator) { + public void setIterator(Iterator iterator) { this.iterator = iterator; } @@ -118,7 +118,7 @@ public class TransformIterator implements Iterator { * * @return the transformer. */ - public Transformer getTransformer() { + public Transformer getTransformer() { return transformer; } @@ -128,7 +128,7 @@ public class TransformIterator implements Iterator { * * @param transformer the transformer to use */ - public void setTransformer(Transformer transformer) { + public void setTransformer(Transformer transformer) { this.transformer = transformer; } @@ -140,10 +140,7 @@ public class TransformIterator implements Iterator { * @param source the object to transform * @return the transformed object */ - protected Object transform(Object source) { - if (transformer != null) { - return transformer.transform(source); - } - return source; + protected O transform(I source) { + return transformer.transform(source); } } diff --git a/src/java/org/apache/commons/collections/iterators/UniqueFilterIterator.java b/src/java/org/apache/commons/collections/iterators/UniqueFilterIterator.java index 87c747c79..64a4b54f8 100644 --- a/src/java/org/apache/commons/collections/iterators/UniqueFilterIterator.java +++ b/src/java/org/apache/commons/collections/iterators/UniqueFilterIterator.java @@ -20,7 +20,7 @@ import java.util.Iterator; import org.apache.commons.collections.functors.UniquePredicate; -/** +/** * A FilterIterator which only returns "unique" Objects. Internally, * the Iterator maintains a Set of objects it has already encountered, * and duplicate Objects are skipped. @@ -30,16 +30,16 @@ import org.apache.commons.collections.functors.UniquePredicate; * * @author Morgan Delagrange */ -public class UniqueFilterIterator extends FilterIterator { - +public class UniqueFilterIterator extends FilterIterator { + //------------------------------------------------------------------------- - + /** * Constructs a new UniqueFilterIterator. * * @param iterator the iterator to use */ - public UniqueFilterIterator( Iterator iterator ) { + public UniqueFilterIterator(Iterator iterator) { super(iterator, UniquePredicate.getInstance()); } diff --git a/src/java/org/apache/commons/collections/iterators/UnmodifiableIterator.java b/src/java/org/apache/commons/collections/iterators/UnmodifiableIterator.java index 7e4cad0c3..7e454cd41 100644 --- a/src/java/org/apache/commons/collections/iterators/UnmodifiableIterator.java +++ b/src/java/org/apache/commons/collections/iterators/UnmodifiableIterator.java @@ -30,10 +30,10 @@ import org.apache.commons.collections.Unmodifiable; * * @author Stephen Colebourne */ -public final class UnmodifiableIterator implements Iterator, Unmodifiable { +public final class UnmodifiableIterator implements Iterator, Unmodifiable { /** The iterator being decorated */ - private Iterator iterator; + private Iterator iterator; //----------------------------------------------------------------------- /** @@ -44,23 +44,23 @@ public final class UnmodifiableIterator implements Iterator, Unmodifiable { * @param iterator the iterator to decorate * @throws IllegalArgumentException if the iterator is null */ - public static Iterator decorate(Iterator iterator) { + public static Iterator decorate(Iterator iterator) { if (iterator == null) { throw new IllegalArgumentException("Iterator must not be null"); } if (iterator instanceof Unmodifiable) { return iterator; } - return new UnmodifiableIterator(iterator); + return new UnmodifiableIterator(iterator); } - + //----------------------------------------------------------------------- /** * Constructor. * * @param iterator the iterator to decorate */ - private UnmodifiableIterator(Iterator iterator) { + private UnmodifiableIterator(Iterator iterator) { super(); this.iterator = iterator; } @@ -70,7 +70,7 @@ public final class UnmodifiableIterator implements Iterator, Unmodifiable { return iterator.hasNext(); } - public Object next() { + public E next() { return iterator.next(); } diff --git a/src/java/org/apache/commons/collections/iterators/UnmodifiableListIterator.java b/src/java/org/apache/commons/collections/iterators/UnmodifiableListIterator.java index 5a9e007df..5c4d623d4 100644 --- a/src/java/org/apache/commons/collections/iterators/UnmodifiableListIterator.java +++ b/src/java/org/apache/commons/collections/iterators/UnmodifiableListIterator.java @@ -30,10 +30,10 @@ import org.apache.commons.collections.Unmodifiable; * * @author Stephen Colebourne */ -public final class UnmodifiableListIterator implements ListIterator, Unmodifiable { +public final class UnmodifiableListIterator implements ListIterator, Unmodifiable { /** The iterator being decorated */ - private ListIterator iterator; + private ListIterator iterator; //----------------------------------------------------------------------- /** @@ -42,14 +42,14 @@ public final class UnmodifiableListIterator implements ListIterator, Unmodifiabl * @param iterator the iterator to decorate * @throws IllegalArgumentException if the iterator is null */ - public static ListIterator decorate(ListIterator iterator) { + public static ListIterator decorate(ListIterator iterator) { if (iterator == null) { throw new IllegalArgumentException("ListIterator must not be null"); } if (iterator instanceof Unmodifiable) { return iterator; } - return new UnmodifiableListIterator(iterator); + return new UnmodifiableListIterator(iterator); } //----------------------------------------------------------------------- @@ -58,7 +58,7 @@ public final class UnmodifiableListIterator implements ListIterator, Unmodifiabl * * @param iterator the iterator to decorate */ - private UnmodifiableListIterator(ListIterator iterator) { + private UnmodifiableListIterator(ListIterator iterator) { super(); this.iterator = iterator; } @@ -68,7 +68,7 @@ public final class UnmodifiableListIterator implements ListIterator, Unmodifiabl return iterator.hasNext(); } - public Object next() { + public E next() { return iterator.next(); } @@ -80,7 +80,7 @@ public final class UnmodifiableListIterator implements ListIterator, Unmodifiabl return iterator.hasPrevious(); } - public Object previous() { + public E previous() { return iterator.previous(); } @@ -92,11 +92,11 @@ public final class UnmodifiableListIterator implements ListIterator, Unmodifiabl throw new UnsupportedOperationException("remove() is not supported"); } - public void set(Object obj) { + public void set(E obj) { throw new UnsupportedOperationException("set() is not supported"); } - public void add(Object obj) { + public void add(E obj) { throw new UnsupportedOperationException("add() is not supported"); } diff --git a/src/java/org/apache/commons/collections/iterators/UnmodifiableMapIterator.java b/src/java/org/apache/commons/collections/iterators/UnmodifiableMapIterator.java index 96f983712..a825b64f5 100644 --- a/src/java/org/apache/commons/collections/iterators/UnmodifiableMapIterator.java +++ b/src/java/org/apache/commons/collections/iterators/UnmodifiableMapIterator.java @@ -29,10 +29,10 @@ import org.apache.commons.collections.Unmodifiable; * * @author Stephen Colebourne */ -public final class UnmodifiableMapIterator implements MapIterator, Unmodifiable { +public final class UnmodifiableMapIterator implements MapIterator, Unmodifiable { /** The iterator being decorated */ - private MapIterator iterator; + private MapIterator iterator; //----------------------------------------------------------------------- /** @@ -41,23 +41,23 @@ public final class UnmodifiableMapIterator implements MapIterator, Unmodifiable * @param iterator the iterator to decorate * @throws IllegalArgumentException if the iterator is null */ - public static MapIterator decorate(MapIterator iterator) { + public static MapIterator decorate(MapIterator iterator) { if (iterator == null) { throw new IllegalArgumentException("MapIterator must not be null"); } if (iterator instanceof Unmodifiable) { return iterator; } - return new UnmodifiableMapIterator(iterator); + return new UnmodifiableMapIterator(iterator); } - + //----------------------------------------------------------------------- /** * Constructor. * * @param iterator the iterator to decorate */ - private UnmodifiableMapIterator(MapIterator iterator) { + private UnmodifiableMapIterator(MapIterator iterator) { super(); this.iterator = iterator; } @@ -67,19 +67,19 @@ public final class UnmodifiableMapIterator implements MapIterator, Unmodifiable return iterator.hasNext(); } - public Object next() { + public K next() { return iterator.next(); } - public Object getKey() { + public K getKey() { return iterator.getKey(); } - public Object getValue() { + public V getValue() { return iterator.getValue(); } - public Object setValue(Object value) { + public V setValue(V value) { throw new UnsupportedOperationException("setValue() is not supported"); } diff --git a/src/java/org/apache/commons/collections/iterators/UnmodifiableOrderedMapIterator.java b/src/java/org/apache/commons/collections/iterators/UnmodifiableOrderedMapIterator.java index 6df67afa3..be8d72955 100644 --- a/src/java/org/apache/commons/collections/iterators/UnmodifiableOrderedMapIterator.java +++ b/src/java/org/apache/commons/collections/iterators/UnmodifiableOrderedMapIterator.java @@ -19,7 +19,7 @@ package org.apache.commons.collections.iterators; import org.apache.commons.collections.OrderedMapIterator; import org.apache.commons.collections.Unmodifiable; -/** +/** * Decorates an ordered map iterator such that it cannot be modified. *

* Attempts to modify it will result in an UnsupportedOperationException. @@ -29,10 +29,11 @@ import org.apache.commons.collections.Unmodifiable; * * @author Stephen Colebourne */ -public final class UnmodifiableOrderedMapIterator implements OrderedMapIterator, Unmodifiable { +public final class UnmodifiableOrderedMapIterator implements OrderedMapIterator, + Unmodifiable { /** The iterator being decorated */ - private OrderedMapIterator iterator; + private OrderedMapIterator iterator; //----------------------------------------------------------------------- /** @@ -41,23 +42,23 @@ public final class UnmodifiableOrderedMapIterator implements OrderedMapIterator, * @param iterator the iterator to decorate * @throws IllegalArgumentException if the iterator is null */ - public static OrderedMapIterator decorate(OrderedMapIterator iterator) { + public static OrderedMapIterator decorate(OrderedMapIterator iterator) { if (iterator == null) { throw new IllegalArgumentException("OrderedMapIterator must not be null"); } if (iterator instanceof Unmodifiable) { return iterator; } - return new UnmodifiableOrderedMapIterator(iterator); + return new UnmodifiableOrderedMapIterator(iterator); } - + //----------------------------------------------------------------------- /** * Constructor. * * @param iterator the iterator to decorate */ - private UnmodifiableOrderedMapIterator(OrderedMapIterator iterator) { + private UnmodifiableOrderedMapIterator(OrderedMapIterator iterator) { super(); this.iterator = iterator; } @@ -67,7 +68,7 @@ public final class UnmodifiableOrderedMapIterator implements OrderedMapIterator, return iterator.hasNext(); } - public Object next() { + public K next() { return iterator.next(); } @@ -75,19 +76,19 @@ public final class UnmodifiableOrderedMapIterator implements OrderedMapIterator, return iterator.hasPrevious(); } - public Object previous() { + public K previous() { return iterator.previous(); } - public Object getKey() { + public K getKey() { return iterator.getKey(); } - public Object getValue() { + public V getValue() { return iterator.getValue(); } - public Object setValue(Object value) { + public V setValue(V value) { throw new UnsupportedOperationException("setValue() is not supported"); } diff --git a/src/java/org/apache/commons/collections/keyvalue/AbstractKeyValue.java b/src/java/org/apache/commons/collections/keyvalue/AbstractKeyValue.java index b4e56c7a3..7aa21850c 100644 --- a/src/java/org/apache/commons/collections/keyvalue/AbstractKeyValue.java +++ b/src/java/org/apache/commons/collections/keyvalue/AbstractKeyValue.java @@ -30,12 +30,12 @@ import org.apache.commons.collections.KeyValue; * @author Neil O'Toole * @author Stephen Colebourne */ -public abstract class AbstractKeyValue implements KeyValue { +public abstract class AbstractKeyValue implements KeyValue { /** The key */ - protected Object key; + protected K key; /** The value */ - protected Object value; + protected V value; /** * Constructs a new pair with the specified key and given value. @@ -43,7 +43,7 @@ public abstract class AbstractKeyValue implements KeyValue { * @param key the key for the entry, may be null * @param value the value for the entry, may be null */ - protected AbstractKeyValue(Object key, Object value) { + protected AbstractKeyValue(K key, V value) { super(); this.key = key; this.value = value; @@ -54,7 +54,7 @@ public abstract class AbstractKeyValue implements KeyValue { * * @return the key */ - public Object getKey() { + public K getKey() { return key; } @@ -63,7 +63,7 @@ public abstract class AbstractKeyValue implements KeyValue { * * @return the value */ - public Object getValue() { + public V getValue() { return value; } diff --git a/src/java/org/apache/commons/collections/keyvalue/AbstractMapEntry.java b/src/java/org/apache/commons/collections/keyvalue/AbstractMapEntry.java index 334f0e7a8..2f7c9ee12 100644 --- a/src/java/org/apache/commons/collections/keyvalue/AbstractMapEntry.java +++ b/src/java/org/apache/commons/collections/keyvalue/AbstractMapEntry.java @@ -30,7 +30,7 @@ import java.util.Map; * @author Neil O'Toole * @author Stephen Colebourne */ -public abstract class AbstractMapEntry extends AbstractKeyValue implements Map.Entry { +public abstract class AbstractMapEntry extends AbstractKeyValue implements Map.Entry { /** * Constructs a new entry with the given key and given value. @@ -38,7 +38,7 @@ public abstract class AbstractMapEntry extends AbstractKeyValue implements Map.E * @param key the key for the entry, may be null * @param value the value for the entry, may be null */ - protected AbstractMapEntry(Object key, Object value) { + protected AbstractMapEntry(K key, V value) { super(key, value); } @@ -53,8 +53,8 @@ public abstract class AbstractMapEntry extends AbstractKeyValue implements Map.E * @param value the new value * @return the previous value */ - public Object setValue(Object value) { - Object answer = this.value; + public V setValue(V value) { + V answer = this.value; this.value = value; return answer; } @@ -67,6 +67,7 @@ public abstract class AbstractMapEntry extends AbstractKeyValue implements Map.E * @param obj the object to compare to * @return true if equal key and value */ + @SuppressWarnings("unchecked") public boolean equals(Object obj) { if (obj == this) { return true; diff --git a/src/java/org/apache/commons/collections/keyvalue/AbstractMapEntryDecorator.java b/src/java/org/apache/commons/collections/keyvalue/AbstractMapEntryDecorator.java index 589dbd4e0..6639ff99d 100644 --- a/src/java/org/apache/commons/collections/keyvalue/AbstractMapEntryDecorator.java +++ b/src/java/org/apache/commons/collections/keyvalue/AbstractMapEntryDecorator.java @@ -29,10 +29,10 @@ import org.apache.commons.collections.KeyValue; * * @author Stephen Colebourne */ -public abstract class AbstractMapEntryDecorator implements Map.Entry, KeyValue { +public abstract class AbstractMapEntryDecorator implements Map.Entry, KeyValue { /** The Map.Entry to decorate */ - protected final Map.Entry entry; + protected final Map.Entry entry; /** * Constructor that wraps (not copies). @@ -40,7 +40,7 @@ public abstract class AbstractMapEntryDecorator implements Map.Entry, KeyValue { * @param entry the Map.Entry to decorate, must not be null * @throws IllegalArgumentException if the collection is null */ - public AbstractMapEntryDecorator(Map.Entry entry) { + public AbstractMapEntryDecorator(Map.Entry entry) { if (entry == null) { throw new IllegalArgumentException("Map Entry must not be null"); } @@ -52,20 +52,20 @@ public abstract class AbstractMapEntryDecorator implements Map.Entry, KeyValue { * * @return the decorated map */ - protected Map.Entry getMapEntry() { + protected Map.Entry getMapEntry() { return entry; } //----------------------------------------------------------------------- - public Object getKey() { + public K getKey() { return entry.getKey(); } - public Object getValue() { + public V getValue() { return entry.getValue(); } - public Object setValue(Object object) { + public V setValue(V object) { return entry.setValue(object); } diff --git a/src/java/org/apache/commons/collections/keyvalue/DefaultKeyValue.java b/src/java/org/apache/commons/collections/keyvalue/DefaultKeyValue.java index 8de11836d..f4514e79b 100644 --- a/src/java/org/apache/commons/collections/keyvalue/DefaultKeyValue.java +++ b/src/java/org/apache/commons/collections/keyvalue/DefaultKeyValue.java @@ -35,7 +35,7 @@ import org.apache.commons.collections.KeyValue; * @author Neil O'Toole * @author Stephen Colebourne */ -public class DefaultKeyValue extends AbstractKeyValue { +public class DefaultKeyValue extends AbstractKeyValue { /** * Constructs a new pair with a null key and null value. @@ -50,7 +50,7 @@ public class DefaultKeyValue extends AbstractKeyValue { * @param key the key for the entry, may be null * @param value the value for the entry, may be null */ - public DefaultKeyValue(final Object key, final Object value) { + public DefaultKeyValue(final K key, final V value) { super(key, value); } @@ -60,7 +60,7 @@ public class DefaultKeyValue extends AbstractKeyValue { * @param pair the pair to copy, must not be null * @throws NullPointerException if the entry is null */ - public DefaultKeyValue(final KeyValue pair) { + public DefaultKeyValue(final KeyValue pair) { super(pair.getKey(), pair.getValue()); } @@ -70,7 +70,7 @@ public class DefaultKeyValue extends AbstractKeyValue { * @param entry the entry to copy, must not be null * @throws NullPointerException if the entry is null */ - public DefaultKeyValue(final Map.Entry entry) { + public DefaultKeyValue(final Map.Entry entry) { super(entry.getKey(), entry.getValue()); } @@ -82,12 +82,12 @@ public class DefaultKeyValue extends AbstractKeyValue { * @return the old key * @throws IllegalArgumentException if key is this object */ - public Object setKey(final Object key) { + public K setKey(final K key) { if (key == this) { throw new IllegalArgumentException("DefaultKeyValue may not contain itself as a key."); } - final Object old = this.key; + final K old = this.key; this.key = key; return old; } @@ -99,12 +99,12 @@ public class DefaultKeyValue extends AbstractKeyValue { * @param value the new value * @throws IllegalArgumentException if value is this object */ - public Object setValue(final Object value) { + public V setValue(final V value) { if (value == this) { throw new IllegalArgumentException("DefaultKeyValue may not contain itself as a value."); } - final Object old = this.value; + final V old = this.value; this.value = value; return old; } @@ -115,8 +115,8 @@ public class DefaultKeyValue extends AbstractKeyValue { * * @return a MapEntry instance */ - public Map.Entry toMapEntry() { - return new DefaultMapEntry(this); + public Map.Entry toMapEntry() { + return new DefaultMapEntry(this); } //----------------------------------------------------------------------- @@ -129,6 +129,7 @@ public class DefaultKeyValue extends AbstractKeyValue { * @param obj the object to compare to * @return true if equal key and value */ + @SuppressWarnings("unchecked") public boolean equals(final Object obj) { if (obj == this) { return true; diff --git a/src/java/org/apache/commons/collections/keyvalue/DefaultMapEntry.java b/src/java/org/apache/commons/collections/keyvalue/DefaultMapEntry.java index 4f2e33577..276be1db1 100644 --- a/src/java/org/apache/commons/collections/keyvalue/DefaultMapEntry.java +++ b/src/java/org/apache/commons/collections/keyvalue/DefaultMapEntry.java @@ -32,7 +32,7 @@ import org.apache.commons.collections.KeyValue; * @author Neil O'Toole * @author Stephen Colebourne */ -public final class DefaultMapEntry extends AbstractMapEntry { +public final class DefaultMapEntry extends AbstractMapEntry { /** * Constructs a new entry with the specified key and given value. @@ -40,7 +40,7 @@ public final class DefaultMapEntry extends AbstractMapEntry { * @param key the key for the entry, may be null * @param value the value for the entry, may be null */ - public DefaultMapEntry(final Object key, final Object value) { + public DefaultMapEntry(final K key, final V value) { super(key, value); } @@ -50,7 +50,7 @@ public final class DefaultMapEntry extends AbstractMapEntry { * @param pair the pair to copy, must not be null * @throws NullPointerException if the entry is null */ - public DefaultMapEntry(final KeyValue pair) { + public DefaultMapEntry(final KeyValue pair) { super(pair.getKey(), pair.getValue()); } @@ -60,7 +60,7 @@ public final class DefaultMapEntry extends AbstractMapEntry { * @param entry the entry to copy, must not be null * @throws NullPointerException if the entry is null */ - public DefaultMapEntry(final Map.Entry entry) { + public DefaultMapEntry(final Map.Entry entry) { super(entry.getKey(), entry.getValue()); } diff --git a/src/java/org/apache/commons/collections/keyvalue/MultiKey.java b/src/java/org/apache/commons/collections/keyvalue/MultiKey.java index 82a1c7beb..1968f86d7 100644 --- a/src/java/org/apache/commons/collections/keyvalue/MultiKey.java +++ b/src/java/org/apache/commons/collections/keyvalue/MultiKey.java @@ -45,17 +45,17 @@ import java.util.Arrays; * @author Howard Lewis Ship * @author Stephen Colebourne */ -public class MultiKey implements Serializable { +public class MultiKey implements Serializable { // This class could implement List, but that would confuse it's purpose /** Serialisation version */ private static final long serialVersionUID = 4465448607415788805L; /** The individual keys */ - private final Object[] keys; + private final K[] keys; /** The cached hashCode */ private transient int hashCode; - + /** * Constructor taking two keys. *

@@ -65,10 +65,11 @@ public class MultiKey implements Serializable { * @param key1 the first key * @param key2 the second key */ - public MultiKey(Object key1, Object key2) { - this(new Object[] {key1, key2}, false); + @SuppressWarnings("unchecked") + public MultiKey(K key1, K key2) { + this((K[]) new Object[] { key1, key2 }, false); } - + /** * Constructor taking three keys. *

@@ -79,10 +80,11 @@ public class MultiKey implements Serializable { * @param key2 the second key * @param key3 the third key */ - public MultiKey(Object key1, Object key2, Object key3) { - this(new Object[] {key1, key2, key3}, false); + @SuppressWarnings("unchecked") + public MultiKey(K key1, K key2, K key3) { + this((K[]) new Object[] {key1, key2, key3}, false); } - + /** * Constructor taking four keys. *

@@ -94,10 +96,11 @@ public class MultiKey implements Serializable { * @param key3 the third key * @param key4 the fourth key */ - public MultiKey(Object key1, Object key2, Object key3, Object key4) { - this(new Object[] {key1, key2, key3, key4}, false); + @SuppressWarnings("unchecked") + public MultiKey(K key1, K key2, K key3, K key4) { + this((K[]) new Object[] {key1, key2, key3, key4}, false); } - + /** * Constructor taking five keys. *

@@ -110,10 +113,11 @@ public class MultiKey implements Serializable { * @param key4 the fourth key * @param key5 the fifth key */ - public MultiKey(Object key1, Object key2, Object key3, Object key4, Object key5) { - this(new Object[] {key1, key2, key3, key4, key5}, false); + @SuppressWarnings("unchecked") + public MultiKey(K key1, K key2, K key3, K key4, K key5) { + this((K[]) new Object[] {key1, key2, key3, key4, key5}, false); } - + /** * Constructor taking an array of keys which is cloned. *

@@ -125,10 +129,10 @@ public class MultiKey implements Serializable { * @param keys the array of keys, not null * @throws IllegalArgumentException if the key array is null */ - public MultiKey(Object[] keys) { + public MultiKey(K[] keys) { this(keys, true); } - + /** * Constructor taking an array of keys, optionally choosing whether to clone. *

@@ -153,20 +157,20 @@ public class MultiKey implements Serializable { * @throws IllegalArgumentException if the key array is null * @since Commons Collections 3.1 */ - public MultiKey(Object[] keys, boolean makeClone) { + public MultiKey(K[] keys, boolean makeClone) { super(); if (keys == null) { throw new IllegalArgumentException("The array of keys must not be null"); } if (makeClone) { - this.keys = (Object[]) keys.clone(); + this.keys = keys.clone(); } else { this.keys = keys; } - + calculateHashCode(keys); } - + //----------------------------------------------------------------------- /** * Gets a clone of the array of keys. @@ -176,10 +180,10 @@ public class MultiKey implements Serializable { * * @return the individual keys */ - public Object[] getKeys() { - return (Object[]) keys.clone(); + public K[] getKeys() { + return keys.clone(); } - + /** * Gets the key at the specified index. *

@@ -191,10 +195,10 @@ public class MultiKey implements Serializable { * @throws IndexOutOfBoundsException if the index is invalid * @since Commons Collections 3.1 */ - public Object getKey(int index) { + public K getKey(int index) { return keys[index]; } - + /** * Gets the size of the list of keys. * @@ -204,7 +208,7 @@ public class MultiKey implements Serializable { public int size() { return keys.length; } - + //----------------------------------------------------------------------- /** * Compares this object to another. @@ -220,7 +224,7 @@ public class MultiKey implements Serializable { return true; } if (other instanceof MultiKey) { - MultiKey otherMulti = (MultiKey) other; + MultiKey otherMulti = (MultiKey) other; return Arrays.equals(keys, otherMulti.keys); } return false; diff --git a/src/java/org/apache/commons/collections/keyvalue/TiedMapEntry.java b/src/java/org/apache/commons/collections/keyvalue/TiedMapEntry.java index 5fec7848e..51340e310 100644 --- a/src/java/org/apache/commons/collections/keyvalue/TiedMapEntry.java +++ b/src/java/org/apache/commons/collections/keyvalue/TiedMapEntry.java @@ -32,15 +32,16 @@ import org.apache.commons.collections.KeyValue; * * @author Stephen Colebourne */ -public class TiedMapEntry implements Map.Entry, KeyValue, Serializable { +public class TiedMapEntry implements Map.Entry, KeyValue, Serializable { /** Serialization version */ private static final long serialVersionUID = -8453869361373831205L; /** The map underlying the entry/iterator */ - private final Map map; + private final Map map; + /** The key */ - private final Object key; + private final K key; /** * Constructs a new entry with the given Map and key. @@ -48,7 +49,7 @@ public class TiedMapEntry implements Map.Entry, KeyValue, Serializable { * @param map the map * @param key the key */ - public TiedMapEntry(Map map, Object key) { + public TiedMapEntry(Map map, K key) { super(); this.map = map; this.key = key; @@ -61,7 +62,7 @@ public class TiedMapEntry implements Map.Entry, KeyValue, Serializable { * * @return the key */ - public Object getKey() { + public K getKey() { return key; } @@ -70,7 +71,7 @@ public class TiedMapEntry implements Map.Entry, KeyValue, Serializable { * * @return the value */ - public Object getValue() { + public V getValue() { return map.get(key); } @@ -81,7 +82,7 @@ public class TiedMapEntry implements Map.Entry, KeyValue, Serializable { * @return the old value * @throws IllegalArgumentException if the value is set to this map entry */ - public Object setValue(Object value) { + public V setValue(V value) { if (value == this) { throw new IllegalArgumentException("Cannot set value to this map entry"); } @@ -96,6 +97,7 @@ public class TiedMapEntry implements Map.Entry, KeyValue, Serializable { * @param obj the object to compare to * @return true if equal key and value */ + @SuppressWarnings("unchecked") public boolean equals(Object obj) { if (obj == this) { return true; diff --git a/src/java/org/apache/commons/collections/keyvalue/UnmodifiableMapEntry.java b/src/java/org/apache/commons/collections/keyvalue/UnmodifiableMapEntry.java index 7eeaac093..a6a75cd9c 100644 --- a/src/java/org/apache/commons/collections/keyvalue/UnmodifiableMapEntry.java +++ b/src/java/org/apache/commons/collections/keyvalue/UnmodifiableMapEntry.java @@ -30,7 +30,7 @@ import org.apache.commons.collections.Unmodifiable; * * @author Stephen Colebourne */ -public final class UnmodifiableMapEntry extends AbstractMapEntry implements Unmodifiable { +public final class UnmodifiableMapEntry extends AbstractMapEntry implements Unmodifiable { /** * Constructs a new entry with the specified key and given value. @@ -38,7 +38,7 @@ public final class UnmodifiableMapEntry extends AbstractMapEntry implements Unmo * @param key the key for the entry, may be null * @param value the value for the entry, may be null */ - public UnmodifiableMapEntry(final Object key, final Object value) { + public UnmodifiableMapEntry(final K key, final V value) { super(key, value); } @@ -48,7 +48,7 @@ public final class UnmodifiableMapEntry extends AbstractMapEntry implements Unmo * @param pair the pair to copy, must not be null * @throws NullPointerException if the entry is null */ - public UnmodifiableMapEntry(final KeyValue pair) { + public UnmodifiableMapEntry(final KeyValue pair) { super(pair.getKey(), pair.getValue()); } @@ -58,7 +58,7 @@ public final class UnmodifiableMapEntry extends AbstractMapEntry implements Unmo * @param entry the entry to copy, must not be null * @throws NullPointerException if the entry is null */ - public UnmodifiableMapEntry(final Map.Entry entry) { + public UnmodifiableMapEntry(final Map.Entry entry) { super(entry.getKey(), entry.getValue()); } @@ -69,7 +69,7 @@ public final class UnmodifiableMapEntry extends AbstractMapEntry implements Unmo * @return the previous value * @throws UnsupportedOperationException always */ - public Object setValue(Object value) { + public V setValue(V value) { throw new UnsupportedOperationException("setValue() is not supported"); } diff --git a/src/java/org/apache/commons/collections/list/AbstractLinkedList.java b/src/java/org/apache/commons/collections/list/AbstractLinkedList.java index 7fd30d423..738871e86 100644 --- a/src/java/org/apache/commons/collections/list/AbstractLinkedList.java +++ b/src/java/org/apache/commons/collections/list/AbstractLinkedList.java @@ -45,7 +45,7 @@ import org.apache.commons.collections.OrderedIterator; * @author Phil Steitz * @author Stephen Colebourne */ -public abstract class AbstractLinkedList implements List { +public abstract class AbstractLinkedList implements List { /* * Implementation notes: @@ -63,9 +63,11 @@ public abstract class AbstractLinkedList implements List { * hold a value. The value of next is the first item in the * list. The value of of previous is the last item in the list. */ - protected transient Node header; + protected transient Node header; + /** The size of the list */ protected transient int size; + /** Modification count for iterators */ protected transient int modCount; @@ -81,10 +83,10 @@ public abstract class AbstractLinkedList implements List { /** * Constructs a list copying data from the specified collection. - * + * * @param coll the collection to copy */ - protected AbstractLinkedList(Collection coll) { + protected AbstractLinkedList(Collection coll) { super(); init(); addAll(coll); @@ -109,28 +111,28 @@ public abstract class AbstractLinkedList implements List { return (size() == 0); } - public Object get(int index) { - Node node = getNode(index, false); + public E get(int index) { + Node node = getNode(index, false); return node.getValue(); } //----------------------------------------------------------------------- - public Iterator iterator() { + public Iterator iterator() { return listIterator(); } - public ListIterator listIterator() { - return new LinkedListIterator(this, 0); + public ListIterator listIterator() { + return new LinkedListIterator(this, 0); } - public ListIterator listIterator(int fromIndex) { - return new LinkedListIterator(this, fromIndex); + public ListIterator listIterator(int fromIndex) { + return new LinkedListIterator(this, fromIndex); } //----------------------------------------------------------------------- public int indexOf(Object value) { int i = 0; - for (Node node = header.next; node != header; node = node.next) { + for (Node node = header.next; node != header; node = node.next) { if (isEqualValue(node.getValue(), value)) { return i; } @@ -141,7 +143,7 @@ public abstract class AbstractLinkedList implements List { public int lastIndexOf(Object value) { int i = size - 1; - for (Node node = header.previous; node != header; node = node.previous) { + for (Node node = header.previous; node != header; node = node.previous) { if (isEqualValue(node.getValue(), value)) { return i; } @@ -154,31 +156,31 @@ public abstract class AbstractLinkedList implements List { return indexOf(value) != -1; } - public boolean containsAll(Collection coll) { - Iterator it = coll.iterator(); - while (it.hasNext()) { - if (contains(it.next()) == false) { + public boolean containsAll(Collection coll) { + for (Object o : coll) { + if (!contains(o)) { return false; } } return true; } - + //----------------------------------------------------------------------- public Object[] toArray() { return toArray(new Object[size]); } - public Object[] toArray(Object[] array) { + @SuppressWarnings("unchecked") + public T[] toArray(T[] array) { // Extend the array if needed if (array.length < size) { Class componentType = array.getClass().getComponentType(); - array = (Object[]) Array.newInstance(componentType, size); + array = (T[]) Array.newInstance(componentType, size); } // Copy the values into the array int i = 0; - for (Node node = header.next; node != header; node = node.next, i++) { - array[i] = node.getValue(); + for (Node node = header.next; node != header; node = node.next, i++) { + array[i] = (T) node.getValue(); } // Set the value after the last value to null if (array.length > size) { @@ -189,49 +191,48 @@ public abstract class AbstractLinkedList implements List { /** * Gets a sublist of the main list. - * + * * @param fromIndexInclusive the index to start from * @param toIndexExclusive the index to end at * @return the new sublist */ - public List subList(int fromIndexInclusive, int toIndexExclusive) { - return new LinkedSubList(this, fromIndexInclusive, toIndexExclusive); + public List subList(int fromIndexInclusive, int toIndexExclusive) { + return new LinkedSubList(this, fromIndexInclusive, toIndexExclusive); } - + //----------------------------------------------------------------------- - public boolean add(Object value) { + public boolean add(E value) { addLast(value); return true; } - - public void add(int index, Object value) { - Node node = getNode(index, true); + + public void add(int index, E value) { + Node node = getNode(index, true); addNodeBefore(node, value); } - - public boolean addAll(Collection coll) { + + public boolean addAll(Collection coll) { return addAll(size, coll); } - public boolean addAll(int index, Collection coll) { - Node node = getNode(index, true); - for (Iterator itr = coll.iterator(); itr.hasNext();) { - Object value = itr.next(); - addNodeBefore(node, value); + public boolean addAll(int index, Collection coll) { + Node node = getNode(index, true); + for (E e : coll) { + addNodeBefore(node, e); } return true; } //----------------------------------------------------------------------- - public Object remove(int index) { - Node node = getNode(index, false); - Object oldValue = node.getValue(); + public E remove(int index) { + Node node = getNode(index, false); + E oldValue = node.getValue(); removeNode(node); return oldValue; } public boolean remove(Object value) { - for (Node node = header.next; node != header; node = node.next) { + for (Node node = header.next; node != header; node = node.next) { if (isEqualValue(node.getValue(), value)) { removeNode(node); return true; @@ -240,9 +241,9 @@ public abstract class AbstractLinkedList implements List { return false; } - public boolean removeAll(Collection coll) { + public boolean removeAll(Collection coll) { boolean modified = false; - Iterator it = iterator(); + Iterator it = iterator(); while (it.hasNext()) { if (coll.contains(it.next())) { it.remove(); @@ -253,9 +254,9 @@ public abstract class AbstractLinkedList implements List { } //----------------------------------------------------------------------- - public boolean retainAll(Collection coll) { + public boolean retainAll(Collection coll) { boolean modified = false; - Iterator it = iterator(); + Iterator it = iterator(); while (it.hasNext()) { if (coll.contains(it.next()) == false) { it.remove(); @@ -265,9 +266,9 @@ public abstract class AbstractLinkedList implements List { return modified; } - public Object set(int index, Object value) { - Node node = getNode(index, false); - Object oldValue = node.getValue(); + public E set(int index, E value) { + Node node = getNode(index, false); + E oldValue = node.getValue(); updateNode(node, value); return oldValue; } @@ -275,55 +276,56 @@ public abstract class AbstractLinkedList implements List { public void clear() { removeAllNodes(); } - + //----------------------------------------------------------------------- - public Object getFirst() { - Node node = header.next; + public E getFirst() { + Node node = header.next; if (node == header) { throw new NoSuchElementException(); } return node.getValue(); } - public Object getLast() { - Node node = header.previous; + public E getLast() { + Node node = header.previous; if (node == header) { throw new NoSuchElementException(); } return node.getValue(); } - public boolean addFirst(Object o) { + public boolean addFirst(E o) { addNodeAfter(header, o); return true; } - public boolean addLast(Object o) { + public boolean addLast(E o) { addNodeBefore(header, o); return true; } - public Object removeFirst() { - Node node = header.next; + public E removeFirst() { + Node node = header.next; if (node == header) { throw new NoSuchElementException(); } - Object oldValue = node.getValue(); + E oldValue = node.getValue(); removeNode(node); return oldValue; } - public Object removeLast() { - Node node = header.previous; + public E removeLast() { + Node node = header.previous; if (node == header) { throw new NoSuchElementException(); } - Object oldValue = node.getValue(); + E oldValue = node.getValue(); removeNode(node); return oldValue; } //----------------------------------------------------------------------- + @SuppressWarnings("unchecked") public boolean equals(Object obj) { if (obj == this) { return true; @@ -348,10 +350,8 @@ public abstract class AbstractLinkedList implements List { public int hashCode() { int hashCode = 1; - Iterator it = iterator(); - while (it.hasNext()) { - Object obj = it.next(); - hashCode = 31 * hashCode + (obj == null ? 0 : obj.hashCode()); + for (E e : this) { + hashCode = 31 * hashCode + (e == null ? 0 : e.hashCode()); } return hashCode; } @@ -363,7 +363,7 @@ public abstract class AbstractLinkedList implements List { StringBuffer buf = new StringBuffer(16 * size()); buf.append("["); - Iterator it = iterator(); + Iterator it = iterator(); boolean hasNext = it.hasNext(); while (hasNext) { Object value = it.next(); @@ -382,7 +382,7 @@ public abstract class AbstractLinkedList implements List { * Compares two values for equals. * This implementation uses the equals method. * Subclasses can override this to match differently. - * + * * @param value1 the first value to compare, may be null * @param value2 the second value to compare, may be null * @return true if equal @@ -390,16 +390,16 @@ public abstract class AbstractLinkedList implements List { protected boolean isEqualValue(Object value1, Object value2) { return (value1 == value2 || (value1 == null ? false : value1.equals(value2))); } - + /** * Updates the node with a new value. * This implementation sets the value on the node. * Subclasses can override this to record the change. - * + * * @param node node to update * @param value new value of the node */ - protected void updateNode(Node node, Object value) { + protected void updateNode(Node node, E value) { node.setValue(value); } @@ -407,26 +407,26 @@ public abstract class AbstractLinkedList implements List { * Creates a new node with previous, next and element all set to null. * This implementation creates a new empty Node. * Subclasses can override this to create a different class. - * + * * @return newly created node */ - protected Node createHeaderNode() { - return new Node(); + protected Node createHeaderNode() { + return new Node(); } /** * Creates a new node with the specified properties. * This implementation creates a new Node with data. * Subclasses can override this to create a different class. - * + * * @param value value of the new node */ - protected Node createNode(Object value) { - return new Node(value); + protected Node createNode(E value) { + return new Node(value); } /** - * Creates a new node with the specified object as its + * Creates a new node with the specified object as its * value and inserts it before node. *

* This implementation uses {@link #createNode(Object)} and @@ -436,24 +436,24 @@ public abstract class AbstractLinkedList implements List { * @param value value of the newly added node * @throws NullPointerException if node is null */ - protected void addNodeBefore(Node node, Object value) { - Node newNode = createNode(value); + protected void addNodeBefore(Node node, E value) { + Node newNode = createNode(value); addNode(newNode, node); } /** - * Creates a new node with the specified object as its + * Creates a new node with the specified object as its * value and inserts it after node. *

* This implementation uses {@link #createNode(Object)} and * {@link #addNode(AbstractLinkedList.Node,AbstractLinkedList.Node)}. - * + * * @param node node to insert after * @param value value of the newly added node * @throws NullPointerException if node is null */ - protected void addNodeAfter(Node node, Object value) { - Node newNode = createNode(value); + protected void addNodeAfter(Node node, E value) { + Node newNode = createNode(value); addNode(newNode, node.next); } @@ -464,7 +464,7 @@ public abstract class AbstractLinkedList implements List { * @param insertBeforeNode node to insert before * @throws NullPointerException if either node is null */ - protected void addNode(Node nodeToInsert, Node insertBeforeNode) { + protected void addNode(Node nodeToInsert, Node insertBeforeNode) { nodeToInsert.next = insertBeforeNode; nodeToInsert.previous = insertBeforeNode.previous; insertBeforeNode.previous.next = nodeToInsert; @@ -479,7 +479,7 @@ public abstract class AbstractLinkedList implements List { * @param node the node to remove * @throws NullPointerException if node is null */ - protected void removeNode(Node node) { + protected void removeNode(Node node) { node.previous.next = node.next; node.next.previous = node.previous; size--; @@ -498,7 +498,7 @@ public abstract class AbstractLinkedList implements List { /** * Gets the node at a particular index. - * + * * @param index the index, starting from 0 * @param endMarkerAllowed whether or not the end marker can be returned if * startIndex is set to the list's size @@ -506,7 +506,7 @@ public abstract class AbstractLinkedList implements List { * the size of the list and endMakerAllowed is false; or greater than the * size of the list */ - protected Node getNode(int index, boolean endMarkerAllowed) throws IndexOutOfBoundsException { + protected Node getNode(int index, boolean endMarkerAllowed) throws IndexOutOfBoundsException { // Check the index is within the bounds if (index < 0) { throw new IndexOutOfBoundsException("Couldn't get the node: " + @@ -522,7 +522,7 @@ public abstract class AbstractLinkedList implements List { "list (" + size + ")."); } // Search the list and get the node - Node node; + Node node; if (index < (size / 2)) { // Search forwards node = header.next; @@ -542,21 +542,21 @@ public abstract class AbstractLinkedList implements List { //----------------------------------------------------------------------- /** * Creates an iterator for the sublist. - * + * * @param subList the sublist to get an iterator for */ - protected Iterator createSubListIterator(LinkedSubList subList) { + protected Iterator createSubListIterator(LinkedSubList subList) { return createSubListListIterator(subList, 0); } /** * Creates a list iterator for the sublist. - * + * * @param subList the sublist to get an iterator for * @param fromIndex the index to start from, relative to the sublist */ - protected ListIterator createSubListListIterator(LinkedSubList subList, int fromIndex) { - return new LinkedSubListIterator(subList, fromIndex); + protected ListIterator createSubListListIterator(LinkedSubList subList, int fromIndex) { + return new LinkedSubListIterator(subList, fromIndex); } //----------------------------------------------------------------------- @@ -569,7 +569,7 @@ public abstract class AbstractLinkedList implements List { protected void doWriteObject(ObjectOutputStream outputStream) throws IOException { // Write the size so we know how many nodes to read back outputStream.writeInt(size()); - for (Iterator itr = iterator(); itr.hasNext();) { + for (Iterator itr = iterator(); itr.hasNext();) { outputStream.writeObject(itr.next()); } } @@ -580,11 +580,12 @@ public abstract class AbstractLinkedList implements List { * The first serializable subclass must call this method from * readObject. */ + @SuppressWarnings("unchecked") protected void doReadObject(ObjectInputStream inputStream) throws IOException, ClassNotFoundException { init(); int size = inputStream.readInt(); for (int i = 0; i < size; i++) { - add(inputStream.readObject()); + add((E) inputStream.readObject()); } } @@ -595,14 +596,14 @@ public abstract class AbstractLinkedList implements List { * From Commons Collections 3.1, all access to the value property * is via the methods on this class. */ - protected static class Node { + protected static class Node { /** A pointer to the node before this node */ - protected Node previous; + protected Node previous; /** A pointer to the node after this node */ - protected Node next; + protected Node next; /** The object contained within this node */ - protected Object value; + protected E value; /** * Constructs a new header node. @@ -615,85 +616,85 @@ public abstract class AbstractLinkedList implements List { /** * Constructs a new node. - * + * * @param value the value to store */ - protected Node(Object value) { + protected Node(E value) { super(); this.value = value; } - + /** * Constructs a new node. - * + * * @param previous the previous node in the list * @param next the next node in the list * @param value the value to store */ - protected Node(Node previous, Node next, Object value) { + protected Node(Node previous, Node next, E value) { super(); this.previous = previous; this.next = next; this.value = value; } - + /** * Gets the value of the node. - * + * * @return the value * @since Commons Collections 3.1 */ - protected Object getValue() { + protected E getValue() { return value; } - + /** * Sets the value of the node. - * + * * @param value the value * @since Commons Collections 3.1 */ - protected void setValue(Object value) { + protected void setValue(E value) { this.value = value; } - + /** * Gets the previous node. - * + * * @return the previous node * @since Commons Collections 3.1 */ - protected Node getPreviousNode() { + protected Node getPreviousNode() { return previous; } - + /** * Sets the previous node. - * + * * @param previous the previous node * @since Commons Collections 3.1 */ - protected void setPreviousNode(Node previous) { + protected void setPreviousNode(Node previous) { this.previous = previous; } - + /** * Gets the next node. - * + * * @return the next node * @since Commons Collections 3.1 */ - protected Node getNextNode() { + protected Node getNextNode() { return next; } - + /** * Sets the next node. - * + * * @param next the next node * @since Commons Collections 3.1 */ - protected void setNextNode(Node next) { + protected void setNextNode(Node next) { this.next = next; } } @@ -702,16 +703,16 @@ public abstract class AbstractLinkedList implements List { /** * A list iterator over the linked list. */ - protected static class LinkedListIterator implements ListIterator, OrderedIterator { - + protected static class LinkedListIterator implements ListIterator, OrderedIterator { + /** The parent list */ - protected final AbstractLinkedList parent; + protected final AbstractLinkedList parent; /** * The node that will be returned by {@link #next()}. If this is equal * to {@link AbstractLinkedList#header} then there are no more values to return. */ - protected Node next; + protected Node next; /** * The index of {@link #next}. @@ -726,7 +727,7 @@ public abstract class AbstractLinkedList implements List { * Should be accessed through {@link #getLastNodeReturned()} to enforce * this behaviour. */ - protected Node current; + protected Node current; /** * The modification count that the list is expected to have. If the list @@ -738,11 +739,11 @@ public abstract class AbstractLinkedList implements List { /** * Create a ListIterator for a list. - * + * * @param parent the parent list * @param fromIndex the index to start at */ - protected LinkedListIterator(AbstractLinkedList parent, int fromIndex) throws IndexOutOfBoundsException { + protected LinkedListIterator(AbstractLinkedList parent, int fromIndex) throws IndexOutOfBoundsException { super(); this.parent = parent; this.expectedModCount = parent.modCount; @@ -753,7 +754,7 @@ public abstract class AbstractLinkedList implements List { /** * Checks the modification count of the list is the value that this * object expects. - * + * * @throws ConcurrentModificationException If the list's modification * count isn't the value that was expected. */ @@ -765,12 +766,12 @@ public abstract class AbstractLinkedList implements List { /** * Gets the last node returned. - * + * * @throws IllegalStateException If {@link #next()} or * {@link #previous()} haven't been called, or if the node has been removed * with {@link #remove()} or a new node added with {@link #add(Object)}. */ - protected Node getLastNodeReturned() throws IllegalStateException { + protected Node getLastNodeReturned() throws IllegalStateException { if (current == null) { throw new IllegalStateException(); } @@ -781,12 +782,12 @@ public abstract class AbstractLinkedList implements List { return next != parent.header; } - public Object next() { + public E next() { checkModCount(); if (!hasNext()) { throw new NoSuchElementException("No element at index " + nextIndex + "."); } - Object value = next.getValue(); + E value = next.getValue(); current = next; next = next.next; nextIndex++; @@ -797,13 +798,13 @@ public abstract class AbstractLinkedList implements List { return next.previous != parent.header; } - public Object previous() { + public E previous() { checkModCount(); if (!hasPrevious()) { throw new NoSuchElementException("Already at start of list."); } next = next.previous; - Object value = next.getValue(); + E value = next.getValue(); current = next; nextIndex--; return value; @@ -833,12 +834,12 @@ public abstract class AbstractLinkedList implements List { expectedModCount++; } - public void set(Object obj) { + public void set(E obj) { checkModCount(); getLastNodeReturned().setValue(obj); } - public void add(Object obj) { + public void add(E obj) { checkModCount(); parent.addNodeBefore(next, obj); current = null; @@ -852,12 +853,12 @@ public abstract class AbstractLinkedList implements List { /** * A list iterator over the linked sub list. */ - protected static class LinkedSubListIterator extends LinkedListIterator { - + protected static class LinkedSubListIterator extends LinkedListIterator { + /** The parent list */ - protected final LinkedSubList sub; - - protected LinkedSubListIterator(LinkedSubList sub, int startIndex) { + protected final LinkedSubList sub; + + protected LinkedSubListIterator(LinkedSubList sub, int startIndex) { super(sub.parent, startIndex + sub.offset); this.sub = sub; } @@ -874,26 +875,26 @@ public abstract class AbstractLinkedList implements List { return (super.nextIndex() - sub.offset); } - public void add(Object obj) { + public void add(E obj) { super.add(obj); sub.expectedModCount = parent.modCount; sub.size++; } - + public void remove() { super.remove(); sub.expectedModCount = parent.modCount; sub.size--; } } - + //----------------------------------------------------------------------- /** * The sublist implementation for AbstractLinkedList. */ - protected static class LinkedSubList extends AbstractList { + protected static class LinkedSubList extends AbstractList { /** The main list */ - AbstractLinkedList parent; + AbstractLinkedList parent; /** Offset from the main list */ int offset; /** Sublist size */ @@ -901,7 +902,7 @@ public abstract class AbstractLinkedList implements List { /** Sublist modCount */ int expectedModCount; - protected LinkedSubList(AbstractLinkedList parent, int fromIndex, int toIndex) { + protected LinkedSubList(AbstractLinkedList parent, int fromIndex, int toIndex) { if (fromIndex < 0) { throw new IndexOutOfBoundsException("fromIndex = " + fromIndex); } @@ -922,13 +923,13 @@ public abstract class AbstractLinkedList implements List { return size; } - public Object get(int index) { + public E get(int index) { rangeCheck(index, size); checkModCount(); return parent.get(index + offset); } - public void add(int index, Object obj) { + public void add(int index, E obj) { rangeCheck(index, size + 1); checkModCount(); parent.add(index + offset, obj); @@ -937,21 +938,21 @@ public abstract class AbstractLinkedList implements List { LinkedSubList.this.modCount++; } - public Object remove(int index) { + public E remove(int index) { rangeCheck(index, size); checkModCount(); - Object result = parent.remove(index + offset); + E result = parent.remove(index + offset); expectedModCount = parent.modCount; size--; LinkedSubList.this.modCount++; return result; } - public boolean addAll(Collection coll) { + public boolean addAll(Collection coll) { return addAll(size, coll); } - public boolean addAll(int index, Collection coll) { + public boolean addAll(int index, Collection coll) { rangeCheck(index, size + 1); int cSize = coll.size(); if (cSize == 0) { @@ -966,7 +967,7 @@ public abstract class AbstractLinkedList implements List { return true; } - public Object set(int index, Object obj) { + public E set(int index, E obj) { rangeCheck(index, size); checkModCount(); return parent.set(index + offset, obj); @@ -974,26 +975,26 @@ public abstract class AbstractLinkedList implements List { public void clear() { checkModCount(); - Iterator it = iterator(); + Iterator it = iterator(); while (it.hasNext()) { it.next(); it.remove(); } } - public Iterator iterator() { + public Iterator iterator() { checkModCount(); return parent.createSubListIterator(this); } - public ListIterator listIterator(final int index) { + public ListIterator listIterator(final int index) { rangeCheck(index, size + 1); checkModCount(); return parent.createSubListListIterator(this, index); } - public List subList(int fromIndexInclusive, int toIndexExclusive) { - return new LinkedSubList(parent, fromIndexInclusive + offset, toIndexExclusive + offset); + public List subList(int fromIndexInclusive, int toIndexExclusive) { + return new LinkedSubList(parent, fromIndexInclusive + offset, toIndexExclusive + offset); } protected void rangeCheck(int index, int beyond) { @@ -1008,5 +1009,5 @@ public abstract class AbstractLinkedList implements List { } } } - + } diff --git a/src/java/org/apache/commons/collections/list/AbstractSerializableListDecorator.java b/src/java/org/apache/commons/collections/list/AbstractSerializableListDecorator.java index a3c03b22a..93f69c048 100644 --- a/src/java/org/apache/commons/collections/list/AbstractSerializableListDecorator.java +++ b/src/java/org/apache/commons/collections/list/AbstractSerializableListDecorator.java @@ -29,8 +29,8 @@ import java.util.List; * @author Stephen Colebourne * @since Commons Collections 3.1 */ -public abstract class AbstractSerializableListDecorator - extends AbstractListDecorator +public abstract class AbstractSerializableListDecorator + extends AbstractListDecorator implements Serializable { /** Serialization version */ @@ -39,7 +39,7 @@ public abstract class AbstractSerializableListDecorator /** * Constructor. */ - protected AbstractSerializableListDecorator(List list) { + protected AbstractSerializableListDecorator(List list) { super(list); } @@ -62,9 +62,10 @@ public abstract class AbstractSerializableListDecorator * @throws IOException * @throws ClassNotFoundException */ + @SuppressWarnings("unchecked") private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); - collection = (Collection) in.readObject(); + collection = (Collection) in.readObject(); } } diff --git a/src/java/org/apache/commons/collections/list/CursorableLinkedList.java b/src/java/org/apache/commons/collections/list/CursorableLinkedList.java index 091fa30af..6b1d46c80 100644 --- a/src/java/org/apache/commons/collections/list/CursorableLinkedList.java +++ b/src/java/org/apache/commons/collections/list/CursorableLinkedList.java @@ -60,13 +60,13 @@ import java.util.ListIterator; * @author Simon Kitching * @author Stephen Colebourne */ -public class CursorableLinkedList extends AbstractLinkedList implements Serializable { +public class CursorableLinkedList extends AbstractLinkedList implements Serializable { /** Ensure serialization compatibility */ private static final long serialVersionUID = 8836393098519411393L; /** A list of the cursor currently open on this list */ - protected transient List cursors = new ArrayList(); + protected transient List>> cursors; //----------------------------------------------------------------------- /** @@ -82,7 +82,7 @@ public class CursorableLinkedList extends AbstractLinkedList implements Serializ * * @param coll the collection to copy */ - public CursorableLinkedList(Collection coll) { + public CursorableLinkedList(Collection coll) { super(coll); } @@ -92,7 +92,7 @@ public class CursorableLinkedList extends AbstractLinkedList implements Serializ */ protected void init() { super.init(); - cursors = new ArrayList(); + cursors = new ArrayList>>(); } //----------------------------------------------------------------------- @@ -105,7 +105,7 @@ public class CursorableLinkedList extends AbstractLinkedList implements Serializ * * @return a new iterator that does not support concurrent modification */ - public Iterator iterator() { + public Iterator iterator() { return super.listIterator(0); } @@ -124,7 +124,7 @@ public class CursorableLinkedList extends AbstractLinkedList implements Serializ * * @return a new cursor iterator */ - public ListIterator listIterator() { + public ListIterator listIterator() { return cursor(0); } @@ -144,7 +144,7 @@ public class CursorableLinkedList extends AbstractLinkedList implements Serializ * @param fromIndex the index to start from * @return a new cursor iterator */ - public ListIterator listIterator(int fromIndex) { + public ListIterator listIterator(int fromIndex) { return cursor(fromIndex); } @@ -171,7 +171,7 @@ public class CursorableLinkedList extends AbstractLinkedList implements Serializ * * @return a new cursor iterator */ - public CursorableLinkedList.Cursor cursor() { + public CursorableLinkedList.Cursor cursor() { return cursor(0); } @@ -202,8 +202,8 @@ public class CursorableLinkedList extends AbstractLinkedList implements Serializ * @throws IndexOutOfBoundsException if the index is out of range * (index < 0 || index > size()). */ - public CursorableLinkedList.Cursor cursor(int fromIndex) { - Cursor cursor = new Cursor(this, fromIndex); + public CursorableLinkedList.Cursor cursor(int fromIndex) { + Cursor cursor = new Cursor(this, fromIndex); registerCursor(cursor); return cursor; } @@ -217,7 +217,7 @@ public class CursorableLinkedList extends AbstractLinkedList implements Serializ * @param node node to update * @param value new value of the node */ - protected void updateNode(Node node, Object value) { + protected void updateNode(Node node, E value) { super.updateNode(node, value); broadcastNodeChanged(node); } @@ -229,7 +229,7 @@ public class CursorableLinkedList extends AbstractLinkedList implements Serializ * @param insertBeforeNode node to insert before * @throws NullPointerException if either node is null */ - protected void addNode(Node nodeToInsert, Node insertBeforeNode) { + protected void addNode(Node nodeToInsert, Node insertBeforeNode) { super.addNode(nodeToInsert, insertBeforeNode); broadcastNodeInserted(nodeToInsert); } @@ -240,7 +240,7 @@ public class CursorableLinkedList extends AbstractLinkedList implements Serializ * @param node the node to remove * @throws NullPointerException if node is null */ - protected void removeNode(Node node) { + protected void removeNode(Node node) { super.removeNode(node); broadcastNodeRemoved(node); } @@ -251,7 +251,7 @@ public class CursorableLinkedList extends AbstractLinkedList implements Serializ protected void removeAllNodes() { if (size() > 0) { // superclass implementation would break all the iterators - Iterator it = iterator(); + Iterator it = iterator(); while (it.hasNext()) { it.next(); it.remove(); @@ -265,16 +265,16 @@ public class CursorableLinkedList extends AbstractLinkedList implements Serializ * * @param cursor the cursor to register */ - protected void registerCursor(Cursor cursor) { + protected void registerCursor(Cursor cursor) { // We take this opportunity to clean the cursors list // of WeakReference objects to garbage-collected cursors. - for (Iterator it = cursors.iterator(); it.hasNext();) { - WeakReference ref = (WeakReference) it.next(); + for (Iterator>> it = cursors.iterator(); it.hasNext();) { + WeakReference> ref = it.next(); if (ref.get() == null) { it.remove(); } } - cursors.add(new WeakReference(cursor)); + cursors.add(new WeakReference>(cursor)); } /** @@ -282,16 +282,15 @@ public class CursorableLinkedList extends AbstractLinkedList implements Serializ * * @param cursor the cursor to deregister */ - protected void unregisterCursor(Cursor cursor) { - for (Iterator it = cursors.iterator(); it.hasNext();) { - WeakReference ref = (WeakReference) it.next(); - Cursor cur = (Cursor) ref.get(); + protected void unregisterCursor(Cursor cursor) { + for (Iterator>> it = cursors.iterator(); it.hasNext();) { + WeakReference> ref = it.next(); + Cursor cur = ref.get(); if (cur == null) { // some other unrelated cursor object has been // garbage-collected; let's take the opportunity to // clean up the cursors list anyway.. it.remove(); - } else if (cur == cursor) { ref.clear(); it.remove(); @@ -307,11 +306,11 @@ public class CursorableLinkedList extends AbstractLinkedList implements Serializ * * @param node the node that was changed */ - protected void broadcastNodeChanged(Node node) { - Iterator it = cursors.iterator(); + protected void broadcastNodeChanged(Node node) { + Iterator>> it = cursors.iterator(); while (it.hasNext()) { - WeakReference ref = (WeakReference) it.next(); - Cursor cursor = (Cursor) ref.get(); + WeakReference> ref = it.next(); + Cursor cursor = ref.get(); if (cursor == null) { it.remove(); // clean up list } else { @@ -326,11 +325,11 @@ public class CursorableLinkedList extends AbstractLinkedList implements Serializ * * @param node the node that was changed */ - protected void broadcastNodeRemoved(Node node) { - Iterator it = cursors.iterator(); + protected void broadcastNodeRemoved(Node node) { + Iterator>> it = cursors.iterator(); while (it.hasNext()) { - WeakReference ref = (WeakReference) it.next(); - Cursor cursor = (Cursor) ref.get(); + WeakReference> ref = it.next(); + Cursor cursor = ref.get(); if (cursor == null) { it.remove(); // clean up list } else { @@ -345,11 +344,11 @@ public class CursorableLinkedList extends AbstractLinkedList implements Serializ * * @param node the node that was changed */ - protected void broadcastNodeInserted(Node node) { - Iterator it = cursors.iterator(); + protected void broadcastNodeInserted(Node node) { + Iterator>> it = cursors.iterator(); while (it.hasNext()) { - WeakReference ref = (WeakReference) it.next(); - Cursor cursor = (Cursor) ref.get(); + WeakReference> ref = it.next(); + Cursor cursor = ref.get(); if (cursor == null) { it.remove(); // clean up list } else { @@ -382,8 +381,8 @@ public class CursorableLinkedList extends AbstractLinkedList implements Serializ * @param subList the sublist to get an iterator for * @param fromIndex the index to start from, relative to the sublist */ - protected ListIterator createSubListListIterator(LinkedSubList subList, int fromIndex) { - SubCursor cursor = new SubCursor(subList, fromIndex); + protected ListIterator createSubListListIterator(LinkedSubList subList, int fromIndex) { + SubCursor cursor = new SubCursor(subList, fromIndex); registerCursor(cursor); return cursor; } @@ -393,7 +392,7 @@ public class CursorableLinkedList extends AbstractLinkedList implements Serializ * An extended ListIterator that allows concurrent changes to * the underlying list. */ - public static class Cursor extends AbstractLinkedList.LinkedListIterator { + public static class Cursor extends AbstractLinkedList.LinkedListIterator { /** Is the cursor valid (not closed) */ boolean valid = true; /** Is the next index valid */ @@ -406,7 +405,7 @@ public class CursorableLinkedList extends AbstractLinkedList implements Serializ * * @param index the index to start from */ - protected Cursor(CursorableLinkedList parent, int index) { + protected Cursor(CursorableLinkedList parent, int index) { super(parent, index); valid = true; } @@ -443,7 +442,7 @@ public class CursorableLinkedList extends AbstractLinkedList implements Serializ * * @param obj the object to add */ - public void add(Object obj) { + public void add(E obj) { // overridden, as the nodeInserted() method updates the iterator state super.add(obj); // matches the (next.previous == node) clause in nodeInserted() @@ -467,7 +466,7 @@ public class CursorableLinkedList extends AbstractLinkedList implements Serializ nextIndex = parent.size(); } else { int pos = 0; - Node temp = parent.header.next; + Node temp = parent.header.next; while (temp != next) { pos++; temp = temp.next; @@ -484,7 +483,7 @@ public class CursorableLinkedList extends AbstractLinkedList implements Serializ * * @param node the node that changed */ - protected void nodeChanged(Node node) { + protected void nodeChanged(Node node) { // do nothing } @@ -493,7 +492,7 @@ public class CursorableLinkedList extends AbstractLinkedList implements Serializ * * @param node the node that was removed */ - protected void nodeRemoved(Node node) { + protected void nodeRemoved(Node node) { if (node == next && node == current) { // state where next() followed by previous() next = node.next; @@ -521,7 +520,7 @@ public class CursorableLinkedList extends AbstractLinkedList implements Serializ * * @param node the node that was added */ - protected void nodeInserted(Node node) { + protected void nodeInserted(Node node) { if (node.previous == current) { next = node; } else if (next.previous == node) { @@ -550,7 +549,7 @@ public class CursorableLinkedList extends AbstractLinkedList implements Serializ */ public void close() { if (valid) { - ((CursorableLinkedList) parent).unregisterCursor(this); + ((CursorableLinkedList) parent).unregisterCursor(this); valid = false; } } @@ -562,18 +561,18 @@ public class CursorableLinkedList extends AbstractLinkedList implements Serializ * * @since Commons Collections 3.2 */ - protected static class SubCursor extends Cursor { + protected static class SubCursor extends Cursor { /** The parent list */ - protected final LinkedSubList sub; + protected final LinkedSubList sub; /** * Constructs a new cursor. * * @param index the index to start from */ - protected SubCursor(LinkedSubList sub, int index) { - super((CursorableLinkedList) sub.parent, index + sub.offset); + protected SubCursor(LinkedSubList sub, int index) { + super((CursorableLinkedList) sub.parent, index + sub.offset); this.sub = sub; } @@ -589,7 +588,7 @@ public class CursorableLinkedList extends AbstractLinkedList implements Serializ return (super.nextIndex() - sub.offset); } - public void add(Object obj) { + public void add(E obj) { super.add(obj); sub.expectedModCount = parent.modCount; sub.size++; diff --git a/src/java/org/apache/commons/collections/list/NodeCachingLinkedList.java b/src/java/org/apache/commons/collections/list/NodeCachingLinkedList.java index ac4e90fb5..299cb3bdb 100644 --- a/src/java/org/apache/commons/collections/list/NodeCachingLinkedList.java +++ b/src/java/org/apache/commons/collections/list/NodeCachingLinkedList.java @@ -44,7 +44,7 @@ import java.util.Collection; * @author Phil Steitz * @author Stephen Colebourne */ -public class NodeCachingLinkedList extends AbstractLinkedList implements Serializable { +public class NodeCachingLinkedList extends AbstractLinkedList implements Serializable { /** Serialization version */ private static final long serialVersionUID = 6897789178562232073L; @@ -59,7 +59,7 @@ public class NodeCachingLinkedList extends AbstractLinkedList implements Seriali * Cached nodes are stored in a singly-linked list with * next pointing to the next element. */ - protected transient Node firstCachedNode; + protected transient Node firstCachedNode; /** * The size of the cache. @@ -84,7 +84,7 @@ public class NodeCachingLinkedList extends AbstractLinkedList implements Seriali * * @param coll the collection to copy */ - public NodeCachingLinkedList(Collection coll) { + public NodeCachingLinkedList(Collection coll) { super(coll); this.maximumCacheSize = DEFAULT_MAXIMUM_CACHE_SIZE; } @@ -137,11 +137,11 @@ public class NodeCachingLinkedList extends AbstractLinkedList implements Seriali * * @return a node, or null if there are no nodes in the cache. */ - protected Node getNodeFromCache() { + protected Node getNodeFromCache() { if (cacheSize == 0) { return null; } - Node cachedNode = firstCachedNode; + Node cachedNode = firstCachedNode; firstCachedNode = cachedNode.next; cachedNode.next = null; // This should be changed anyway, but defensively // set it to null. @@ -164,13 +164,13 @@ public class NodeCachingLinkedList extends AbstractLinkedList implements Seriali * * @param node the node to add to the cache */ - protected void addNodeToCache(Node node) { + protected void addNodeToCache(Node node) { if (isCacheFull()) { // don't cache the node. return; } // clear the node's contents and add it to the cache. - Node nextCachedNode = firstCachedNode; + Node nextCachedNode = firstCachedNode; node.previous = null; node.next = nextCachedNode; node.setValue(null); @@ -186,14 +186,13 @@ public class NodeCachingLinkedList extends AbstractLinkedList implements Seriali * @param value value of the new node * @return the newly created node */ - protected Node createNode(Object value) { - Node cachedNode = getNodeFromCache(); + protected Node createNode(E value) { + Node cachedNode = getNodeFromCache(); if (cachedNode == null) { return super.createNode(value); - } else { - cachedNode.setValue(value); - return cachedNode; } + cachedNode.setValue(value); + return cachedNode; } /** @@ -202,7 +201,7 @@ public class NodeCachingLinkedList extends AbstractLinkedList implements Seriali * * @param node the node to remove */ - protected void removeNode(Node node) { + protected void removeNode(Node node) { super.removeNode(node); addNodeToCache(node); } @@ -218,9 +217,9 @@ public class NodeCachingLinkedList extends AbstractLinkedList implements Seriali // {@link AbstractLinkedList.removeAllNodes()} removes the // nodes by removing references directly from {@link #header}. int numberOfNodesToCache = Math.min(size, maximumCacheSize - cacheSize); - Node node = header.next; + Node node = header.next; for (int currentIndex = 0; currentIndex < numberOfNodesToCache; currentIndex++) { - Node oldNode = node; + Node oldNode = node; node = node.next; addNodeToCache(oldNode); } diff --git a/src/java/org/apache/commons/collections/list/SetUniqueList.java b/src/java/org/apache/commons/collections/list/SetUniqueList.java index 402dd31aa..351bf524d 100644 --- a/src/java/org/apache/commons/collections/list/SetUniqueList.java +++ b/src/java/org/apache/commons/collections/list/SetUniqueList.java @@ -51,7 +51,7 @@ import org.apache.commons.collections.set.UnmodifiableSet; * @author Stephen Colebourne * @author Tom Dunham */ -public class SetUniqueList extends AbstractSerializableListDecorator { +public class SetUniqueList extends AbstractSerializableListDecorator { /** Serialization version */ private static final long serialVersionUID = 7196982186153478694L; @@ -59,30 +59,29 @@ public class SetUniqueList extends AbstractSerializableListDecorator { /** * Internal Set to maintain uniqueness. */ - protected final Set set; + protected final Set set; /** * Factory method to create a SetList using the supplied list to retain order. *

* If the list contains duplicates, these are removed (first indexed one kept). * A HashSet is used for the set behaviour. - * + * * @param list the list to decorate, must not be null * @throws IllegalArgumentException if list is null */ - public static SetUniqueList decorate(List list) { + public static SetUniqueList decorate(List list) { if (list == null) { throw new IllegalArgumentException("List must not be null"); } if (list.isEmpty()) { - return new SetUniqueList(list, new HashSet()); - } else { - List temp = new ArrayList(list); - list.clear(); - SetUniqueList sl = new SetUniqueList(list, new HashSet()); - sl.addAll(temp); - return sl; + return new SetUniqueList(list, new HashSet()); } + List temp = new ArrayList(list); + list.clear(); + SetUniqueList sl = new SetUniqueList(list, new HashSet()); + sl.addAll(temp); + return sl; } //----------------------------------------------------------------------- @@ -90,12 +89,12 @@ public class SetUniqueList extends AbstractSerializableListDecorator { * Constructor that wraps (not copies) the List and specifies the set to use. *

* The set and list must both be correctly initialised to the same elements. - * + * * @param set the set to decorate, must not be null * @param list the list to decorate, must not be null * @throws IllegalArgumentException if set or list is null */ - protected SetUniqueList(List list, Set set) { + protected SetUniqueList(List list, Set set) { super(list); if (set == null) { throw new IllegalArgumentException("Set must not be null"); @@ -106,10 +105,10 @@ public class SetUniqueList extends AbstractSerializableListDecorator { //----------------------------------------------------------------------- /** * Gets an unmodifiable view as a Set. - * + * * @return an unmodifiable set view */ - public Set asSet() { + public Set asSet() { return UnmodifiableSet.decorate(set); } @@ -121,11 +120,11 @@ public class SetUniqueList extends AbstractSerializableListDecorator { * The List interface requires that this method returns * true always. However this class may return false * because of the Set behaviour. - * + * * @param object the object to add * @return true if object was added */ - public boolean add(Object object) { + public boolean add(E object) { // gets initial size final int sizeBefore = size(); @@ -142,11 +141,11 @@ public class SetUniqueList extends AbstractSerializableListDecorator { * (Violation) * The List interface makes the assumption that the element is * always inserted. This may not happen with this implementation. - * + * * @param index the index to insert at * @param object the object to add */ - public void add(int index, Object object) { + public void add(int index, E object) { // adds element if it is not contained already if (set.contains(object) == false) { super.add(index, object); @@ -163,11 +162,11 @@ public class SetUniqueList extends AbstractSerializableListDecorator { * (Violation) * The List interface makes the assumption that the elements * are always inserted. This may not happen with this implementation. - * + * * @param coll the collection to add in iterator order * @return true if this collection changed */ - public boolean addAll(Collection coll) { + public boolean addAll(Collection coll) { return addAll(size(), coll); } @@ -181,27 +180,24 @@ public class SetUniqueList extends AbstractSerializableListDecorator { * (Violation) * The List interface makes the assumption that the elements * are always inserted. This may not happen with this implementation. - * + * * @param index the index to insert at * @param coll the collection to add in iterator order * @return true if this collection changed */ - public boolean addAll(int index, Collection coll) { - // gets initial size - final int sizeBefore = size(); - - // adds all elements - for (final Iterator it = coll.iterator(); it.hasNext();) { - int sizeBeforeAddNext = size(); - add(index, it.next()); - // if it was inserted, then increase the target index - if (sizeBeforeAddNext != size()) { - index++; + public boolean addAll(int index, Collection coll) { + HashSet temp = new HashSet(coll); + temp.removeAll(set); + if (temp.isEmpty()) { + return false; + } + for (E e : coll) { + if (temp.contains(e)) { + add(index, e); + index++; } } - - // compares sizes to detect if collection changed - return sizeBefore != size(); + return true; } //----------------------------------------------------------------------- @@ -212,14 +208,14 @@ public class SetUniqueList extends AbstractSerializableListDecorator { * Afterwards, any previous duplicate is removed * If the object is not already in the list then a normal set occurs. * If it is present, then the old version is removed. - * + * * @param index the index to insert at * @param object the object to set * @return the previous object */ - public Object set(int index, Object object) { + public E set(int index, E object) { int pos = indexOf(object); - Object removed = super.set(index, object); + E removed = super.set(index, object); if (pos != -1 && pos != index) { // the object is already in the uniq list @@ -239,19 +235,19 @@ public class SetUniqueList extends AbstractSerializableListDecorator { return result; } - public Object remove(int index) { - Object result = super.remove(index); + public E remove(int index) { + E result = super.remove(index); set.remove(result); return result; } - public boolean removeAll(Collection coll) { + public boolean removeAll(Collection coll) { boolean result = super.removeAll(coll); set.removeAll(coll); return result; } - public boolean retainAll(Collection coll) { + public boolean retainAll(Collection coll) { boolean result = super.retainAll(coll); set.retainAll(coll); return result; @@ -266,39 +262,40 @@ public class SetUniqueList extends AbstractSerializableListDecorator { return set.contains(object); } - public boolean containsAll(Collection coll) { + public boolean containsAll(Collection coll) { return set.containsAll(coll); } - public Iterator iterator() { - return new SetListIterator(super.iterator(), set); + public Iterator iterator() { + return new SetListIterator(super.iterator(), set); } - public ListIterator listIterator() { - return new SetListListIterator(super.listIterator(), set); + public ListIterator listIterator() { + return new SetListListIterator(super.listIterator(), set); } - public ListIterator listIterator(int index) { - return new SetListListIterator(super.listIterator(index), set); + public ListIterator listIterator(int index) { + return new SetListListIterator(super.listIterator(index), set); } - public List subList(int fromIndex, int toIndex) { - List superSubList = super.subList(fromIndex, toIndex); - Set subSet = createSetBasedOnList(set, superSubList); - return new SetUniqueList(superSubList, subSet); + public List subList(int fromIndex, int toIndex) { + List superSubList = super.subList(fromIndex, toIndex); + Set subSet = createSetBasedOnList(set, superSubList); + return new SetUniqueList(superSubList, subSet); } - protected Set createSetBasedOnList(Set set, List list) { - Set subSet = null; - if(set.getClass().equals(HashSet.class)) { - subSet = new HashSet(); + @SuppressWarnings("unchecked") + protected Set createSetBasedOnList(Set set, List list) { + Set subSet = null; + if (set.getClass().equals(HashSet.class)) { + subSet = new HashSet(); } else { try { - subSet = (Set) set.getClass().newInstance(); - } catch(InstantiationException ie) { - subSet = new HashSet(); - } catch(IllegalAccessException iae) { - subSet = new HashSet(); + subSet = (Set) set.getClass().newInstance(); + } catch (InstantiationException ie) { + subSet = new HashSet(); + } catch (IllegalAccessException iae) { + subSet = new HashSet(); } } subSet.addAll(list); @@ -309,17 +306,17 @@ public class SetUniqueList extends AbstractSerializableListDecorator { /** * Inner class iterator. */ - static class SetListIterator extends AbstractIteratorDecorator { - - protected final Set set; - protected Object last = null; - - protected SetListIterator(Iterator it, Set set) { + static class SetListIterator extends AbstractIteratorDecorator { + + protected final Set set; + protected E last = null; + + protected SetListIterator(Iterator it, Set set) { super(it); this.set = set; } - - public Object next() { + + public E next() { last = super.next(); return last; } @@ -330,26 +327,26 @@ public class SetUniqueList extends AbstractSerializableListDecorator { last = null; } } - + /** * Inner class iterator. */ - static class SetListListIterator extends AbstractListIteratorDecorator { - - protected final Set set; - protected Object last = null; - - protected SetListListIterator(ListIterator it, Set set) { + static class SetListListIterator extends AbstractListIteratorDecorator { + + protected final Set set; + protected E last = null; + + protected SetListListIterator(ListIterator it, Set set) { super(it); this.set = set; } - - public Object next() { + + public E next() { last = super.next(); return last; } - public Object previous() { + public E previous() { last = super.previous(); return last; } @@ -360,16 +357,16 @@ public class SetUniqueList extends AbstractSerializableListDecorator { last = null; } - public void add(Object object) { + public void add(E object) { if (set.contains(object) == false) { super.add(object); set.add(object); } } - - public void set(Object object) { + + public void set(E object) { throw new UnsupportedOperationException("ListIterator does not support set"); } } - + } diff --git a/src/java/org/apache/commons/collections/list/TransformedList.java b/src/java/org/apache/commons/collections/list/TransformedList.java index 04dae37a3..e4068cac6 100644 --- a/src/java/org/apache/commons/collections/list/TransformedList.java +++ b/src/java/org/apache/commons/collections/list/TransformedList.java @@ -39,7 +39,7 @@ import org.apache.commons.collections.iterators.AbstractListIteratorDecorator; * * @author Stephen Colebourne */ -public class TransformedList extends TransformedCollection implements List { +public class TransformedList extends TransformedCollection implements List { /** Serialization version */ private static final long serialVersionUID = 1077193035000013141L; @@ -55,8 +55,8 @@ public class TransformedList extends TransformedCollection implements List { * @param transformer the transformer to use for conversion, must not be null * @throws IllegalArgumentException if list or transformer is null */ - public static List decorate(List list, Transformer transformer) { - return new TransformedList(list, transformer); + public static List decorate(List list, Transformer transformer) { + return new TransformedList(list, transformer); } /** @@ -73,13 +73,14 @@ public class TransformedList extends TransformedCollection implements List { * @throws IllegalArgumentException if list or transformer is null * @since Commons Collections 3.3 */ + // TODO: Generics public static List decorateTransform(List list, Transformer transformer) { TransformedList decorated = new TransformedList(list, transformer); if (transformer != null && list != null && list.size() > 0) { Object[] values = list.toArray(); list.clear(); for(int i=0; i list, Transformer transformer) { super(list, transformer); } @@ -105,12 +106,12 @@ public class TransformedList extends TransformedCollection implements List { * * @return the decorated list */ - protected List getList() { - return (List) collection; + protected List getList() { + return (List) collection; } //----------------------------------------------------------------------- - public Object get(int index) { + public E get(int index) { return getList().get(index); } @@ -122,54 +123,54 @@ public class TransformedList extends TransformedCollection implements List { return getList().lastIndexOf(object); } - public Object remove(int index) { + public E remove(int index) { return getList().remove(index); } //----------------------------------------------------------------------- - public void add(int index, Object object) { + public void add(int index, E object) { object = transform(object); getList().add(index, object); } - public boolean addAll(int index, Collection coll) { + public boolean addAll(int index, Collection coll) { coll = transform(coll); return getList().addAll(index, coll); } - public ListIterator listIterator() { + public ListIterator listIterator() { return listIterator(0); } - public ListIterator listIterator(int i) { + public ListIterator listIterator(int i) { return new TransformedListIterator(getList().listIterator(i)); } - public Object set(int index, Object object) { + public E set(int index, E object) { object = transform(object); return getList().set(index, object); } - public List subList(int fromIndex, int toIndex) { - List sub = getList().subList(fromIndex, toIndex); - return new TransformedList(sub, transformer); + public List subList(int fromIndex, int toIndex) { + List sub = getList().subList(fromIndex, toIndex); + return new TransformedList(sub, transformer); } /** * Inner class Iterator for the TransformedList */ - protected class TransformedListIterator extends AbstractListIteratorDecorator { - - protected TransformedListIterator(ListIterator iterator) { + protected class TransformedListIterator extends AbstractListIteratorDecorator { + + protected TransformedListIterator(ListIterator iterator) { super(iterator); } - - public void add(Object object) { + + public void add(E object) { object = transform(object); iterator.add(object); } - - public void set(Object object) { + + public void set(E object) { object = transform(object); iterator.set(object); } diff --git a/src/java/org/apache/commons/collections/list/TreeList.java b/src/java/org/apache/commons/collections/list/TreeList.java index ee4e9292a..b93c4e0ba 100644 --- a/src/java/org/apache/commons/collections/list/TreeList.java +++ b/src/java/org/apache/commons/collections/list/TreeList.java @@ -48,7 +48,7 @@ import org.apache.commons.collections.OrderedIterator; *

* LinkedList is rarely a good choice of implementation. * TreeList is almost always a good replacement for it, although it - * does use sligtly more memory. + * does use slightly more memory. * * @since Commons Collections 3.1 * @version $Revision$ $Date$ @@ -56,14 +56,14 @@ import org.apache.commons.collections.OrderedIterator; * @author Joerg Schmuecker * @author Stephen Colebourne */ -public class TreeList extends AbstractList { +public class TreeList extends AbstractList { // add; toArray; iterator; insert; get; indexOf; remove // TreeList = 1260;7360;3080; 160; 170;3400; 170; // ArrayList = 220;1480;1760; 6870; 50;1540; 7200; // LinkedList = 270;7360;3350;55860;290720;2910;55200; /** The root node in the AVL tree */ - private AVLNode root; + private AVLNode root; /** The current size of the list */ private int size; @@ -78,11 +78,11 @@ public class TreeList extends AbstractList { /** * Constructs a new empty list that copies the specified list. - * + * * @param coll the collection to copy * @throws NullPointerException if the collection is null */ - public TreeList(Collection coll) { + public TreeList(Collection coll) { super(); addAll(coll); } @@ -90,18 +90,18 @@ public class TreeList extends AbstractList { //----------------------------------------------------------------------- /** * Gets the element at the specified index. - * + * * @param index the index to retrieve * @return the element at the specified index */ - public Object get(int index) { + public E get(int index) { checkInterval(index, 0, size() - 1); return root.get(index).getValue(); } /** * Gets the current size of the list. - * + * * @return the current size */ public int size() { @@ -110,40 +110,40 @@ public class TreeList extends AbstractList { /** * Gets an iterator over the list. - * + * * @return an iterator over the list */ - public Iterator iterator() { + public Iterator iterator() { // override to go 75% faster return listIterator(0); } /** * Gets a ListIterator over the list. - * + * * @return the new iterator */ - public ListIterator listIterator() { + public ListIterator listIterator() { // override to go 75% faster return listIterator(0); } /** * Gets a ListIterator over the list. - * + * * @param fromIndex the index to start from * @return the new iterator */ - public ListIterator listIterator(int fromIndex) { + public ListIterator listIterator(int fromIndex) { // override to go 75% faster // cannot use EmptyIterator as iterator.add() must work checkInterval(fromIndex, 0, size()); - return new TreeListIterator(this, fromIndex); + return new TreeListIterator(this, fromIndex); } /** * Searches for the index of an object in the list. - * + * * @return the index of the object, -1 if not found */ public int indexOf(Object object) { @@ -156,7 +156,7 @@ public class TreeList extends AbstractList { /** * Searches for the presence of an object in the list. - * + * * @return true if the object is found */ public boolean contains(Object object) { @@ -165,7 +165,7 @@ public class TreeList extends AbstractList { /** * Converts the list into an array. - * + * * @return the list as an array */ public Object[] toArray() { @@ -180,15 +180,15 @@ public class TreeList extends AbstractList { //----------------------------------------------------------------------- /** * Adds a new element to the list. - * + * * @param index the index to add before * @param obj the element to add */ - public void add(int index, Object obj) { + public void add(int index, E obj) { modCount++; checkInterval(index, 0, size()); if (root == null) { - root = new AVLNode(index, obj, null, null); + root = new AVLNode(index, obj, null, null); } else { root = root.insert(index, obj); } @@ -197,30 +197,30 @@ public class TreeList extends AbstractList { /** * Sets the element at the specified index. - * + * * @param index the index to set * @param obj the object to store at the specified index * @return the previous object at that index * @throws IndexOutOfBoundsException if the index is invalid */ - public Object set(int index, Object obj) { + public E set(int index, E obj) { checkInterval(index, 0, size() - 1); - AVLNode node = root.get(index); - Object result = node.value; + AVLNode node = root.get(index); + E result = node.value; node.setValue(obj); return result; } /** * Removes the element at the specified index. - * + * * @param index the index to remove * @return the previous object at that index */ - public Object remove(int index) { + public E remove(int index) { modCount++; checkInterval(index, 0, size() - 1); - Object result = get(index); + E result = get(index); root = root.remove(index); size--; return result; @@ -238,7 +238,7 @@ public class TreeList extends AbstractList { //----------------------------------------------------------------------- /** * Checks whether the index is valid. - * + * * @param index the index to check * @param startIndex the first allowed index * @param endIndex the last allowed index @@ -263,13 +263,13 @@ public class TreeList extends AbstractList { * The Faedelung calculation stores a flag for both the left and right child * to indicate if they are a child (false) or a link as in linked list (true). */ - static class AVLNode { + static class AVLNode { /** The left child node or the predecessor if {@link #leftIsPrevious}.*/ - private AVLNode left; + private AVLNode left; /** Flag indicating that left reference is not a subtree but the predecessor. */ private boolean leftIsPrevious; /** The right child node or the successor if {@link #rightIsNext}. */ - private AVLNode right; + private AVLNode right; /** Flag indicating that right reference is not a subtree but the successor. */ private boolean rightIsNext; /** How many levels of left/right are below this one. */ @@ -277,17 +277,17 @@ public class TreeList extends AbstractList { /** The relative position, root holds absolute position. */ private int relativePosition; /** The stored element. */ - private Object value; + private E value; /** * Constructs a new node with a relative position. - * + * * @param relativePosition the relative position of the node * @param obj the value for the ndoe * @param rightFollower the node with the value following this one * @param leftFollower the node with the value leading this one */ - private AVLNode(int relativePosition, Object obj, AVLNode rightFollower, AVLNode leftFollower) { + private AVLNode(int relativePosition, E obj, AVLNode rightFollower, AVLNode leftFollower) { this.relativePosition = relativePosition; value = obj; rightIsNext = true; @@ -298,19 +298,19 @@ public class TreeList extends AbstractList { /** * Gets the value. - * + * * @return the value of this node */ - Object getValue() { + E getValue() { return value; } /** * Sets the value. - * + * * @param obj the value to store */ - void setValue(Object obj) { + void setValue(E obj) { this.value = obj; } @@ -318,14 +318,14 @@ public class TreeList extends AbstractList { * Locate the element with the given index relative to the * offset of the parent of this node. */ - AVLNode get(int index) { + AVLNode get(int index) { int indexRelativeToMe = index - relativePosition; if (indexRelativeToMe == 0) { return this; } - AVLNode nextNode = ((indexRelativeToMe < 0) ? getLeftSubTree() : getRightSubTree()); + AVLNode nextNode = ((indexRelativeToMe < 0) ? getLeftSubTree() : getRightSubTree()); if (nextNode == null) { return null; } @@ -353,7 +353,7 @@ public class TreeList extends AbstractList { /** * Stores the node and its children into the array specified. - * + * * @param array the array to be filled * @param index the index of this node */ @@ -369,10 +369,10 @@ public class TreeList extends AbstractList { /** * Gets the next node in the list after this one. - * + * * @return the next node */ - AVLNode next() { + AVLNode next() { if (rightIsNext || right == null) { return right; } @@ -381,10 +381,10 @@ public class TreeList extends AbstractList { /** * Gets the node in the list before this one. - * + * * @return the previous node */ - AVLNode previous() { + AVLNode previous() { if (leftIsPrevious || left == null) { return left; } @@ -392,27 +392,26 @@ public class TreeList extends AbstractList { } /** - * Inserts a node at the position index. - * - * @param index is the index of the position relative to the position of + * Inserts a node at the position index. + * + * @param index is the index of the position relative to the position of * the parent node. * @param obj is the object to be stored in the position. */ - AVLNode insert(int index, Object obj) { + AVLNode insert(int index, E obj) { int indexRelativeToMe = index - relativePosition; if (indexRelativeToMe <= 0) { return insertOnLeft(indexRelativeToMe, obj); - } else { - return insertOnRight(indexRelativeToMe, obj); } + return insertOnRight(indexRelativeToMe, obj); } - private AVLNode insertOnLeft(int indexRelativeToMe, Object obj) { - AVLNode ret = this; + private AVLNode insertOnLeft(int indexRelativeToMe, E obj) { + AVLNode ret = this; if (getLeftSubTree() == null) { - setLeft(new AVLNode(-1, obj, this, left), null); + setLeft(new AVLNode(-1, obj, this, left), null); } else { setLeft(left.insert(indexRelativeToMe, obj), null); } @@ -425,11 +424,11 @@ public class TreeList extends AbstractList { return ret; } - private AVLNode insertOnRight(int indexRelativeToMe, Object obj) { - AVLNode ret = this; + private AVLNode insertOnRight(int indexRelativeToMe, E obj) { + AVLNode ret = this; if (getRightSubTree() == null) { - setRight(new AVLNode(+1, obj, right, this), null); + setRight(new AVLNode(+1, obj, right, this), null); } else { setRight(right.insert(indexRelativeToMe, obj), null); } @@ -445,42 +444,42 @@ public class TreeList extends AbstractList { /** * Gets the left node, returning null if its a faedelung. */ - private AVLNode getLeftSubTree() { + private AVLNode getLeftSubTree() { return (leftIsPrevious ? null : left); } /** * Gets the right node, returning null if its a faedelung. */ - private AVLNode getRightSubTree() { + private AVLNode getRightSubTree() { return (rightIsNext ? null : right); } /** * Gets the rightmost child of this node. - * + * * @return the rightmost child (greatest index) */ - private AVLNode max() { + private AVLNode max() { return (getRightSubTree() == null) ? this : right.max(); } /** * Gets the leftmost child of this node. - * + * * @return the leftmost child (smallest index) */ - private AVLNode min() { + private AVLNode min() { return (getLeftSubTree() == null) ? this : left.min(); } /** * Removes the node at a given position. - * - * @param index is the index of the element to be removed relative to the position of + * + * @param index is the index of the element to be removed relative to the position of * the parent node of the current node. */ - AVLNode remove(int index) { + AVLNode remove(int index) { int indexRelativeToMe = index - relativePosition; if (indexRelativeToMe == 0) { @@ -501,7 +500,7 @@ public class TreeList extends AbstractList { return balance(); } - private AVLNode removeMax() { + private AVLNode removeMax() { if (getRightSubTree() == null) { return removeSelf(); } @@ -513,7 +512,7 @@ public class TreeList extends AbstractList { return balance(); } - private AVLNode removeMin() { + private AVLNode removeMin() { if (getLeftSubTree() == null) { return removeSelf(); } @@ -530,7 +529,7 @@ public class TreeList extends AbstractList { * * @return the node that replaces this one in the parent */ - private AVLNode removeSelf() { + private AVLNode removeSelf() { if (getRightSubTree() == null && getLeftSubTree() == null) { return null; } @@ -549,7 +548,7 @@ public class TreeList extends AbstractList { if (heightRightMinusLeft() > 0) { // more on the right, so delete from the right - AVLNode rightMin = right.min(); + AVLNode rightMin = right.min(); value = rightMin.value; if (leftIsPrevious) { left = rightMin.left; @@ -560,12 +559,12 @@ public class TreeList extends AbstractList { } } else { // more on the left or equal, so delete from the left - AVLNode leftMax = left.max(); + AVLNode leftMax = left.max(); value = leftMax.value; if (rightIsNext) { right = leftMax.right; } - AVLNode leftPrevious = left.left; + AVLNode leftPrevious = left.left; left = left.removeMax(); if (left == null) { // special case where left that was deleted was a double link @@ -585,7 +584,7 @@ public class TreeList extends AbstractList { /** * Balances according to the AVL algorithm. */ - private AVLNode balance() { + private AVLNode balance() { switch (heightRightMinusLeft()) { case 1 : case 0 : @@ -609,7 +608,7 @@ public class TreeList extends AbstractList { /** * Gets the relative position. */ - private int getOffset(AVLNode node) { + private int getOffset(AVLNode node) { if (node == null) { return 0; } @@ -619,7 +618,7 @@ public class TreeList extends AbstractList { /** * Sets the relative position. */ - private int setOffset(AVLNode node, int newOffest) { + private int setOffset(AVLNode node, int newOffest) { if (node == null) { return 0; } @@ -640,7 +639,7 @@ public class TreeList extends AbstractList { /** * Returns the height of the node or -1 if the node is null. */ - private int getHeight(AVLNode node) { + private int getHeight(AVLNode node) { return (node == null ? -1 : node.height); } @@ -651,9 +650,9 @@ public class TreeList extends AbstractList { return getHeight(getRightSubTree()) - getHeight(getLeftSubTree()); } - private AVLNode rotateLeft() { - AVLNode newTop = right; // can't be faedelung! - AVLNode movedNode = getRightSubTree().getLeftSubTree(); + private AVLNode rotateLeft() { + AVLNode newTop = right; // can't be faedelung! + AVLNode movedNode = getRightSubTree().getLeftSubTree(); int newTopPosition = relativePosition + getOffset(newTop); int myNewPosition = -newTop.relativePosition; @@ -668,9 +667,9 @@ public class TreeList extends AbstractList { return newTop; } - private AVLNode rotateRight() { - AVLNode newTop = left; // can't be faedelung - AVLNode movedNode = getLeftSubTree().getRightSubTree(); + private AVLNode rotateRight() { + AVLNode newTop = left; // can't be faedelung + AVLNode movedNode = getLeftSubTree().getRightSubTree(); int newTopPosition = relativePosition + getOffset(newTop); int myNewPosition = -newTop.relativePosition; @@ -691,7 +690,7 @@ public class TreeList extends AbstractList { * @param node the new left subtree node * @param previous the previous node in the linked list */ - private void setLeft(AVLNode node, AVLNode previous) { + private void setLeft(AVLNode node, AVLNode previous) { leftIsPrevious = (node == null); left = (leftIsPrevious ? previous : node); recalcHeight(); @@ -703,7 +702,7 @@ public class TreeList extends AbstractList { * @param node the new left subtree node * @param next the next node in the linked list */ - private void setRight(AVLNode node, AVLNode next) { + private void setRight(AVLNode node, AVLNode next) { rightIsNext = (node == null); right = (rightIsNext ? next : node); recalcHeight(); @@ -747,7 +746,7 @@ public class TreeList extends AbstractList { // } // return count + left.checkLeftSubNode(); // } -// +// // private int checkRightSubNode() { // AVLNode right = getRightSubTree(); // if (right == null) { @@ -773,13 +772,13 @@ public class TreeList extends AbstractList { /** * A list iterator over the linked list. */ - static class TreeListIterator implements ListIterator, OrderedIterator { + static class TreeListIterator implements ListIterator, OrderedIterator { /** The parent list */ - protected final TreeList parent; + protected final TreeList parent; /** * Cache of the next node that will be returned by {@link #next()}. */ - protected AVLNode next; + protected AVLNode next; /** * The index of the next node to be returned. */ @@ -788,7 +787,7 @@ public class TreeList extends AbstractList { * Cache of the last node that was returned by {@link #next()} * or {@link #previous()}. */ - protected AVLNode current; + protected AVLNode current; /** * The index of the last node that was returned. */ @@ -803,11 +802,11 @@ public class TreeList extends AbstractList { /** * Create a ListIterator for a list. - * + * * @param parent the parent list * @param fromIndex the index to start at */ - protected TreeListIterator(TreeList parent, int fromIndex) throws IndexOutOfBoundsException { + protected TreeListIterator(TreeList parent, int fromIndex) throws IndexOutOfBoundsException { super(); this.parent = parent; this.expectedModCount = parent.modCount; @@ -819,7 +818,7 @@ public class TreeList extends AbstractList { /** * Checks the modification count of the list is the value that this * object expects. - * + * * @throws ConcurrentModificationException If the list's modification * count isn't the value that was expected. */ @@ -833,7 +832,7 @@ public class TreeList extends AbstractList { return (nextIndex < parent.size()); } - public Object next() { + public E next() { checkModCount(); if (!hasNext()) { throw new NoSuchElementException("No element at index " + nextIndex + "."); @@ -841,7 +840,7 @@ public class TreeList extends AbstractList { if (next == null) { next = parent.root.get(nextIndex); } - Object value = next.getValue(); + E value = next.getValue(); current = next; currentIndex = nextIndex++; next = next.next(); @@ -852,7 +851,7 @@ public class TreeList extends AbstractList { return (nextIndex > 0); } - public Object previous() { + public E previous() { checkModCount(); if (!hasPrevious()) { throw new NoSuchElementException("Already at start of list."); @@ -862,7 +861,7 @@ public class TreeList extends AbstractList { } else { next = next.previous(); } - Object value = next.getValue(); + E value = next.getValue(); current = next; currentIndex = --nextIndex; return value; @@ -895,7 +894,7 @@ public class TreeList extends AbstractList { expectedModCount++; } - public void set(Object obj) { + public void set(E obj) { checkModCount(); if (current == null) { throw new IllegalStateException(); @@ -903,7 +902,7 @@ public class TreeList extends AbstractList { current.setValue(obj); } - public void add(Object obj) { + public void add(E obj) { checkModCount(); parent.add(nextIndex, obj); current = null; diff --git a/src/java/org/apache/commons/collections/map/AbstractHashedMap.java b/src/java/org/apache/commons/collections/map/AbstractHashedMap.java index faff56fe8..fd646ad47 100644 --- a/src/java/org/apache/commons/collections/map/AbstractHashedMap.java +++ b/src/java/org/apache/commons/collections/map/AbstractHashedMap.java @@ -59,15 +59,15 @@ import org.apache.commons.collections.iterators.EmptyMapIterator; * @author Stephen Colebourne * @author Christian Siefkes */ -public class AbstractHashedMap extends AbstractMap implements IterableMap { - +public class AbstractHashedMap extends AbstractMap implements IterableMap { + protected static final String NO_NEXT_ENTRY = "No next() entry in the iteration"; protected static final String NO_PREVIOUS_ENTRY = "No previous() entry in the iteration"; protected static final String REMOVE_INVALID = "remove() can only be called once after next()"; protected static final String GETKEY_INVALID = "getKey() can only be called after next() and before remove()"; protected static final String GETVALUE_INVALID = "getValue() can only be called after next() and before remove()"; protected static final String SETVALUE_INVALID = "setValue() can only be called after next() and before remove()"; - + /** The default capacity to use */ protected static final int DEFAULT_CAPACITY = 16; /** The default threshold to use */ @@ -78,23 +78,23 @@ public class AbstractHashedMap extends AbstractMap implements IterableMap { protected static final int MAXIMUM_CAPACITY = 1 << 30; /** An object for masking null */ protected static final Object NULL = new Object(); - + /** Load factor, normally 0.75 */ protected transient float loadFactor; /** The size of the map */ protected transient int size; /** Map entries */ - protected transient HashEntry[] data; + protected transient HashEntry[] data; /** Size at which to rehash */ protected transient int threshold; /** Modification count for iterators */ protected transient int modCount; /** Entry set */ - protected transient EntrySet entrySet; + protected transient EntrySet entrySet; /** Key set */ - protected transient KeySet keySet; + protected transient KeySet keySet; /** Values */ - protected transient Values values; + protected transient Values values; /** * Constructor only used in deserialization, do not use otherwise. @@ -105,11 +105,12 @@ public class AbstractHashedMap extends AbstractMap implements IterableMap { /** * Constructor which performs no validation on the passed in parameters. - * + * * @param initialCapacity the initial capacity, must be a power of two * @param loadFactor the load factor, must be > 0.0f and generally < 1.0f * @param threshold the threshold, must be sensible */ + @SuppressWarnings("unchecked") protected AbstractHashedMap(int initialCapacity, float loadFactor, int threshold) { super(); this.loadFactor = loadFactor; @@ -120,7 +121,7 @@ public class AbstractHashedMap extends AbstractMap implements IterableMap { /** * Constructs a new, empty map with the specified initial capacity and - * default load factor. + * default load factor. * * @param initialCapacity the initial capacity * @throws IllegalArgumentException if the initial capacity is less than one @@ -131,13 +132,14 @@ public class AbstractHashedMap extends AbstractMap implements IterableMap { /** * Constructs a new, empty map with the specified initial capacity and - * load factor. + * load factor. * * @param initialCapacity the initial capacity * @param loadFactor the load factor * @throws IllegalArgumentException if the initial capacity is less than one * @throws IllegalArgumentException if the load factor is less than or equal to zero */ + @SuppressWarnings("unchecked") protected AbstractHashedMap(int initialCapacity, float loadFactor) { super(); if (initialCapacity < 1) { @@ -159,7 +161,7 @@ public class AbstractHashedMap extends AbstractMap implements IterableMap { * @param map the map to copy * @throws NullPointerException if the map is null */ - protected AbstractHashedMap(Map map) { + protected AbstractHashedMap(Map map) { this(Math.max(2 * map.size(), DEFAULT_CAPACITY), DEFAULT_LOAD_FACTOR); _putAll(map); } @@ -173,14 +175,14 @@ public class AbstractHashedMap extends AbstractMap implements IterableMap { //----------------------------------------------------------------------- /** * Gets the value mapped to the key specified. - * + * * @param key the key * @return the mapped value, null if no match */ - public Object get(Object key) { + public V get(Object key) { key = convertKey(key); int hashCode = hash(key); - HashEntry entry = data[hashIndex(hashCode, data.length)]; // no local for hash index + HashEntry entry = data[hashIndex(hashCode, data.length)]; // no local for hash index while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(key, entry.key)) { return entry.getValue(); @@ -192,7 +194,7 @@ public class AbstractHashedMap extends AbstractMap implements IterableMap { /** * Gets the size of the map. - * + * * @return the size */ public int size() { @@ -201,7 +203,7 @@ public class AbstractHashedMap extends AbstractMap implements IterableMap { /** * Checks whether the map is currently empty. - * + * * @return true if the map is currently size zero */ public boolean isEmpty() { @@ -211,14 +213,14 @@ public class AbstractHashedMap extends AbstractMap implements IterableMap { //----------------------------------------------------------------------- /** * Checks whether the map contains the specified key. - * + * * @param key the key to search for * @return true if the map contains the key */ public boolean containsKey(Object key) { key = convertKey(key); int hashCode = hash(key); - HashEntry entry = data[hashIndex(hashCode, data.length)]; // no local for hash index + HashEntry entry = data[hashIndex(hashCode, data.length)]; // no local for hash index while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(key, entry.key)) { return true; @@ -230,14 +232,14 @@ public class AbstractHashedMap extends AbstractMap implements IterableMap { /** * Checks whether the map contains the specified value. - * + * * @param value the value to search for * @return true if the map contains the value */ public boolean containsValue(Object value) { if (value == null) { for (int i = 0, isize = data.length; i < isize; i++) { - HashEntry entry = data[i]; + HashEntry entry = data[i]; while (entry != null) { if (entry.getValue() == null) { return true; @@ -247,7 +249,7 @@ public class AbstractHashedMap extends AbstractMap implements IterableMap { } } else { for (int i = 0, isize = data.length; i < isize; i++) { - HashEntry entry = data[i]; + HashEntry entry = data[i]; while (entry != null) { if (isEqualValue(value, entry.getValue())) { return true; @@ -262,25 +264,25 @@ public class AbstractHashedMap extends AbstractMap implements IterableMap { //----------------------------------------------------------------------- /** * Puts a key-value mapping into this map. - * + * * @param key the key to add * @param value the value to add * @return the value previously mapped to this key, null if none */ - public Object put(Object key, Object value) { - key = convertKey(key); - int hashCode = hash(key); + public V put(K key, V value) { + Object convertedKey = convertKey(key); + int hashCode = hash(convertedKey); int index = hashIndex(hashCode, data.length); - HashEntry entry = data[index]; + HashEntry entry = data[index]; while (entry != null) { - if (entry.hashCode == hashCode && isEqualKey(key, entry.key)) { - Object oldValue = entry.getValue(); + if (entry.hashCode == hashCode && isEqualKey(convertedKey, entry.key)) { + V oldValue = entry.getValue(); updateEntry(entry, value); return oldValue; } entry = entry.next; } - + addMapping(index, hashCode, key, value); return null; } @@ -290,11 +292,11 @@ public class AbstractHashedMap extends AbstractMap implements IterableMap { *

* This implementation iterates around the specified map and * uses {@link #put(Object, Object)}. - * + * * @param map the map to add * @throws NullPointerException if the map is null */ - public void putAll(Map map) { + public void putAll(Map map) { _putAll(map); } @@ -310,34 +312,33 @@ public class AbstractHashedMap extends AbstractMap implements IterableMap { * @param map the map to add * @throws NullPointerException if the map is null */ - private void _putAll(Map map) { + private void _putAll(Map map) { int mapSize = map.size(); if (mapSize == 0) { return; } int newSize = (int) ((size + mapSize) / loadFactor + 1); ensureCapacity(calculateNewCapacity(newSize)); - for (Iterator it = map.entrySet().iterator(); it.hasNext();) { - Map.Entry entry = (Map.Entry) it.next(); + for (Map.Entry entry: map.entrySet()) { put(entry.getKey(), entry.getValue()); } } /** * Removes the specified mapping from this map. - * + * * @param key the mapping to remove * @return the value mapped to the removed key, null if key not in map */ - public Object remove(Object key) { + public V remove(Object key) { key = convertKey(key); int hashCode = hash(key); int index = hashIndex(hashCode, data.length); - HashEntry entry = data[index]; - HashEntry previous = null; + HashEntry entry = data[index]; + HashEntry previous = null; while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(key, entry.key)) { - Object oldValue = entry.getValue(); + V oldValue = entry.getValue(); removeMapping(entry, index, previous); return oldValue; } @@ -353,7 +354,7 @@ public class AbstractHashedMap extends AbstractMap implements IterableMap { */ public void clear() { modCount++; - HashEntry[] data = this.data; + HashEntry[] data = this.data; for (int i = data.length - 1; i >= 0; i--) { data[i] = null; } @@ -368,19 +369,19 @@ public class AbstractHashedMap extends AbstractMap implements IterableMap { *

* The reverse conversion can be changed, if required, by overriding the * getKey() method in the hash entry. - * + * * @param key the key convert * @return the converted key */ protected Object convertKey(Object key) { return (key == null ? NULL : key); } - + /** * Gets the hash code for the key specified. * This implementation uses the additional hashing routine from JDK1.4. * Subclasses can override this to return alternate hash codes. - * + * * @param key the key to get a hash code for * @return the hash code */ @@ -393,12 +394,12 @@ public class AbstractHashedMap extends AbstractMap implements IterableMap { h ^= (h >>> 10); return h; } - + /** * Compares two keys, in internal converted form, to see if they are equal. * This implementation uses the equals method and assumes neither key is null. * Subclasses can override this to match differently. - * + * * @param key1 the first key to compare passed in from outside * @param key2 the second key extracted from the entry via entry.key * @return true if equal @@ -406,12 +407,12 @@ public class AbstractHashedMap extends AbstractMap implements IterableMap { protected boolean isEqualKey(Object key1, Object key2) { return (key1 == key2 || key1.equals(key2)); } - + /** * Compares two values, in external form, to see if they are equal. * This implementation uses the equals method and assumes neither value is null. * Subclasses can override this to match differently. - * + * * @param value1 the first value to compare passed in from outside * @param value2 the second value extracted from the entry via getValue() * @return true if equal @@ -419,12 +420,12 @@ public class AbstractHashedMap extends AbstractMap implements IterableMap { protected boolean isEqualValue(Object value1, Object value2) { return (value1 == value2 || value1.equals(value2)); } - + /** * Gets the index into the data storage for the hashCode specified. * This implementation uses the least significant bits of the hashCode. * Subclasses can override this to return alternate bucketing. - * + * * @param hashCode the hash code to use * @param dataSize the size of the data to pick a bucket from * @return the bucket index @@ -432,7 +433,7 @@ public class AbstractHashedMap extends AbstractMap implements IterableMap { protected int hashIndex(int hashCode, int dataSize) { return hashCode & (dataSize - 1); } - + //----------------------------------------------------------------------- /** * Gets the entry mapped to the key specified. @@ -440,14 +441,14 @@ public class AbstractHashedMap extends AbstractMap implements IterableMap { * This method exists for subclasses that may need to perform a multi-step * process accessing the entry. The public methods in this class don't use this * method to gain a small performance boost. - * + * * @param key the key * @return the entry, null if no match */ - protected HashEntry getEntry(Object key) { + protected HashEntry getEntry(Object key) { key = convertKey(key); int hashCode = hash(key); - HashEntry entry = data[hashIndex(hashCode, data.length)]; // no local for hash index + HashEntry entry = data[hashIndex(hashCode, data.length)]; // no local for hash index while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(key, entry.key)) { return entry; @@ -463,33 +464,33 @@ public class AbstractHashedMap extends AbstractMap implements IterableMap { *

* This implementation calls setValue() on the entry. * Subclasses could override to handle changes to the map. - * + * * @param entry the entry to update * @param newValue the new value to store */ - protected void updateEntry(HashEntry entry, Object newValue) { + protected void updateEntry(HashEntry entry, V newValue) { entry.setValue(newValue); } - + /** * Reuses an existing key-value mapping, storing completely new data. *

* This implementation sets all the data fields on the entry. * Subclasses could populate additional entry fields. - * + * * @param entry the entry to update, not null * @param hashIndex the index in the data array * @param hashCode the hash code of the key to add * @param key the key to add * @param value the value to add */ - protected void reuseEntry(HashEntry entry, int hashIndex, int hashCode, Object key, Object value) { + protected void reuseEntry(HashEntry entry, int hashIndex, int hashCode, K key, V value) { entry.next = data[hashIndex]; entry.hashCode = hashCode; entry.key = key; entry.value = value; } - + //----------------------------------------------------------------------- /** * Adds a new key-value mapping into this map. @@ -498,37 +499,37 @@ public class AbstractHashedMap extends AbstractMap implements IterableMap { * and checkCapacity(). * It also handles changes to modCount and size. * Subclasses could override to fully control adds to the map. - * + * * @param hashIndex the index into the data array to store at * @param hashCode the hash code of the key to add * @param key the key to add * @param value the value to add */ - protected void addMapping(int hashIndex, int hashCode, Object key, Object value) { + protected void addMapping(int hashIndex, int hashCode, K key, V value) { modCount++; - HashEntry entry = createEntry(data[hashIndex], hashCode, key, value); + HashEntry entry = createEntry(data[hashIndex], hashCode, key, value); addEntry(entry, hashIndex); size++; checkCapacity(); } - + /** * Creates an entry to store the key-value data. *

* This implementation creates a new HashEntry instance. * Subclasses can override this to return a different storage class, * or implement caching. - * + * * @param next the next entry in sequence * @param hashCode the hash code to use * @param key the key to store * @param value the value to store * @return the newly created entry */ - protected HashEntry createEntry(HashEntry next, int hashCode, Object key, Object value) { - return new HashEntry(next, hashCode, key, value); + protected HashEntry createEntry(HashEntry next, int hashCode, K key, V value) { + return new HashEntry(next, hashCode, convertKey(key), value); } - + /** * Adds an entry into this map. *

@@ -538,10 +539,10 @@ public class AbstractHashedMap extends AbstractMap implements IterableMap { * @param entry the entry to add * @param hashIndex the index into the data array to store at */ - protected void addEntry(HashEntry entry, int hashIndex) { + protected void addEntry(HashEntry entry, int hashIndex) { data[hashIndex] = entry; } - + //----------------------------------------------------------------------- /** * Removes a mapping from the map. @@ -549,51 +550,51 @@ public class AbstractHashedMap extends AbstractMap implements IterableMap { * This implementation calls removeEntry() and destroyEntry(). * It also handles changes to modCount and size. * Subclasses could override to fully control removals from the map. - * + * * @param entry the entry to remove * @param hashIndex the index into the data structure * @param previous the previous entry in the chain */ - protected void removeMapping(HashEntry entry, int hashIndex, HashEntry previous) { + protected void removeMapping(HashEntry entry, int hashIndex, HashEntry previous) { modCount++; removeEntry(entry, hashIndex, previous); size--; destroyEntry(entry); } - + /** * Removes an entry from the chain stored in a particular index. *

* This implementation removes the entry from the data storage table. * The size is not updated. * Subclasses could override to handle changes to the map. - * + * * @param entry the entry to remove * @param hashIndex the index into the data structure * @param previous the previous entry in the chain */ - protected void removeEntry(HashEntry entry, int hashIndex, HashEntry previous) { + protected void removeEntry(HashEntry entry, int hashIndex, HashEntry previous) { if (previous == null) { data[hashIndex] = entry.next; } else { previous.next = entry.next; } } - + /** * Kills an entry ready for the garbage collector. *

* This implementation prepares the HashEntry for garbage collection. * Subclasses can override this to implement caching (override clear as well). - * + * * @param entry the entry to destroy */ - protected void destroyEntry(HashEntry entry) { + protected void destroyEntry(HashEntry entry) { entry.next = null; entry.key = null; entry.value = null; } - + //----------------------------------------------------------------------- /** * Checks the capacity of the map and enlarges it if necessary. @@ -608,12 +609,13 @@ public class AbstractHashedMap extends AbstractMap implements IterableMap { } } } - + /** * Changes the size of the data structure to the capacity proposed. - * + * * @param newCapacity the new capacity of the array (a power of two, less or equal to max) */ + @SuppressWarnings("unchecked") protected void ensureCapacity(int newCapacity) { int oldCapacity = data.length; if (newCapacity <= oldCapacity) { @@ -633,7 +635,7 @@ public class AbstractHashedMap extends AbstractMap implements IterableMap { oldEntries[i] = null; // gc do { HashEntry next = entry.next; - int index = hashIndex(entry.hashCode, newCapacity); + int index = hashIndex(entry.hashCode, newCapacity); entry.next = newEntries[index]; newEntries[index] = entry; entry = next; @@ -648,7 +650,7 @@ public class AbstractHashedMap extends AbstractMap implements IterableMap { /** * Calculates the new capacity of the map. * This implementation normalizes the capacity to a power of two. - * + * * @param proposedCapacity the proposed capacity * @return the normalized new capacity */ @@ -666,11 +668,11 @@ public class AbstractHashedMap extends AbstractMap implements IterableMap { } return newCapacity; } - + /** * Calculates the new threshold of the map, where it will be resized. * This implementation uses the load factor. - * + * * @param newCapacity the new capacity * @param factor the load factor * @return the new resize threshold @@ -678,60 +680,60 @@ public class AbstractHashedMap extends AbstractMap implements IterableMap { protected int calculateThreshold(int newCapacity, float factor) { return (int) (newCapacity * factor); } - + //----------------------------------------------------------------------- /** * Gets the next field from a HashEntry. * Used in subclasses that have no visibility of the field. - * + * * @param entry the entry to query, must not be null * @return the next field of the entry * @throws NullPointerException if the entry is null * @since Commons Collections 3.1 */ - protected HashEntry entryNext(HashEntry entry) { + protected HashEntry entryNext(HashEntry entry) { return entry.next; } - + /** * Gets the hashCode field from a HashEntry. * Used in subclasses that have no visibility of the field. - * + * * @param entry the entry to query, must not be null * @return the hashCode field of the entry * @throws NullPointerException if the entry is null * @since Commons Collections 3.1 */ - protected int entryHashCode(HashEntry entry) { + protected int entryHashCode(HashEntry entry) { return entry.hashCode; } - + /** * Gets the key field from a HashEntry. * Used in subclasses that have no visibility of the field. - * + * * @param entry the entry to query, must not be null * @return the key field of the entry * @throws NullPointerException if the entry is null * @since Commons Collections 3.1 */ - protected Object entryKey(HashEntry entry) { - return entry.key; + protected K entryKey(HashEntry entry) { + return entry.getKey(); } - + /** * Gets the value field from a HashEntry. * Used in subclasses that have no visibility of the field. - * + * * @param entry the entry to query, must not be null * @return the value field of the entry * @throws NullPointerException if the entry is null * @since Commons Collections 3.1 */ - protected Object entryValue(HashEntry entry) { - return entry.value; + protected V entryValue(HashEntry entry) { + return entry.getValue(); } - + //----------------------------------------------------------------------- /** * Gets an iterator over the map. @@ -741,90 +743,90 @@ public class AbstractHashedMap extends AbstractMap implements IterableMap { * methods to get the key and value, and set the value. * It avoids the need to create an entrySet/keySet/values object. * It also avoids creating the Map.Entry object. - * + * * @return the map iterator */ - public MapIterator mapIterator() { + public MapIterator mapIterator() { if (size == 0) { - return EmptyMapIterator.INSTANCE; + return EmptyMapIterator.getInstance(); } - return new HashMapIterator(this); + return new HashMapIterator(this); } /** * MapIterator implementation. */ - protected static class HashMapIterator extends HashIterator implements MapIterator { - - protected HashMapIterator(AbstractHashedMap parent) { + protected static class HashMapIterator extends HashIterator implements MapIterator { + + protected HashMapIterator(AbstractHashedMap parent) { super(parent); } - public Object next() { + public K next() { return super.nextEntry().getKey(); } - public Object getKey() { - HashEntry current = currentEntry(); + public K getKey() { + HashEntry current = currentEntry(); if (current == null) { throw new IllegalStateException(AbstractHashedMap.GETKEY_INVALID); } return current.getKey(); } - public Object getValue() { - HashEntry current = currentEntry(); + public V getValue() { + HashEntry current = currentEntry(); if (current == null) { throw new IllegalStateException(AbstractHashedMap.GETVALUE_INVALID); } return current.getValue(); } - public Object setValue(Object value) { - HashEntry current = currentEntry(); + public V setValue(V value) { + HashEntry current = currentEntry(); if (current == null) { throw new IllegalStateException(AbstractHashedMap.SETVALUE_INVALID); } return current.setValue(value); } } - - //----------------------------------------------------------------------- + + //----------------------------------------------------------------------- /** * Gets the entrySet view of the map. * Changes made to the view affect this map. * To simply iterate through the entries, use {@link #mapIterator()}. - * + * * @return the entrySet view */ - public Set entrySet() { + public Set> entrySet() { if (entrySet == null) { - entrySet = new EntrySet(this); + entrySet = new EntrySet(this); } return entrySet; } - + /** * Creates an entry set iterator. * Subclasses can override this to return iterators with different properties. - * + * * @return the entrySet iterator */ - protected Iterator createEntrySetIterator() { + protected Iterator> createEntrySetIterator() { if (size() == 0) { - return EmptyIterator.INSTANCE; + return EmptyIterator.>getInstance(); } - return new EntrySetIterator(this); + return new EntrySetIterator(this); } /** * EntrySet implementation. */ - protected static class EntrySet extends AbstractSet { + protected static class EntrySet extends AbstractSet> { /** The parent map */ - protected final AbstractHashedMap parent; - - protected EntrySet(AbstractHashedMap parent) { + protected final AbstractHashedMap parent; + + protected EntrySet(AbstractHashedMap parent) { super(); this.parent = parent; } @@ -832,20 +834,20 @@ public class AbstractHashedMap extends AbstractMap implements IterableMap { public int size() { return parent.size(); } - + public void clear() { parent.clear(); } - + public boolean contains(Object entry) { if (entry instanceof Map.Entry) { - Map.Entry e = (Map.Entry) entry; - Entry match = parent.getEntry(e.getKey()); + Map.Entry e = (Map.Entry) entry; + Entry match = parent.getEntry(e.getKey()); return (match != null && match.equals(e)); } return false; } - + public boolean remove(Object obj) { if (obj instanceof Map.Entry == false) { return false; @@ -853,13 +855,12 @@ public class AbstractHashedMap extends AbstractMap implements IterableMap { if (contains(obj) == false) { return false; } - Map.Entry entry = (Map.Entry) obj; - Object key = entry.getKey(); - parent.remove(key); + Map.Entry entry = (Map.Entry) obj; + parent.remove(entry.getKey()); return true; } - public Iterator iterator() { + public Iterator> iterator() { return parent.createEntrySetIterator(); } } @@ -867,28 +868,28 @@ public class AbstractHashedMap extends AbstractMap implements IterableMap { /** * EntrySet iterator. */ - protected static class EntrySetIterator extends HashIterator { - - protected EntrySetIterator(AbstractHashedMap parent) { + protected static class EntrySetIterator extends HashIterator implements Iterator> { + + protected EntrySetIterator(AbstractHashedMap parent) { super(parent); } - public Object next() { + public Map.Entry next() { return super.nextEntry(); } } - //----------------------------------------------------------------------- + //----------------------------------------------------------------------- /** * Gets the keySet view of the map. * Changes made to the view affect this map. * To simply iterate through the keys, use {@link #mapIterator()}. - * + * * @return the keySet view */ - public Set keySet() { + public Set keySet() { if (keySet == null) { - keySet = new KeySet(this); + keySet = new KeySet(this); } return keySet; } @@ -896,24 +897,24 @@ public class AbstractHashedMap extends AbstractMap implements IterableMap { /** * Creates a key set iterator. * Subclasses can override this to return iterators with different properties. - * + * * @return the keySet iterator */ - protected Iterator createKeySetIterator() { + protected Iterator createKeySetIterator() { if (size() == 0) { - return EmptyIterator.INSTANCE; + return EmptyIterator.getInstance(); } - return new KeySetIterator(this); + return new KeySetIterator(this); } /** * KeySet implementation. */ - protected static class KeySet extends AbstractSet { + protected static class KeySet extends AbstractSet { /** The parent map */ - protected final AbstractHashedMap parent; - - protected KeySet(AbstractHashedMap parent) { + protected final AbstractHashedMap parent; + + protected KeySet(AbstractHashedMap parent) { super(); this.parent = parent; } @@ -921,22 +922,22 @@ public class AbstractHashedMap extends AbstractMap implements IterableMap { public int size() { return parent.size(); } - + public void clear() { parent.clear(); } - + public boolean contains(Object key) { return parent.containsKey(key); } - + public boolean remove(Object key) { boolean result = parent.containsKey(key); parent.remove(key); return result; } - public Iterator iterator() { + public Iterator iterator() { return parent.createKeySetIterator(); } } @@ -944,28 +945,29 @@ public class AbstractHashedMap extends AbstractMap implements IterableMap { /** * KeySet iterator. */ - protected static class KeySetIterator extends EntrySetIterator { - - protected KeySetIterator(AbstractHashedMap parent) { - super(parent); + protected static class KeySetIterator extends HashIterator implements Iterator { + + @SuppressWarnings("unchecked") + protected KeySetIterator(AbstractHashedMap parent) { + super((AbstractHashedMap) parent); } - public Object next() { + public K next() { return super.nextEntry().getKey(); } } - - //----------------------------------------------------------------------- + + //----------------------------------------------------------------------- /** * Gets the values view of the map. * Changes made to the view affect this map. * To simply iterate through the values, use {@link #mapIterator()}. - * + * * @return the values view */ - public Collection values() { + public Collection values() { if (values == null) { - values = new Values(this); + values = new Values(this); } return values; } @@ -973,24 +975,24 @@ public class AbstractHashedMap extends AbstractMap implements IterableMap { /** * Creates a values iterator. * Subclasses can override this to return iterators with different properties. - * + * * @return the values iterator */ - protected Iterator createValuesIterator() { + protected Iterator createValuesIterator() { if (size() == 0) { - return EmptyIterator.INSTANCE; + return EmptyIterator.getInstance(); } - return new ValuesIterator(this); + return new ValuesIterator(this); } /** * Values implementation. */ - protected static class Values extends AbstractCollection { + protected static class Values extends AbstractCollection { /** The parent map */ - protected final AbstractHashedMap parent; - - protected Values(AbstractHashedMap parent) { + protected final AbstractHashedMap parent; + + protected Values(AbstractHashedMap parent) { super(); this.parent = parent; } @@ -998,16 +1000,16 @@ public class AbstractHashedMap extends AbstractMap implements IterableMap { public int size() { return parent.size(); } - + public void clear() { parent.clear(); } - + public boolean contains(Object value) { return parent.containsValue(value); } - - public Iterator iterator() { + + public Iterator iterator() { return parent.createValuesIterator(); } } @@ -1015,17 +1017,18 @@ public class AbstractHashedMap extends AbstractMap implements IterableMap { /** * Values iterator. */ - protected static class ValuesIterator extends HashIterator { - - protected ValuesIterator(AbstractHashedMap parent) { - super(parent); + protected static class ValuesIterator extends HashIterator implements Iterator { + + @SuppressWarnings("unchecked") + protected ValuesIterator(AbstractHashedMap parent) { + super((AbstractHashedMap) parent); } - public Object next() { + public V next() { return super.nextEntry().getValue(); } } - + //----------------------------------------------------------------------- /** * HashEntry used to store the data. @@ -1035,38 +1038,44 @@ public class AbstractHashedMap extends AbstractMap implements IterableMap { * The entryXxx() methods on AbstractHashedMap exist * to provide the necessary access. */ - protected static class HashEntry implements Map.Entry, KeyValue { + protected static class HashEntry implements Map.Entry, KeyValue { /** The next entry in the hash chain */ - protected HashEntry next; + protected HashEntry next; /** The hash code of the key */ protected int hashCode; /** The key */ protected Object key; /** The value */ protected Object value; - - protected HashEntry(HashEntry next, int hashCode, Object key, Object value) { + + protected HashEntry(HashEntry next, int hashCode, Object key, V value) { super(); this.next = next; this.hashCode = hashCode; this.key = key; this.value = value; } - - public Object getKey() { - return (key == NULL ? null : key); + + @SuppressWarnings("unchecked") + public K getKey() { + if (key == NULL) { + return null; + } + return (K) key; } - - public Object getValue() { - return value; + + @SuppressWarnings("unchecked") + public V getValue() { + return (V) value; } - - public Object setValue(Object value) { + + @SuppressWarnings("unchecked") + public V setValue(V value) { Object old = this.value; this.value = value; - return old; + return (V) old; } - + public boolean equals(Object obj) { if (obj == this) { return true; @@ -1074,44 +1083,44 @@ public class AbstractHashedMap extends AbstractMap implements IterableMap { if (obj instanceof Map.Entry == false) { return false; } - Map.Entry other = (Map.Entry) obj; + Map.Entry other = (Map.Entry) obj; return (getKey() == null ? other.getKey() == null : getKey().equals(other.getKey())) && (getValue() == null ? other.getValue() == null : getValue().equals(other.getValue())); } - + public int hashCode() { return (getKey() == null ? 0 : getKey().hashCode()) ^ - (getValue() == null ? 0 : getValue().hashCode()); + (getValue() == null ? 0 : getValue().hashCode()); } - + public String toString() { return new StringBuffer().append(getKey()).append('=').append(getValue()).toString(); } } - + /** * Base Iterator */ - protected static abstract class HashIterator implements Iterator { - + protected static abstract class HashIterator { + /** The parent map */ - protected final AbstractHashedMap parent; + protected final AbstractHashedMap parent; /** The current index into the array of buckets */ protected int hashIndex; /** The last returned entry */ - protected HashEntry last; + protected HashEntry last; /** The next entry */ - protected HashEntry next; + protected HashEntry next; /** The modification count expected */ protected int expectedModCount; - - protected HashIterator(AbstractHashedMap parent) { + + protected HashIterator(AbstractHashedMap parent) { super(); this.parent = parent; - HashEntry[] data = parent.data; + HashEntry[] data = parent.data; int i = data.length; - HashEntry next = null; + HashEntry next = null; while (i > 0 && next == null) { next = data[--i]; } @@ -1124,17 +1133,17 @@ public class AbstractHashedMap extends AbstractMap implements IterableMap { return (next != null); } - protected HashEntry nextEntry() { + protected HashEntry nextEntry() { if (parent.modCount != expectedModCount) { throw new ConcurrentModificationException(); } - HashEntry newCurrent = next; + HashEntry newCurrent = next; if (newCurrent == null) { throw new NoSuchElementException(AbstractHashedMap.NO_NEXT_ENTRY); } - HashEntry[] data = parent.data; + HashEntry[] data = parent.data; int i = hashIndex; - HashEntry n = newCurrent.next; + HashEntry n = newCurrent.next; while (n == null && i > 0) { n = data[--i]; } @@ -1144,10 +1153,10 @@ public class AbstractHashedMap extends AbstractMap implements IterableMap { return newCurrent; } - protected HashEntry currentEntry() { + protected HashEntry currentEntry() { return last; } - + public void remove() { if (last == null) { throw new IllegalStateException(AbstractHashedMap.REMOVE_INVALID); @@ -1163,12 +1172,11 @@ public class AbstractHashedMap extends AbstractMap implements IterableMap { public String toString() { if (last != null) { return "Iterator[" + last.getKey() + "=" + last.getValue() + "]"; - } else { - return "Iterator[]"; } + return "Iterator[]"; } } - + //----------------------------------------------------------------------- /** * Writes the map data to the stream. This method must be overridden if a @@ -1186,14 +1194,14 @@ public class AbstractHashedMap extends AbstractMap implements IterableMap { * Subclasses may override if they have a specific field that must be present * on read before this implementation will work. Generally, the read determines * what must be serialized here, if anything. - * + * * @param out the output stream */ protected void doWriteObject(ObjectOutputStream out) throws IOException { out.writeFloat(loadFactor); out.writeInt(data.length); out.writeInt(size); - for (MapIterator it = mapIterator(); it.hasNext();) { + for (MapIterator it = mapIterator(); it.hasNext();) { out.writeObject(it.next()); out.writeObject(it.getValue()); } @@ -1214,9 +1222,10 @@ public class AbstractHashedMap extends AbstractMap implements IterableMap { *

* Subclasses may override if the subclass has a specific field that must be present * before put() or calculateThreshold() will work correctly. - * + * * @param in the input stream */ + @SuppressWarnings("unchecked") protected void doReadObject(ObjectInputStream in) throws IOException, ClassNotFoundException { loadFactor = in.readFloat(); int capacity = in.readInt(); @@ -1225,12 +1234,12 @@ public class AbstractHashedMap extends AbstractMap implements IterableMap { threshold = calculateThreshold(capacity, loadFactor); data = new HashEntry[capacity]; for (int i = 0; i < size; i++) { - Object key = in.readObject(); - Object value = in.readObject(); + K key = (K) in.readObject(); + V value = (V) in.readObject(); put(key, value); } } - + //----------------------------------------------------------------------- /** * Clones the map without cloning the keys or values. @@ -1240,9 +1249,10 @@ public class AbstractHashedMap extends AbstractMap implements IterableMap { * * @return a shallow clone */ - protected Object clone() { + @SuppressWarnings("unchecked") + protected AbstractHashedMap clone() { try { - AbstractHashedMap cloned = (AbstractHashedMap) super.clone(); + AbstractHashedMap cloned = (AbstractHashedMap) super.clone(); cloned.data = new HashEntry[data.length]; cloned.entrySet = null; cloned.keySet = null; @@ -1252,18 +1262,18 @@ public class AbstractHashedMap extends AbstractMap implements IterableMap { cloned.init(); cloned.putAll(this); return cloned; - } catch (CloneNotSupportedException ex) { return null; // should never happen } } - + /** * Compares this map with another. - * + * * @param obj the object to compare to * @return true if equal */ + @SuppressWarnings("unchecked") public boolean equals(Object obj) { if (obj == this) { return true; @@ -1300,12 +1310,12 @@ public class AbstractHashedMap extends AbstractMap implements IterableMap { /** * Gets the standard Map hashCode. - * + * * @return the hash code defined in the Map interface */ public int hashCode() { int total = 0; - Iterator it = createEntrySetIterator(); + Iterator> it = createEntrySetIterator(); while (it.hasNext()) { total += it.next().hashCode(); } @@ -1314,7 +1324,7 @@ public class AbstractHashedMap extends AbstractMap implements IterableMap { /** * Gets the map as a String. - * + * * @return a string version of the map */ public String toString() { @@ -1324,11 +1334,11 @@ public class AbstractHashedMap extends AbstractMap implements IterableMap { StringBuffer buf = new StringBuffer(32 * size()); buf.append('{'); - MapIterator it = mapIterator(); + MapIterator it = mapIterator(); boolean hasNext = it.hasNext(); while (hasNext) { - Object key = it.next(); - Object value = it.getValue(); + K key = it.next(); + V value = it.getValue(); buf.append(key == this ? "(this Map)" : key) .append('=') .append(value == this ? "(this Map)" : value); diff --git a/src/java/org/apache/commons/collections/map/AbstractInputCheckedMapDecorator.java b/src/java/org/apache/commons/collections/map/AbstractInputCheckedMapDecorator.java index bc503a8cd..4d62588e6 100644 --- a/src/java/org/apache/commons/collections/map/AbstractInputCheckedMapDecorator.java +++ b/src/java/org/apache/commons/collections/map/AbstractInputCheckedMapDecorator.java @@ -44,8 +44,8 @@ import org.apache.commons.collections.set.AbstractSetDecorator; * * @author Stephen Colebourne */ -abstract class AbstractInputCheckedMapDecorator - extends AbstractMapDecorator { +abstract class AbstractInputCheckedMapDecorator + extends AbstractMapDecorator { /** * Constructor only used in deserialization, do not use otherwise. @@ -60,7 +60,7 @@ abstract class AbstractInputCheckedMapDecorator * @param map the map to decorate, must not be null * @throws IllegalArgumentException if map is null */ - protected AbstractInputCheckedMapDecorator(Map map) { + protected AbstractInputCheckedMapDecorator(Map map) { super(map); } @@ -79,7 +79,7 @@ abstract class AbstractInputCheckedMapDecorator * @throws ClassCastException if the class of the specified value is invalid * @throws NullPointerException if the specified value is null and nulls are invalid */ - protected abstract Object checkSetValue(Object value); + protected abstract V checkSetValue(V value); /** * Hook method called to determine if checkSetValue has any effect. @@ -96,41 +96,43 @@ abstract class AbstractInputCheckedMapDecorator } //----------------------------------------------------------------------- - public Set entrySet() { + public Set> entrySet() { if (isSetValueChecking()) { return new EntrySet(map.entrySet(), this); - } else { - return map.entrySet(); } + return map.entrySet(); } //----------------------------------------------------------------------- /** * Implementation of an entry set that checks additions via setValue. */ - static class EntrySet extends AbstractSetDecorator { + @SuppressWarnings("serial") + private class EntrySet extends AbstractSetDecorator> { /** The parent map */ - private final AbstractInputCheckedMapDecorator parent; + private final AbstractInputCheckedMapDecorator parent; - protected EntrySet(Set set, AbstractInputCheckedMapDecorator parent) { + protected EntrySet(Set> set, AbstractInputCheckedMapDecorator parent) { super(set); this.parent = parent; } - public Iterator iterator() { + public Iterator> iterator() { return new EntrySetIterator(collection.iterator(), parent); } + @SuppressWarnings("unchecked") public Object[] toArray() { Object[] array = collection.toArray(); for (int i = 0; i < array.length; i++) { - array[i] = new MapEntry((Map.Entry) array[i], parent); + array[i] = new MapEntry((Map.Entry) array[i], parent); } return array; } - public Object[] toArray(Object array[]) { + @SuppressWarnings("unchecked") + public T[] toArray(T[] array) { Object[] result = array; if (array.length > 0) { // we must create a new array to handle multi-threaded situations @@ -139,12 +141,12 @@ abstract class AbstractInputCheckedMapDecorator } result = collection.toArray(result); for (int i = 0; i < result.length; i++) { - result[i] = new MapEntry((Map.Entry) result[i], parent); + result[i] = new MapEntry((Map.Entry) result[i], parent); } // check to see if result should be returned straight if (result.length > array.length) { - return result; + return (T[]) result; } // copy back into input array to fulfil the method contract @@ -159,18 +161,18 @@ abstract class AbstractInputCheckedMapDecorator /** * Implementation of an entry set iterator that checks additions via setValue. */ - static class EntrySetIterator extends AbstractIteratorDecorator { - + private class EntrySetIterator extends AbstractIteratorDecorator> { + /** The parent map */ - private final AbstractInputCheckedMapDecorator parent; - - protected EntrySetIterator(Iterator iterator, AbstractInputCheckedMapDecorator parent) { + private final AbstractInputCheckedMapDecorator parent; + + protected EntrySetIterator(Iterator> iterator, AbstractInputCheckedMapDecorator parent) { super(iterator); this.parent = parent; } - - public Object next() { - Map.Entry entry = (Map.Entry) iterator.next(); + + public Map.Entry next() { + Map.Entry entry = iterator.next(); return new MapEntry(entry, parent); } } @@ -178,17 +180,17 @@ abstract class AbstractInputCheckedMapDecorator /** * Implementation of a map entry that checks additions via setValue. */ - static class MapEntry extends AbstractMapEntryDecorator { + private class MapEntry extends AbstractMapEntryDecorator { /** The parent map */ - private final AbstractInputCheckedMapDecorator parent; + private final AbstractInputCheckedMapDecorator parent; - protected MapEntry(Map.Entry entry, AbstractInputCheckedMapDecorator parent) { + protected MapEntry(Map.Entry entry, AbstractInputCheckedMapDecorator parent) { super(entry); this.parent = parent; } - public Object setValue(Object value) { + public V setValue(V value) { value = parent.checkSetValue(value); return entry.setValue(value); } diff --git a/src/java/org/apache/commons/collections/map/AbstractLinkedMap.java b/src/java/org/apache/commons/collections/map/AbstractLinkedMap.java index f0c559579..d5a070895 100644 --- a/src/java/org/apache/commons/collections/map/AbstractLinkedMap.java +++ b/src/java/org/apache/commons/collections/map/AbstractLinkedMap.java @@ -21,7 +21,6 @@ import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; -import org.apache.commons.collections.MapIterator; import org.apache.commons.collections.OrderedIterator; import org.apache.commons.collections.OrderedMap; import org.apache.commons.collections.OrderedMapIterator; @@ -63,10 +62,10 @@ import org.apache.commons.collections.iterators.EmptyOrderedMapIterator; * @author java util LinkedHashMap * @author Stephen Colebourne */ -public class AbstractLinkedMap extends AbstractHashedMap implements OrderedMap { +public abstract class AbstractLinkedMap extends AbstractHashedMap implements OrderedMap { /** Header in the linked list */ - protected transient LinkEntry header; + protected transient LinkEntry header; /** * Constructor only used in deserialization, do not use otherwise. @@ -115,7 +114,7 @@ public class AbstractLinkedMap extends AbstractHashedMap implements OrderedMap { * @param map the map to copy * @throws NullPointerException if the map is null */ - protected AbstractLinkedMap(Map map) { + protected AbstractLinkedMap(Map map) { super(map); } @@ -127,7 +126,7 @@ public class AbstractLinkedMap extends AbstractHashedMap implements OrderedMap { * the map entry object. */ protected void init() { - header = (LinkEntry) createEntry(null, -1, null, null); + header = createEntry(null, -1, null, null); header.before = header.after = header; } @@ -141,13 +140,13 @@ public class AbstractLinkedMap extends AbstractHashedMap implements OrderedMap { public boolean containsValue(Object value) { // override uses faster iterator if (value == null) { - for (LinkEntry entry = header.after; entry != header; entry = entry.after) { + for (LinkEntry entry = header.after; entry != header; entry = entry.after) { if (entry.getValue() == null) { return true; } } } else { - for (LinkEntry entry = header.after; entry != header; entry = entry.after) { + for (LinkEntry entry = header.after; entry != header; entry = entry.after) { if (isEqualValue(value, entry.getValue())) { return true; } @@ -172,7 +171,7 @@ public class AbstractLinkedMap extends AbstractHashedMap implements OrderedMap { * * @return the eldest key */ - public Object firstKey() { + public K firstKey() { if (size == 0) { throw new NoSuchElementException("Map is empty"); } @@ -184,7 +183,7 @@ public class AbstractLinkedMap extends AbstractHashedMap implements OrderedMap { * * @return the most recently inserted key */ - public Object lastKey() { + public K lastKey() { if (size == 0) { throw new NoSuchElementException("Map is empty"); } @@ -197,19 +196,23 @@ public class AbstractLinkedMap extends AbstractHashedMap implements OrderedMap { * @param key the key to get after * @return the next key */ - public Object nextKey(Object key) { - LinkEntry entry = (LinkEntry) getEntry(key); + public K nextKey(Object key) { + LinkEntry entry = getEntry(key); return (entry == null || entry.after == header ? null : entry.after.getKey()); } + protected LinkEntry getEntry(Object key) { + return (LinkEntry) super.getEntry(key); + } + /** * Gets the previous key in sequence. * * @param key the key to get before * @return the previous key */ - public Object previousKey(Object key) { - LinkEntry entry = (LinkEntry) getEntry(key); + public K previousKey(Object key) { + LinkEntry entry = getEntry(key); return (entry == null || entry.before == header ? null : entry.before.getKey()); } @@ -221,14 +224,14 @@ public class AbstractLinkedMap extends AbstractHashedMap implements OrderedMap { * @return the key at the specified index * @throws IndexOutOfBoundsException if the index is invalid */ - protected LinkEntry getEntry(int index) { + protected LinkEntry getEntry(int index) { if (index < 0) { throw new IndexOutOfBoundsException("Index " + index + " is less than zero"); } if (index >= size) { throw new IndexOutOfBoundsException("Index " + index + " is invalid for size " + size); } - LinkEntry entry; + LinkEntry entry; if (index < (size / 2)) { // Search forwards entry = header.after; @@ -251,18 +254,18 @@ public class AbstractLinkedMap extends AbstractHashedMap implements OrderedMap { * This implementation adds the entry to the data storage table and * to the end of the linked list. * - * @param entry the entry to add + * @param link the entry to add * @param hashIndex the index into the data array to store at */ - protected void addEntry(HashEntry entry, int hashIndex) { - LinkEntry link = (LinkEntry) entry; + protected void addEntry(HashEntry entry, int hashIndex) { + LinkEntry link = (LinkEntry) entry; link.after = header; link.before = header.before; header.before.after = link; header.before = link; - data[hashIndex] = entry; + data[hashIndex] = link; } - + /** * Creates an entry to store the data. *

@@ -274,10 +277,10 @@ public class AbstractLinkedMap extends AbstractHashedMap implements OrderedMap { * @param value the value to store * @return the newly created entry */ - protected HashEntry createEntry(HashEntry next, int hashCode, Object key, Object value) { - return new LinkEntry(next, hashCode, key, value); + protected LinkEntry createEntry(HashEntry next, int hashCode, K key, V value) { + return new LinkEntry(next, hashCode, convertKey(key), value); } - + /** * Removes an entry from the map and the linked list. *

@@ -288,15 +291,15 @@ public class AbstractLinkedMap extends AbstractHashedMap implements OrderedMap { * @param hashIndex the index into the data structure * @param previous the previous entry in the chain */ - protected void removeEntry(HashEntry entry, int hashIndex, HashEntry previous) { - LinkEntry link = (LinkEntry) entry; + protected void removeEntry(HashEntry entry, int hashIndex, HashEntry previous) { + LinkEntry link = (LinkEntry) entry; link.before.after = link.after; link.after.before = link.before; link.after = null; link.before = null; super.removeEntry(entry, hashIndex, previous); } - + //----------------------------------------------------------------------- /** * Gets the before field from a LinkEntry. @@ -307,10 +310,10 @@ public class AbstractLinkedMap extends AbstractHashedMap implements OrderedMap { * @throws NullPointerException if the entry is null * @since Commons Collections 3.1 */ - protected LinkEntry entryBefore(LinkEntry entry) { + protected LinkEntry entryBefore(LinkEntry entry) { return entry.before; } - + /** * Gets the after field from a LinkEntry. * Used in subclasses that have no visibility of the field. @@ -320,87 +323,64 @@ public class AbstractLinkedMap extends AbstractHashedMap implements OrderedMap { * @throws NullPointerException if the entry is null * @since Commons Collections 3.1 */ - protected LinkEntry entryAfter(LinkEntry entry) { + protected LinkEntry entryAfter(LinkEntry entry) { return entry.after; } - + //----------------------------------------------------------------------- /** - * Gets an iterator over the map. - * Changes made to the iterator affect this map. - *

- * A MapIterator returns the keys in the map. It also provides convenient - * methods to get the key and value, and set the value. - * It avoids the need to create an entrySet/keySet/values object. - * - * @return the map iterator + * {@inheritDoc} */ - public MapIterator mapIterator() { + public OrderedMapIterator mapIterator() { if (size == 0) { - return EmptyOrderedMapIterator.INSTANCE; + return EmptyOrderedMapIterator.getInstance(); } - return new LinkMapIterator(this); - } - - /** - * Gets a bidirectional iterator over the map. - * Changes made to the iterator affect this map. - *

- * A MapIterator returns the keys in the map. It also provides convenient - * methods to get the key and value, and set the value. - * It avoids the need to create an entrySet/keySet/values object. - * - * @return the map iterator - */ - public OrderedMapIterator orderedMapIterator() { - if (size == 0) { - return EmptyOrderedMapIterator.INSTANCE; - } - return new LinkMapIterator(this); + return new LinkMapIterator(this); } /** * MapIterator implementation. */ - protected static class LinkMapIterator extends LinkIterator implements OrderedMapIterator { - - protected LinkMapIterator(AbstractLinkedMap parent) { + protected static class LinkMapIterator extends LinkIterator implements + OrderedMapIterator, ResettableIterator { + + protected LinkMapIterator(AbstractLinkedMap parent) { super(parent); } - public Object next() { + public K next() { return super.nextEntry().getKey(); } - public Object previous() { + public K previous() { return super.previousEntry().getKey(); } - public Object getKey() { - HashEntry current = currentEntry(); + public K getKey() { + LinkEntry current = currentEntry(); if (current == null) { throw new IllegalStateException(AbstractHashedMap.GETKEY_INVALID); } return current.getKey(); } - public Object getValue() { - HashEntry current = currentEntry(); + public V getValue() { + LinkEntry current = currentEntry(); if (current == null) { throw new IllegalStateException(AbstractHashedMap.GETVALUE_INVALID); } return current.getValue(); } - public Object setValue(Object value) { - HashEntry current = currentEntry(); + public V setValue(V value) { + LinkEntry current = currentEntry(); if (current == null) { throw new IllegalStateException(AbstractHashedMap.SETVALUE_INVALID); } return current.setValue(value); } } - + //----------------------------------------------------------------------- /** * Creates an entry set iterator. @@ -408,27 +388,28 @@ public class AbstractLinkedMap extends AbstractHashedMap implements OrderedMap { * * @return the entrySet iterator */ - protected Iterator createEntrySetIterator() { + protected Iterator> createEntrySetIterator() { if (size() == 0) { - return EmptyOrderedIterator.INSTANCE; + return EmptyOrderedIterator.>getInstance(); } - return new EntrySetIterator(this); + return new EntrySetIterator(this); } /** * EntrySet iterator. */ - protected static class EntrySetIterator extends LinkIterator { - - protected EntrySetIterator(AbstractLinkedMap parent) { + protected static class EntrySetIterator extends LinkIterator implements + OrderedIterator>, ResettableIterator> { + + protected EntrySetIterator(AbstractLinkedMap parent) { super(parent); } - public Object next() { + public Map.Entry next() { return super.nextEntry(); } - public Object previous() { + public Map.Entry previous() { return super.previousEntry(); } } @@ -440,31 +421,33 @@ public class AbstractLinkedMap extends AbstractHashedMap implements OrderedMap { * * @return the keySet iterator */ - protected Iterator createKeySetIterator() { + protected Iterator createKeySetIterator() { if (size() == 0) { - return EmptyOrderedIterator.INSTANCE; + return EmptyOrderedIterator.getInstance(); } - return new KeySetIterator(this); + return new KeySetIterator(this); } /** * KeySet iterator. */ - protected static class KeySetIterator extends EntrySetIterator { + protected static class KeySetIterator extends LinkIterator implements + OrderedIterator, ResettableIterator { - protected KeySetIterator(AbstractLinkedMap parent) { - super(parent); + @SuppressWarnings("unchecked") + protected KeySetIterator(AbstractLinkedMap parent) { + super((AbstractLinkedMap) parent); } - public Object next() { + public K next() { return super.nextEntry().getKey(); } - public Object previous() { + public K previous() { return super.previousEntry().getKey(); } } - + //----------------------------------------------------------------------- /** * Creates a values iterator. @@ -472,31 +455,33 @@ public class AbstractLinkedMap extends AbstractHashedMap implements OrderedMap { * * @return the values iterator */ - protected Iterator createValuesIterator() { + protected Iterator createValuesIterator() { if (size() == 0) { - return EmptyOrderedIterator.INSTANCE; + return EmptyOrderedIterator.getInstance(); } - return new ValuesIterator(this); + return new ValuesIterator(this); } /** * Values iterator. */ - protected static class ValuesIterator extends LinkIterator { - - protected ValuesIterator(AbstractLinkedMap parent) { - super(parent); + protected static class ValuesIterator extends LinkIterator implements + OrderedIterator, ResettableIterator { + + @SuppressWarnings("unchecked") + protected ValuesIterator(AbstractLinkedMap parent) { + super((AbstractLinkedMap) parent); } - public Object next() { + public V next() { return super.nextEntry().getValue(); } - public Object previous() { + public V previous() { return super.previousEntry().getValue(); } } - + //----------------------------------------------------------------------- /** * LinkEntry that stores the data. @@ -506,12 +491,12 @@ public class AbstractLinkedMap extends AbstractHashedMap implements OrderedMap { * The entryXxx() methods on AbstractLinkedMap exist * to provide the necessary access. */ - protected static class LinkEntry extends HashEntry { + protected static class LinkEntry extends HashEntry { /** The entry before this one in the order */ - protected LinkEntry before; + protected LinkEntry before; /** The entry after this one in the order */ - protected LinkEntry after; - + protected LinkEntry after; + /** * Constructs a new entry. * @@ -520,27 +505,26 @@ public class AbstractLinkedMap extends AbstractHashedMap implements OrderedMap { * @param key the key * @param value the value */ - protected LinkEntry(HashEntry next, int hashCode, Object key, Object value) { + protected LinkEntry(HashEntry next, int hashCode, Object key, V value) { super(next, hashCode, key, value); } } - + /** * Base Iterator that iterates in link order. */ - protected static abstract class LinkIterator - implements OrderedIterator, ResettableIterator { - + protected static abstract class LinkIterator { + /** The parent map */ - protected final AbstractLinkedMap parent; + protected final AbstractLinkedMap parent; /** The current (last returned) entry */ - protected LinkEntry last; + protected LinkEntry last; /** The next entry */ - protected LinkEntry next; + protected LinkEntry next; /** The modification count expected */ protected int expectedModCount; - - protected LinkIterator(AbstractLinkedMap parent) { + + protected LinkIterator(AbstractLinkedMap parent) { super(); this.parent = parent; this.next = parent.header.after; @@ -550,12 +534,12 @@ public class AbstractLinkedMap extends AbstractHashedMap implements OrderedMap { public boolean hasNext() { return (next != parent.header); } - + public boolean hasPrevious() { return (next.before != parent.header); } - protected LinkEntry nextEntry() { + protected LinkEntry nextEntry() { if (parent.modCount != expectedModCount) { throw new ConcurrentModificationException(); } @@ -567,11 +551,11 @@ public class AbstractLinkedMap extends AbstractHashedMap implements OrderedMap { return last; } - protected LinkEntry previousEntry() { + protected LinkEntry previousEntry() { if (parent.modCount != expectedModCount) { throw new ConcurrentModificationException(); } - LinkEntry previous = next.before; + LinkEntry previous = next.before; if (previous == parent.header) { throw new NoSuchElementException(AbstractHashedMap.NO_PREVIOUS_ENTRY); } @@ -579,11 +563,11 @@ public class AbstractLinkedMap extends AbstractHashedMap implements OrderedMap { last = previous; return last; } - - protected LinkEntry currentEntry() { + + protected LinkEntry currentEntry() { return last; } - + public void remove() { if (last == null) { throw new IllegalStateException(AbstractHashedMap.REMOVE_INVALID); @@ -595,7 +579,7 @@ public class AbstractLinkedMap extends AbstractHashedMap implements OrderedMap { last = null; expectedModCount = parent.modCount; } - + public void reset() { last = null; next = parent.header.after; @@ -604,10 +588,9 @@ public class AbstractLinkedMap extends AbstractHashedMap implements OrderedMap { public String toString() { if (last != null) { return "Iterator[" + last.getKey() + "=" + last.getValue() + "]"; - } else { - return "Iterator[]"; } + return "Iterator[]"; } } - + } diff --git a/src/java/org/apache/commons/collections/map/AbstractReferenceMap.java b/src/java/org/apache/commons/collections/map/AbstractReferenceMap.java index 1b27502e6..60a069957 100644 --- a/src/java/org/apache/commons/collections/map/AbstractReferenceMap.java +++ b/src/java/org/apache/commons/collections/map/AbstractReferenceMap.java @@ -72,7 +72,7 @@ import org.apache.commons.collections.keyvalue.DefaultMapEntry; * ResettableIterator and calling reset(). *

* This implementation is not synchronized. - * You can use {@link java.util.Collections#synchronizedMap} to + * You can use {@link java.util.Collections#synchronizedMap} to * provide synchronized access to a ReferenceMap. * * @see java.lang.ref.Reference @@ -82,28 +82,51 @@ import org.apache.commons.collections.keyvalue.DefaultMapEntry; * @author Paul Jack * @author Stephen Colebourne */ -public abstract class AbstractReferenceMap extends AbstractHashedMap { - - /** Constant indicating that hard references should be used */ - public static final int HARD = 0; - - /** Constant indicating that soft references should be used */ - public static final int SOFT = 1; - - /** Constant indicating that weak references should be used */ - public static final int WEAK = 2; +public abstract class AbstractReferenceMap extends AbstractHashedMap { /** - * The reference type for keys. Must be HARD, SOFT, WEAK. - * @serial + * Reference type enum. */ - protected int keyType; + public static enum ReferenceStrength { + HARD(0), SOFT(1), WEAK(2); + + /** value */ + public final int value; + + /** + * Resolve enum from int. + * @param value + * @return ReferenceType + * @throws IllegalArgumentException if the specified value is invalid. + */ + public static ReferenceStrength resolve(int value) { + switch (value) { + case 0: + return HARD; + case 1: + return SOFT; + case 2: + return WEAK; + default: + throw new IllegalArgumentException(); + } + } + + private ReferenceStrength(int value) { + this.value = value; + } + + } /** - * The reference type for values. Must be HARD, SOFT, WEAK. - * @serial + * The reference type for keys. */ - protected int valueType; + protected ReferenceStrength keyType; + + /** + * The reference type for values. + */ + protected ReferenceStrength valueType; /** * Should the value be automatically purged when the associated key has been collected? @@ -114,7 +137,7 @@ public abstract class AbstractReferenceMap extends AbstractHashedMap { * ReferenceQueue used to eliminate stale mappings. * See purge. */ - private transient ReferenceQueue queue; + private transient ReferenceQueue queue; //----------------------------------------------------------------------- /** @@ -134,15 +157,13 @@ public abstract class AbstractReferenceMap extends AbstractHashedMap { * must be {@link #HARD}, {@link #SOFT}, {@link #WEAK} * @param capacity the initial capacity for the map * @param loadFactor the load factor for the map - * @param purgeValues should the value be automatically purged when the - * key is garbage collected + * @param purgeValues should the value be automatically purged when the + * key is garbage collected */ protected AbstractReferenceMap( - int keyType, int valueType, int capacity, + ReferenceStrength keyType, ReferenceStrength valueType, int capacity, float loadFactor, boolean purgeValues) { super(capacity, loadFactor); - verify("keyType", keyType); - verify("valueType", valueType); this.keyType = keyType; this.valueType = valueType; this.purgeValues = purgeValues; @@ -152,27 +173,13 @@ public abstract class AbstractReferenceMap extends AbstractHashedMap { * Initialise this subclass during construction, cloning or deserialization. */ protected void init() { - queue = new ReferenceQueue(); - } - - //----------------------------------------------------------------------- - /** - * Checks the type int is a valid value. - * - * @param name the name for error messages - * @param type the type value to check - * @throws IllegalArgumentException if the value if invalid - */ - private static void verify(String name, int type) { - if ((type < HARD) || (type > WEAK)) { - throw new IllegalArgumentException(name + " must be HARD, SOFT, WEAK."); - } + queue = new ReferenceQueue(); } //----------------------------------------------------------------------- /** * Gets the size of the map. - * + * * @return the size */ public int size() { @@ -182,7 +189,7 @@ public abstract class AbstractReferenceMap extends AbstractHashedMap { /** * Checks whether the map is currently empty. - * + * * @return true if the map is currently size zero */ public boolean isEmpty() { @@ -192,13 +199,13 @@ public abstract class AbstractReferenceMap extends AbstractHashedMap { /** * Checks whether the map contains the specified key. - * + * * @param key the key to search for * @return true if the map contains the key */ public boolean containsKey(Object key) { purgeBeforeRead(); - Entry entry = getEntry(key); + Entry entry = getEntry(key); if (entry == null) { return false; } @@ -207,7 +214,7 @@ public abstract class AbstractReferenceMap extends AbstractHashedMap { /** * Checks whether the map contains the specified value. - * + * * @param value the value to search for * @return true if the map contains the value */ @@ -221,13 +228,13 @@ public abstract class AbstractReferenceMap extends AbstractHashedMap { /** * Gets the value mapped to the key specified. - * + * * @param key the key * @return the mapped value, null if no match */ - public Object get(Object key) { + public V get(Object key) { purgeBeforeRead(); - Entry entry = getEntry(key); + Entry entry = getEntry(key); if (entry == null) { return null; } @@ -238,13 +245,13 @@ public abstract class AbstractReferenceMap extends AbstractHashedMap { /** * Puts a key-value mapping into this map. * Neither the key nor the value may be null. - * + * * @param key the key to add, must not be null * @param value the value to add, must not be null * @return the value previously mapped to this key, null if none * @throws NullPointerException if either the key or value is null */ - public Object put(Object key, Object value) { + public V put(K key, V value) { if (key == null) { throw new NullPointerException("null keys not allowed"); } @@ -255,14 +262,14 @@ public abstract class AbstractReferenceMap extends AbstractHashedMap { purgeBeforeWrite(); return super.put(key, value); } - + /** * Removes the specified mapping from this map. - * + * * @param key the mapping to remove * @return the value mapped to the removed key, null if key not in map */ - public Object remove(Object key) { + public V remove(Object key) { if (key == null) { return null; } @@ -282,11 +289,11 @@ public abstract class AbstractReferenceMap extends AbstractHashedMap { /** * Gets a MapIterator over the reference map. * The iterator only returns valid key/value pairs. - * + * * @return a map iterator */ - public MapIterator mapIterator() { - return new ReferenceMapIterator(this); + public MapIterator mapIterator() { + return new ReferenceMapIterator(this); } /** @@ -296,9 +303,9 @@ public abstract class AbstractReferenceMap extends AbstractHashedMap { * * @return a set view of this map's entries */ - public Set entrySet() { + public Set> entrySet() { if (entrySet == null) { - entrySet = new ReferenceEntrySet(this); + entrySet = new ReferenceEntrySet(this); } return entrySet; } @@ -308,9 +315,9 @@ public abstract class AbstractReferenceMap extends AbstractHashedMap { * * @return a set view of this map's keys */ - public Set keySet() { + public Set keySet() { if (keySet == null) { - keySet = new ReferenceKeySet(this); + keySet = new ReferenceKeySet(this); } return keySet; } @@ -320,9 +327,9 @@ public abstract class AbstractReferenceMap extends AbstractHashedMap { * * @return a set view of this map's values */ - public Collection values() { + public Collection values() { if (values == null) { - values = new ReferenceValues(this); + values = new ReferenceValues(this); } return values; } @@ -355,7 +362,7 @@ public abstract class AbstractReferenceMap extends AbstractHashedMap { * background thread. */ protected void purge() { - Reference ref = queue.poll(); + Reference ref = queue.poll(); while (ref != null) { purge(ref); ref = queue.poll(); @@ -364,19 +371,19 @@ public abstract class AbstractReferenceMap extends AbstractHashedMap { /** * Purges the specified reference. - * + * * @param ref the reference to purge */ - protected void purge(Reference ref) { + protected void purge(Reference ref) { // The hashCode of the reference is the hashCode of the - // mapping key, even if the reference refers to the + // mapping key, even if the reference refers to the // mapping value... int hash = ref.hashCode(); int index = hashIndex(hash, data.length); - HashEntry previous = null; - HashEntry entry = data[index]; + HashEntry previous = null; + HashEntry entry = data[index]; while (entry != null) { - if (((ReferenceEntry) entry).purge(ref)) { + if (((ReferenceEntry) entry).purge(ref)) { if (previous == null) { data[index] = entry.next; } else { @@ -394,93 +401,93 @@ public abstract class AbstractReferenceMap extends AbstractHashedMap { //----------------------------------------------------------------------- /** * Gets the entry mapped to the key specified. - * + * * @param key the key * @return the entry, null if no match */ - protected HashEntry getEntry(Object key) { + protected HashEntry getEntry(Object key) { if (key == null) { return null; - } else { - return super.getEntry(key); } + return super.getEntry(key); } /** * Gets the hash code for a MapEntry. * Subclasses can override this, for example to use the identityHashCode. - * + * * @param key the key to get a hash code for, may be null * @param value the value to get a hash code for, may be null * @return the hash code, as per the MapEntry specification */ protected int hashEntry(Object key, Object value) { return (key == null ? 0 : key.hashCode()) ^ - (value == null ? 0 : value.hashCode()); + (value == null ? 0 : value.hashCode()); } - + /** * Compares two keys, in internal converted form, to see if they are equal. *

* This implementation converts the key from the entry to a real reference * before comparison. - * + * * @param key1 the first key to compare passed in from outside * @param key2 the second key extracted from the entry via entry.key * @return true if equal */ + @SuppressWarnings("unchecked") protected boolean isEqualKey(Object key1, Object key2) { - key2 = (keyType > HARD ? ((Reference) key2).get() : key2); + key2 = (keyType == ReferenceStrength.HARD ? key2 : ((Reference) key2).get()); return (key1 == key2 || key1.equals(key2)); } - + /** * Creates a ReferenceEntry instead of a HashEntry. - * + * * @param next the next entry in sequence * @param hashCode the hash code to use * @param key the key to store * @param value the value to store * @return the newly created entry */ - protected HashEntry createEntry(HashEntry next, int hashCode, Object key, Object value) { - return new ReferenceEntry(this, next, hashCode, key, value); + protected ReferenceEntry createEntry(HashEntry next, int hashCode, K key, V value) { + return new ReferenceEntry(this, next, hashCode, key, value); } /** * Creates an entry set iterator. - * + * * @return the entrySet iterator */ - protected Iterator createEntrySetIterator() { - return new ReferenceEntrySetIterator(this); + protected Iterator> createEntrySetIterator() { + return new ReferenceEntrySetIterator(this); } /** * Creates an key set iterator. - * + * * @return the keySet iterator */ - protected Iterator createKeySetIterator() { - return new ReferenceKeySetIterator(this); + protected Iterator createKeySetIterator() { + return new ReferenceKeySetIterator(this); } /** * Creates an values iterator. - * + * * @return the values iterator */ - protected Iterator createValuesIterator() { - return new ReferenceValuesIterator(this); + protected Iterator createValuesIterator() { + return new ReferenceValuesIterator(this); } //----------------------------------------------------------------------- /** * EntrySet implementation. */ - static class ReferenceEntrySet extends EntrySet { - - protected ReferenceEntrySet(AbstractHashedMap parent) { + static class ReferenceEntrySet extends EntrySet { + + protected ReferenceEntrySet(AbstractHashedMap parent) { super(parent); } @@ -488,13 +495,11 @@ public abstract class AbstractReferenceMap extends AbstractHashedMap { return toArray(new Object[0]); } - public Object[] toArray(Object[] arr) { + public T[] toArray(T[] arr) { // special implementation to handle disappearing entries - ArrayList list = new ArrayList(); - Iterator iterator = iterator(); - while (iterator.hasNext()) { - Entry e = (Entry) iterator.next(); - list.add(new DefaultMapEntry(e.getKey(), e.getValue())); + ArrayList> list = new ArrayList>(); + for (Map.Entry entry : this) { + list.add(new DefaultMapEntry(entry)); } return list.toArray(arr); } @@ -504,9 +509,9 @@ public abstract class AbstractReferenceMap extends AbstractHashedMap { /** * KeySet implementation. */ - static class ReferenceKeySet extends KeySet { - - protected ReferenceKeySet(AbstractHashedMap parent) { + static class ReferenceKeySet extends KeySet { + + protected ReferenceKeySet(AbstractHashedMap parent) { super(parent); } @@ -514,11 +519,11 @@ public abstract class AbstractReferenceMap extends AbstractHashedMap { return toArray(new Object[0]); } - public Object[] toArray(Object[] arr) { + public T[] toArray(T[] arr) { // special implementation to handle disappearing keys - List list = new ArrayList(parent.size()); - for (Iterator it = iterator(); it.hasNext(); ) { - list.add(it.next()); + List list = new ArrayList(parent.size()); + for (K key : this) { + list.add(key); } return list.toArray(arr); } @@ -528,9 +533,9 @@ public abstract class AbstractReferenceMap extends AbstractHashedMap { /** * Values implementation. */ - static class ReferenceValues extends Values { - - protected ReferenceValues(AbstractHashedMap parent) { + static class ReferenceValues extends Values { + + protected ReferenceValues(AbstractHashedMap parent) { super(parent); } @@ -538,11 +543,11 @@ public abstract class AbstractReferenceMap extends AbstractHashedMap { return toArray(new Object[0]); } - public Object[] toArray(Object[] arr) { + public T[] toArray(T[] arr) { // special implementation to handle disappearing values - List list = new ArrayList(parent.size()); - for (Iterator it = iterator(); it.hasNext(); ) { - list.add(it.next()); + List list = new ArrayList(parent.size()); + for (V value : this) { + list.add(value); } return list.toArray(arr); } @@ -554,23 +559,23 @@ public abstract class AbstractReferenceMap extends AbstractHashedMap { *

* If getKey() or getValue() returns null, it means * the mapping is stale and should be removed. - * + * * @since Commons Collections 3.1 */ - protected static class ReferenceEntry extends HashEntry { + protected static class ReferenceEntry extends HashEntry { /** The parent map */ - protected final AbstractReferenceMap parent; + protected final AbstractReferenceMap parent; /** * Creates a new entry object for the ReferenceMap. - * + * * @param parent the parent map * @param next the next entry in the hash bucket * @param hashCode the hash code of the key * @param key the key * @param value the value */ - public ReferenceEntry(AbstractReferenceMap parent, HashEntry next, int hashCode, Object key, Object value) { + public ReferenceEntry(AbstractReferenceMap parent, HashEntry next, int hashCode, K key, V value) { super(next, hashCode, null, null); this.parent = parent; this.key = toReference(parent.keyType, key, hashCode); @@ -580,33 +585,36 @@ public abstract class AbstractReferenceMap extends AbstractHashedMap { /** * Gets the key from the entry. * This method dereferences weak and soft keys and thus may return null. - * + * * @return the key, which may be null if it was garbage collected */ - public Object getKey() { - return (parent.keyType > HARD) ? ((Reference) key).get() : key; + @SuppressWarnings("unchecked") + public K getKey() { + return (K) ((parent.keyType == ReferenceStrength.HARD) ? key : ((Reference) key).get()); } /** * Gets the value from the entry. * This method dereferences weak and soft value and thus may return null. - * + * * @return the value, which may be null if it was garbage collected */ - public Object getValue() { - return (parent.valueType > HARD) ? ((Reference) value).get() : value; + @SuppressWarnings("unchecked") + public V getValue() { + return (V) ((parent.valueType == ReferenceStrength.HARD) ? value : ((Reference) value).get()); } /** * Sets the value of the entry. - * + * * @param obj the object to store * @return the previous value */ - public Object setValue(Object obj) { - Object old = getValue(); - if (parent.valueType > HARD) { - ((Reference)value).clear(); + @SuppressWarnings("unchecked") + public V setValue(V obj) { + V old = getValue(); + if (parent.valueType != ReferenceStrength.HARD) { + ((Reference) value).clear(); } value = toReference(parent.valueType, obj, hashCode); return old; @@ -617,10 +625,11 @@ public abstract class AbstractReferenceMap extends AbstractHashedMap { *

* This implementation uses isEqualKey and * isEqualValue on the main map for comparison. - * + * * @param obj the other map entry to compare to * @return true if equal, false if not */ + @SuppressWarnings("unchecked") public boolean equals(Object obj) { if (obj == this) { return true; @@ -628,7 +637,7 @@ public abstract class AbstractReferenceMap extends AbstractHashedMap { if (obj instanceof Map.Entry == false) { return false; } - + Map.Entry entry = (Map.Entry)obj; Object entryKey = entry.getKey(); // convert to hard reference Object entryValue = entry.getValue(); // convert to hard reference @@ -645,7 +654,7 @@ public abstract class AbstractReferenceMap extends AbstractHashedMap { * Gets the hashcode of the entry using temporary hard references. *

* This implementation uses hashEntry on the main map. - * + * * @return the hashcode of the entry */ public int hashCode() { @@ -662,13 +671,17 @@ public abstract class AbstractReferenceMap extends AbstractHashedMap { * this number might be different from referent.hashCode() if * the referent represents a value and not a key */ - protected Object toReference(int type, Object referent, int hash) { - switch (type) { - case HARD: return referent; - case SOFT: return new SoftRef(hash, referent, parent.queue); - case WEAK: return new WeakRef(hash, referent, parent.queue); - default: throw new Error(); + protected Object toReference(ReferenceStrength type, T referent, int hash) { + if (type == ReferenceStrength.HARD) { + return referent; } + if (type == ReferenceStrength.SOFT) { + return new SoftRef(hash, referent, parent.queue); + } + if (type == ReferenceStrength.WEAK) { + return new WeakRef(hash, referent, parent.queue); + } + throw new Error(); } /** @@ -676,15 +689,15 @@ public abstract class AbstractReferenceMap extends AbstractHashedMap { * @param ref the reference to purge * @return true or false */ - boolean purge(Reference ref) { - boolean r = (parent.keyType > HARD) && (key == ref); - r = r || ((parent.valueType > HARD) && (value == ref)); + boolean purge(Reference ref) { + boolean r = (parent.keyType != ReferenceStrength.HARD) && (key == ref); + r = r || ((parent.valueType != ReferenceStrength.HARD) && (value == ref)); if (r) { - if (parent.keyType > HARD) { - ((Reference)key).clear(); + if (parent.keyType != ReferenceStrength.HARD) { + ((Reference) key).clear(); } - if (parent.valueType > HARD) { - ((Reference)value).clear(); + if (parent.valueType != ReferenceStrength.HARD) { + ((Reference) value).clear(); } else if (parent.purgeValues) { value = null; } @@ -694,36 +707,36 @@ public abstract class AbstractReferenceMap extends AbstractHashedMap { /** * Gets the next entry in the bucket. - * + * * @return the next entry in the bucket */ - protected ReferenceEntry next() { - return (ReferenceEntry) next; + protected ReferenceEntry next() { + return (ReferenceEntry) next; } } //----------------------------------------------------------------------- /** - * The EntrySet iterator. + * Base iterator class. */ - static class ReferenceEntrySetIterator implements Iterator { + static class ReferenceBaseIterator { /** The parent map */ - final AbstractReferenceMap parent; - + final AbstractReferenceMap parent; + // These fields keep track of where we are in the table. int index; - ReferenceEntry entry; - ReferenceEntry previous; + ReferenceEntry entry; + ReferenceEntry previous; // These Object fields provide hard references to the // current and next entry; this assures that if hasNext() // returns true, next() will actually return a valid element. - Object nextKey, nextValue; - Object currentKey, currentValue; + K currentKey, nextKey; + V currentValue, nextValue; int expectedModCount; - public ReferenceEntrySetIterator(AbstractReferenceMap parent) { + public ReferenceBaseIterator(AbstractReferenceMap parent) { super(); this.parent = parent; index = (parent.size() != 0 ? parent.data.length : 0); @@ -735,11 +748,11 @@ public abstract class AbstractReferenceMap extends AbstractHashedMap { public boolean hasNext() { checkMod(); while (nextNull()) { - ReferenceEntry e = entry; + ReferenceEntry e = entry; int i = index; while ((e == null) && (i > 0)) { i--; - e = (ReferenceEntry) parent.data[i]; + e = (ReferenceEntry) parent.data[i]; } entry = e; index = i; @@ -767,7 +780,7 @@ public abstract class AbstractReferenceMap extends AbstractHashedMap { return (nextKey == null) || (nextValue == null); } - protected ReferenceEntry nextEntry() { + protected ReferenceEntry nextEntry() { checkMod(); if (nextNull() && !hasNext()) { throw new NoSuchElementException(); @@ -781,14 +794,10 @@ public abstract class AbstractReferenceMap extends AbstractHashedMap { return previous; } - protected ReferenceEntry currentEntry() { + protected ReferenceEntry currentEntry() { checkMod(); return previous; } - - public Object next() { - return nextEntry(); - } public void remove() { checkMod(); @@ -804,15 +813,31 @@ public abstract class AbstractReferenceMap extends AbstractHashedMap { } /** - * The keySet iterator. + * The EntrySet iterator. */ - static class ReferenceKeySetIterator extends ReferenceEntrySetIterator { - - ReferenceKeySetIterator(AbstractReferenceMap parent) { + static class ReferenceEntrySetIterator extends ReferenceBaseIterator implements Iterator> { + + public ReferenceEntrySetIterator(AbstractReferenceMap parent) { super(parent); } - - public Object next() { + + public Map.Entry next() { + return nextEntry(); + } + + } + + /** + * The keySet iterator. + */ + static class ReferenceKeySetIterator extends ReferenceBaseIterator implements Iterator { + + @SuppressWarnings("unchecked") + ReferenceKeySetIterator(AbstractReferenceMap parent) { + super((AbstractReferenceMap) parent); + } + + public K next() { return nextEntry().getKey(); } } @@ -820,13 +845,14 @@ public abstract class AbstractReferenceMap extends AbstractHashedMap { /** * The values iterator. */ - static class ReferenceValuesIterator extends ReferenceEntrySetIterator { - - ReferenceValuesIterator(AbstractReferenceMap parent) { - super(parent); + static class ReferenceValuesIterator extends ReferenceBaseIterator implements Iterator { + + @SuppressWarnings("unchecked") + ReferenceValuesIterator(AbstractReferenceMap parent) { + super((AbstractReferenceMap) parent); } - - public Object next() { + + public V next() { return nextEntry().getValue(); } } @@ -834,41 +860,41 @@ public abstract class AbstractReferenceMap extends AbstractHashedMap { /** * The MapIterator implementation. */ - static class ReferenceMapIterator extends ReferenceEntrySetIterator implements MapIterator { - - protected ReferenceMapIterator(AbstractReferenceMap parent) { + static class ReferenceMapIterator extends ReferenceBaseIterator implements MapIterator { + + protected ReferenceMapIterator(AbstractReferenceMap parent) { super(parent); } - public Object next() { + public K next() { return nextEntry().getKey(); } - public Object getKey() { - HashEntry current = currentEntry(); + public K getKey() { + HashEntry current = currentEntry(); if (current == null) { throw new IllegalStateException(AbstractHashedMap.GETKEY_INVALID); } return current.getKey(); } - public Object getValue() { - HashEntry current = currentEntry(); + public V getValue() { + HashEntry current = currentEntry(); if (current == null) { throw new IllegalStateException(AbstractHashedMap.GETVALUE_INVALID); } return current.getValue(); } - public Object setValue(Object value) { - HashEntry current = currentEntry(); + public V setValue(V value) { + HashEntry current = currentEntry(); if (current == null) { throw new IllegalStateException(AbstractHashedMap.SETVALUE_INVALID); } return current.setValue(value); } } - + //----------------------------------------------------------------------- // These two classes store the hashCode of the key of // of the mapping, so that after they're dequeued a quick @@ -877,11 +903,11 @@ public abstract class AbstractReferenceMap extends AbstractHashedMap { /** * A soft reference holder. */ - static class SoftRef extends SoftReference { + static class SoftRef extends SoftReference { /** the hashCode of the key (even if the reference points to a value) */ private int hash; - public SoftRef(int hash, Object r, ReferenceQueue q) { + public SoftRef(int hash, T r, ReferenceQueue q) { super(r, q); this.hash = hash; } @@ -894,11 +920,11 @@ public abstract class AbstractReferenceMap extends AbstractHashedMap { /** * A weak reference holder. */ - static class WeakRef extends WeakReference { + static class WeakRef extends WeakReference { /** the hashCode of the key (even if the reference points to a value) */ private int hash; - public WeakRef(int hash, Object r, ReferenceQueue q) { + public WeakRef(int hash, T r, ReferenceQueue q) { super(r, q); this.hash = hash; } @@ -924,16 +950,16 @@ public abstract class AbstractReferenceMap extends AbstractHashedMap { * Subclasses may override if they have a specific field that must be present * on read before this implementation will work. Generally, the read determines * what must be serialized here, if anything. - * + * * @param out the output stream */ protected void doWriteObject(ObjectOutputStream out) throws IOException { - out.writeInt(keyType); - out.writeInt(valueType); + out.writeInt(keyType.value); + out.writeInt(valueType.value); out.writeBoolean(purgeValues); out.writeFloat(loadFactor); out.writeInt(data.length); - for (MapIterator it = mapIterator(); it.hasNext();) { + for (MapIterator it = mapIterator(); it.hasNext();) { out.writeObject(it.next()); out.writeObject(it.getValue()); } @@ -955,23 +981,24 @@ public abstract class AbstractReferenceMap extends AbstractHashedMap { *

* Subclasses may override if the subclass has a specific field that must be present * before put() or calculateThreshold() will work correctly. - * + * * @param in the input stream */ + @SuppressWarnings("unchecked") protected void doReadObject(ObjectInputStream in) throws IOException, ClassNotFoundException { - this.keyType = in.readInt(); - this.valueType = in.readInt(); + this.keyType = ReferenceStrength.resolve(in.readInt()); + this.valueType = ReferenceStrength.resolve(in.readInt()); this.purgeValues = in.readBoolean(); this.loadFactor = in.readFloat(); int capacity = in.readInt(); init(); data = new HashEntry[capacity]; while (true) { - Object key = in.readObject(); + K key = (K) in.readObject(); if (key == null) { break; } - Object value = in.readObject(); + V value = (V) in.readObject(); put(key, value); } threshold = calculateThreshold(data.length, loadFactor); diff --git a/src/java/org/apache/commons/collections/map/CaseInsensitiveMap.java b/src/java/org/apache/commons/collections/map/CaseInsensitiveMap.java index 68e649265..7505a8939 100644 --- a/src/java/org/apache/commons/collections/map/CaseInsensitiveMap.java +++ b/src/java/org/apache/commons/collections/map/CaseInsensitiveMap.java @@ -57,7 +57,7 @@ import java.util.Map; * * @author Commons-Collections team */ -public class CaseInsensitiveMap extends AbstractHashedMap implements Serializable, Cloneable { +public class CaseInsensitiveMap extends AbstractHashedMap implements Serializable, Cloneable { /** Serialisation version */ private static final long serialVersionUID = -7074655917369299456L; @@ -102,7 +102,7 @@ public class CaseInsensitiveMap extends AbstractHashedMap implements Serializabl * @param map the map to copy * @throws NullPointerException if the map is null */ - public CaseInsensitiveMap(Map map) { + public CaseInsensitiveMap(Map map) { super(map); } @@ -123,9 +123,8 @@ public class CaseInsensitiveMap extends AbstractHashedMap implements Serializabl chars[i] = Character.toLowerCase(Character.toUpperCase(chars[i])); } return new String(chars); - } else { - return AbstractHashedMap.NULL; } + return AbstractHashedMap.NULL; } //----------------------------------------------------------------------- @@ -134,8 +133,8 @@ public class CaseInsensitiveMap extends AbstractHashedMap implements Serializabl * * @return a shallow clone */ - public Object clone() { - return super.clone(); + public CaseInsensitiveMap clone() { + return (CaseInsensitiveMap) super.clone(); } /** diff --git a/src/java/org/apache/commons/collections/map/FixedSizeSortedMap.java b/src/java/org/apache/commons/collections/map/FixedSizeSortedMap.java index ec8066b4b..17abe58d5 100644 --- a/src/java/org/apache/commons/collections/map/FixedSizeSortedMap.java +++ b/src/java/org/apache/commons/collections/map/FixedSizeSortedMap.java @@ -21,12 +21,12 @@ import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Collection; -import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.SortedMap; import org.apache.commons.collections.BoundedMap; +import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.collection.UnmodifiableCollection; import org.apache.commons.collections.set.UnmodifiableSet; @@ -57,9 +57,9 @@ import org.apache.commons.collections.set.UnmodifiableSet; * @author Stephen Colebourne * @author Paul Jack */ -public class FixedSizeSortedMap - extends AbstractSortedMapDecorator - implements SortedMap, BoundedMap, Serializable { +public class FixedSizeSortedMap + extends AbstractSortedMapDecorator + implements SortedMap, BoundedMap, Serializable { /** Serialization version */ private static final long serialVersionUID = 3126019624511683653L; @@ -70,8 +70,8 @@ public class FixedSizeSortedMap * @param map the map to decorate, must not be null * @throws IllegalArgumentException if map is null */ - public static SortedMap decorate(SortedMap map) { - return new FixedSizeSortedMap(map); + public static SortedMap decorate(SortedMap map) { + return new FixedSizeSortedMap(map); } //----------------------------------------------------------------------- @@ -81,7 +81,7 @@ public class FixedSizeSortedMap * @param map the map to decorate, must not be null * @throws IllegalArgumentException if map is null */ - protected FixedSizeSortedMap(SortedMap map) { + protected FixedSizeSortedMap(SortedMap map) { super(map); } @@ -90,8 +90,8 @@ public class FixedSizeSortedMap * * @return the decorated map */ - protected SortedMap getSortedMap() { - return (SortedMap) map; + protected SortedMap getSortedMap() { + return (SortedMap) map; } //----------------------------------------------------------------------- @@ -106,24 +106,23 @@ public class FixedSizeSortedMap /** * Read the map in using a custom routine. */ + @SuppressWarnings("unchecked") private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); map = (Map) in.readObject(); } //----------------------------------------------------------------------- - public Object put(Object key, Object value) { + public V put(K key, V value) { if (map.containsKey(key) == false) { throw new IllegalArgumentException("Cannot put new key/value pair - Map is fixed size"); } return map.put(key, value); } - public void putAll(Map mapToCopy) { - for (Iterator it = mapToCopy.keySet().iterator(); it.hasNext(); ) { - if (mapToCopy.containsKey(it.next()) == false) { - throw new IllegalArgumentException("Cannot put new key/value pair - Map is fixed size"); - } + public void putAll(Map mapToCopy) { + if (CollectionUtils.isSubCollection(mapToCopy.keySet(), keySet())) { + throw new IllegalArgumentException("Cannot put new key/value pair - Map is fixed size"); } map.putAll(mapToCopy); } @@ -132,39 +131,33 @@ public class FixedSizeSortedMap throw new UnsupportedOperationException("Map is fixed size"); } - public Object remove(Object key) { + public V remove(Object key) { throw new UnsupportedOperationException("Map is fixed size"); } - public Set entrySet() { - Set set = map.entrySet(); - return UnmodifiableSet.decorate(set); + public Set> entrySet() { + return UnmodifiableSet.decorate(map.entrySet()); } - public Set keySet() { - Set set = map.keySet(); - return UnmodifiableSet.decorate(set); + public Set keySet() { + return UnmodifiableSet.decorate(map.keySet()); } - public Collection values() { - Collection coll = map.values(); - return UnmodifiableCollection.decorate(coll); + public Collection values() { + return UnmodifiableCollection.decorate(map.values()); } //----------------------------------------------------------------------- - public SortedMap subMap(Object fromKey, Object toKey) { - SortedMap map = getSortedMap().subMap(fromKey, toKey); - return new FixedSizeSortedMap(map); + public SortedMap subMap(K fromKey, K toKey) { + return new FixedSizeSortedMap(getSortedMap().subMap(fromKey, toKey)); } - public SortedMap headMap(Object toKey) { - SortedMap map = getSortedMap().headMap(toKey); - return new FixedSizeSortedMap(map); + public SortedMap headMap(K toKey) { + return new FixedSizeSortedMap(getSortedMap().headMap(toKey)); } - public SortedMap tailMap(Object fromKey) { - SortedMap map = getSortedMap().tailMap(fromKey); - return new FixedSizeSortedMap(map); + public SortedMap tailMap(K fromKey) { + return new FixedSizeSortedMap(getSortedMap().tailMap(fromKey)); } public boolean isFull() { diff --git a/src/java/org/apache/commons/collections/map/Flat3Map.java b/src/java/org/apache/commons/collections/map/Flat3Map.java index 1cd3f86c0..e13a13039 100644 --- a/src/java/org/apache/commons/collections/map/Flat3Map.java +++ b/src/java/org/apache/commons/collections/map/Flat3Map.java @@ -64,7 +64,7 @@ import org.apache.commons.collections.iterators.EmptyMapIterator; * Note that Flat3Map is not synchronized and is not thread-safe. * If you wish to use this map from multiple threads concurrently, you must use * appropriate synchronization. The simplest approach is to wrap this map - * using {@link java.util.Collections#synchronizedMap(Map)}. This class may throw + * using {@link java.util.Collections#synchronizedMap(Map)}. This class may throw * exceptions when accessed by concurrent threads without synchronization. * * @since Commons Collections 3.0 @@ -72,7 +72,7 @@ import org.apache.commons.collections.iterators.EmptyMapIterator; * * @author Stephen Colebourne */ -public class Flat3Map implements IterableMap, Serializable, Cloneable { +public class Flat3Map implements IterableMap, Serializable, Cloneable { /** Serialization version */ private static final long serialVersionUID = -6701087419741928296L; @@ -86,19 +86,19 @@ public class Flat3Map implements IterableMap, Serializable, Cloneable { /** Hash, used while in flat mode */ private transient int hash3; /** Key, used while in flat mode */ - private transient Object key1; + private transient K key1; /** Key, used while in flat mode */ - private transient Object key2; + private transient K key2; /** Key, used while in flat mode */ - private transient Object key3; + private transient K key3; /** Value, used while in flat mode */ - private transient Object value1; + private transient V value1; /** Value, used while in flat mode */ - private transient Object value2; + private transient V value2; /** Value, used while in flat mode */ - private transient Object value3; + private transient V value3; /** Map, used while in delegate mode */ - private transient AbstractHashedMap delegateMap; + private transient AbstractHashedMap delegateMap; /** * Constructor. @@ -113,7 +113,7 @@ public class Flat3Map implements IterableMap, Serializable, Cloneable { * @param map the map to copy * @throws NullPointerException if the map is null */ - public Flat3Map(Map map) { + public Flat3Map(Map map) { super(); putAll(map); } @@ -121,11 +121,11 @@ public class Flat3Map implements IterableMap, Serializable, Cloneable { //----------------------------------------------------------------------- /** * Gets the value mapped to the key specified. - * + * * @param key the key * @return the mapped value, null if no match */ - public Object get(Object key) { + public V get(Object key) { if (delegateMap != null) { return delegateMap.get(key); } @@ -158,7 +158,7 @@ public class Flat3Map implements IterableMap, Serializable, Cloneable { /** * Gets the size of the map. - * + * * @return the size */ public int size() { @@ -170,7 +170,7 @@ public class Flat3Map implements IterableMap, Serializable, Cloneable { /** * Checks whether the map is currently empty. - * + * * @return true if the map is currently size zero */ public boolean isEmpty() { @@ -180,7 +180,7 @@ public class Flat3Map implements IterableMap, Serializable, Cloneable { //----------------------------------------------------------------------- /** * Checks whether the map contains the specified key. - * + * * @param key the key to search for * @return true if the map contains the key */ @@ -215,7 +215,7 @@ public class Flat3Map implements IterableMap, Serializable, Cloneable { /** * Checks whether the map contains the specified value. - * + * * @param value the value to search for * @return true if the map contains the key */ @@ -248,12 +248,12 @@ public class Flat3Map implements IterableMap, Serializable, Cloneable { //----------------------------------------------------------------------- /** * Puts a key-value mapping into this map. - * + * * @param key the key to add * @param value the value to add * @return the value previously mapped to this key, null if none */ - public Object put(Object key, Object value) { + public V put(K key, V value) { if (delegateMap != null) { return delegateMap.put(key, value); } @@ -262,19 +262,19 @@ public class Flat3Map implements IterableMap, Serializable, Cloneable { switch (size) { // drop through case 3: if (key3 == null) { - Object old = value3; + V old = value3; value3 = value; return old; } case 2: if (key2 == null) { - Object old = value2; + V old = value2; value2 = value; return old; } case 1: if (key1 == null) { - Object old = value1; + V old = value1; value1 = value; return old; } @@ -285,26 +285,26 @@ public class Flat3Map implements IterableMap, Serializable, Cloneable { switch (size) { // drop through case 3: if (hash3 == hashCode && key.equals(key3)) { - Object old = value3; + V old = value3; value3 = value; return old; } case 2: if (hash2 == hashCode && key.equals(key2)) { - Object old = value2; + V old = value2; value2 = value; return old; } case 1: if (hash1 == hashCode && key.equals(key1)) { - Object old = value1; + V old = value1; value1 = value; return old; } } } } - + // add new mapping switch (size) { default: @@ -333,11 +333,11 @@ public class Flat3Map implements IterableMap, Serializable, Cloneable { /** * Puts all the values from the specified map into this map. - * + * * @param map the map to add * @throws NullPointerException if the map is null */ - public void putAll(Map map) { + public void putAll(Map map) { int size = map.size(); if (size == 0) { return; @@ -347,8 +347,7 @@ public class Flat3Map implements IterableMap, Serializable, Cloneable { return; } if (size < 4) { - for (Iterator it = map.entrySet().iterator(); it.hasNext();) { - Map.Entry entry = (Map.Entry) it.next(); + for (Map.Entry entry : map.entrySet()) { put(entry.getKey(), entry.getValue()); } } else { @@ -370,7 +369,7 @@ public class Flat3Map implements IterableMap, Serializable, Cloneable { case 1: delegateMap.put(key1, value1); } - + size = 0; hash1 = hash2 = hash3 = 0; key1 = key2 = key3 = null; @@ -387,17 +386,17 @@ public class Flat3Map implements IterableMap, Serializable, Cloneable { * @return a new AbstractHashedMap or subclass * @since Commons Collections 3.1 */ - protected AbstractHashedMap createDelegateMap() { - return new HashedMap(); + protected AbstractHashedMap createDelegateMap() { + return new HashedMap(); } /** * Removes the specified mapping from this map. - * + * * @param key the mapping to remove * @return the value mapped to the removed key, null if key not in map */ - public Object remove(Object key) { + public V remove(Object key) { if (delegateMap != null) { return delegateMap.remove(key); } @@ -408,7 +407,7 @@ public class Flat3Map implements IterableMap, Serializable, Cloneable { switch (size) { // drop through case 3: if (key3 == null) { - Object old = value3; + V old = value3; hash3 = 0; key3 = null; value3 = null; @@ -416,7 +415,7 @@ public class Flat3Map implements IterableMap, Serializable, Cloneable { return old; } if (key2 == null) { - Object old = value2; + V old = value2; hash2 = hash3; key2 = key3; value2 = value3; @@ -427,7 +426,7 @@ public class Flat3Map implements IterableMap, Serializable, Cloneable { return old; } if (key1 == null) { - Object old = value1; + V old = value1; hash1 = hash3; key1 = key3; value1 = value3; @@ -440,7 +439,7 @@ public class Flat3Map implements IterableMap, Serializable, Cloneable { return null; case 2: if (key2 == null) { - Object old = value2; + V old = value2; hash2 = 0; key2 = null; value2 = null; @@ -448,7 +447,7 @@ public class Flat3Map implements IterableMap, Serializable, Cloneable { return old; } if (key1 == null) { - Object old = value1; + V old = value1; hash1 = hash2; key1 = key2; value1 = value2; @@ -461,7 +460,7 @@ public class Flat3Map implements IterableMap, Serializable, Cloneable { return null; case 1: if (key1 == null) { - Object old = value1; + V old = value1; hash1 = 0; key1 = null; value1 = null; @@ -475,7 +474,7 @@ public class Flat3Map implements IterableMap, Serializable, Cloneable { switch (size) { // drop through case 3: if (hash3 == hashCode && key.equals(key3)) { - Object old = value3; + V old = value3; hash3 = 0; key3 = null; value3 = null; @@ -483,7 +482,7 @@ public class Flat3Map implements IterableMap, Serializable, Cloneable { return old; } if (hash2 == hashCode && key.equals(key2)) { - Object old = value2; + V old = value2; hash2 = hash3; key2 = key3; value2 = value3; @@ -494,7 +493,7 @@ public class Flat3Map implements IterableMap, Serializable, Cloneable { return old; } if (hash1 == hashCode && key.equals(key1)) { - Object old = value1; + V old = value1; hash1 = hash3; key1 = key3; value1 = value3; @@ -507,7 +506,7 @@ public class Flat3Map implements IterableMap, Serializable, Cloneable { return null; case 2: if (hash2 == hashCode && key.equals(key2)) { - Object old = value2; + V old = value2; hash2 = 0; key2 = null; value2 = null; @@ -515,7 +514,7 @@ public class Flat3Map implements IterableMap, Serializable, Cloneable { return old; } if (hash1 == hashCode && key.equals(key1)) { - Object old = value1; + V old = value1; hash1 = hash2; key1 = key2; value1 = value2; @@ -528,7 +527,7 @@ public class Flat3Map implements IterableMap, Serializable, Cloneable { return null; case 1: if (hash1 == hashCode && key.equals(key1)) { - Object old = value1; + V old = value1; hash1 = 0; key1 = null; value1 = null; @@ -566,28 +565,28 @@ public class Flat3Map implements IterableMap, Serializable, Cloneable { * methods to get the key and value, and set the value. * It avoids the need to create an entrySet/keySet/values object. * It also avoids creating the Map Entry object. - * + * * @return the map iterator */ - public MapIterator mapIterator() { + public MapIterator mapIterator() { if (delegateMap != null) { return delegateMap.mapIterator(); } if (size == 0) { - return EmptyMapIterator.INSTANCE; + return EmptyMapIterator.getInstance(); } - return new FlatMapIterator(this); + return new FlatMapIterator(this); } /** * FlatMapIterator */ - static class FlatMapIterator implements MapIterator, ResettableIterator { - private final Flat3Map parent; + static class FlatMapIterator implements MapIterator, ResettableIterator { + private final Flat3Map parent; private int nextIndex = 0; private boolean canRemove = false; - - FlatMapIterator(Flat3Map parent) { + + FlatMapIterator(Flat3Map parent) { super(); this.parent = parent; } @@ -596,7 +595,7 @@ public class Flat3Map implements IterableMap, Serializable, Cloneable { return (nextIndex < parent.size); } - public Object next() { + public K next() { if (hasNext() == false) { throw new NoSuchElementException(AbstractHashedMap.NO_NEXT_ENTRY); } @@ -614,7 +613,7 @@ public class Flat3Map implements IterableMap, Serializable, Cloneable { canRemove = false; } - public Object getKey() { + public K getKey() { if (canRemove == false) { throw new IllegalStateException(AbstractHashedMap.GETKEY_INVALID); } @@ -629,7 +628,7 @@ public class Flat3Map implements IterableMap, Serializable, Cloneable { throw new IllegalStateException("Invalid map index"); } - public Object getValue() { + public V getValue() { if (canRemove == false) { throw new IllegalStateException(AbstractHashedMap.GETVALUE_INVALID); } @@ -644,13 +643,13 @@ public class Flat3Map implements IterableMap, Serializable, Cloneable { throw new IllegalStateException("Invalid map index"); } - public Object setValue(Object value) { + public V setValue(V value) { if (canRemove == false) { throw new IllegalStateException(AbstractHashedMap.SETVALUE_INVALID); } - Object old = getValue(); + V old = getValue(); switch (nextIndex) { - case 3: + case 3: parent.value3 = value; break; case 2: @@ -662,44 +661,43 @@ public class Flat3Map implements IterableMap, Serializable, Cloneable { } return old; } - + public void reset() { nextIndex = 0; canRemove = false; } - + public String toString() { if (canRemove) { return "Iterator[" + getKey() + "=" + getValue() + "]"; - } else { - return "Iterator[]"; } + return "Iterator[]"; } } - + /** * Gets the entrySet view of the map. * Changes made to the view affect this map. - * The Map Entry is not an independent object and changes as the + * The Map Entry is not an independent object and changes as the * iterator progresses. * To simply iterate through the entries, use {@link #mapIterator()}. - * + * * @return the entrySet view */ - public Set entrySet() { + public Set> entrySet() { if (delegateMap != null) { return delegateMap.entrySet(); } - return new EntrySet(this); + return new EntrySet(this); } - + /** * EntrySet */ - static class EntrySet extends AbstractSet { - private final Flat3Map parent; - - EntrySet(Flat3Map parent) { + static class EntrySet extends AbstractSet> { + private final Flat3Map parent; + + EntrySet(Flat3Map parent) { super(); this.parent = parent; } @@ -707,43 +705,42 @@ public class Flat3Map implements IterableMap, Serializable, Cloneable { public int size() { return parent.size(); } - + public void clear() { parent.clear(); } - + 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(); boolean result = parent.containsKey(key); parent.remove(key); return result; } - public Iterator iterator() { + public Iterator> iterator() { if (parent.delegateMap != null) { return parent.delegateMap.entrySet().iterator(); } if (parent.size() == 0) { - return EmptyIterator.INSTANCE; + return EmptyIterator.>getInstance(); } - return new EntrySetIterator(parent); + return new EntrySetIterator(parent); } } - /** - * EntrySetIterator and MapEntry - */ - static class EntrySetIterator implements Iterator, Map.Entry { - private final Flat3Map parent; + static abstract class EntryIterator implements Map.Entry { + private final Flat3Map parent; private int nextIndex = 0; - private boolean canRemove = false; - - EntrySetIterator(Flat3Map parent) { - super(); + protected boolean canRemove = false; + + /** + * Create a new Flat3Map.EntryIterator. + */ + public EntryIterator(Flat3Map parent) { this.parent = parent; } @@ -751,7 +748,7 @@ public class Flat3Map implements IterableMap, Serializable, Cloneable { return (nextIndex < parent.size); } - public Object next() { + public Map.Entry nextEntry() { if (hasNext() == false) { throw new NoSuchElementException(AbstractHashedMap.NO_NEXT_ENTRY); } @@ -769,7 +766,7 @@ public class Flat3Map implements IterableMap, Serializable, Cloneable { canRemove = false; } - public Object getKey() { + public K getKey() { if (canRemove == false) { throw new IllegalStateException(AbstractHashedMap.GETKEY_INVALID); } @@ -784,7 +781,7 @@ public class Flat3Map implements IterableMap, Serializable, Cloneable { throw new IllegalStateException("Invalid map index"); } - public Object getValue() { + public V getValue() { if (canRemove == false) { throw new IllegalStateException(AbstractHashedMap.GETVALUE_INVALID); } @@ -799,13 +796,13 @@ public class Flat3Map implements IterableMap, Serializable, Cloneable { throw new IllegalStateException("Invalid map index"); } - public Object setValue(Object value) { + public V setValue(V value) { if (canRemove == false) { throw new IllegalStateException(AbstractHashedMap.SETVALUE_INVALID); } - Object old = getValue(); + V old = getValue(); switch (nextIndex) { - case 3: + case 3: parent.value3 = value; break; case 2: @@ -817,7 +814,21 @@ public class Flat3Map implements IterableMap, Serializable, Cloneable { } return old; } - + } + + /** + * EntrySetIterator and MapEntry + */ + static class EntrySetIterator extends EntryIterator implements Iterator> { + + EntrySetIterator(Flat3Map parent) { + super(parent); + } + + public Map.Entry next() { + return nextEntry(); + } + public boolean equals(Object obj) { if (canRemove == false) { return false; @@ -825,13 +836,13 @@ public class Flat3Map implements IterableMap, Serializable, Cloneable { if (obj instanceof Map.Entry == false) { return false; } - Map.Entry other = (Map.Entry) obj; + Map.Entry other = (Map.Entry) obj; Object key = getKey(); Object value = getValue(); return (key == null ? other.getKey() == null : key.equals(other.getKey())) && (value == null ? other.getValue() == null : value.equals(other.getValue())); } - + public int hashCode() { if (canRemove == false) { return 0; @@ -841,37 +852,36 @@ public class Flat3Map implements IterableMap, Serializable, Cloneable { return (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode()); } - + public String toString() { if (canRemove) { return getKey() + "=" + getValue(); - } else { - return ""; } + return ""; } } - + /** * Gets the keySet view of the map. * Changes made to the view affect this map. * To simply iterate through the keys, use {@link #mapIterator()}. - * + * * @return the keySet view */ - public Set keySet() { + public Set keySet() { if (delegateMap != null) { return delegateMap.keySet(); } - return new KeySet(this); + return new KeySet(this); } /** * KeySet */ - static class KeySet extends AbstractSet { - private final Flat3Map parent; - - KeySet(Flat3Map parent) { + static class KeySet extends AbstractSet { + private final Flat3Map parent; + + KeySet(Flat3Map parent) { super(); this.parent = parent; } @@ -879,11 +889,11 @@ public class Flat3Map implements IterableMap, Serializable, Cloneable { public int size() { return parent.size(); } - + public void clear() { parent.clear(); } - + public boolean contains(Object key) { return parent.containsKey(key); } @@ -894,53 +904,54 @@ public class Flat3Map implements IterableMap, Serializable, Cloneable { return result; } - public Iterator iterator() { + public Iterator iterator() { if (parent.delegateMap != null) { return parent.delegateMap.keySet().iterator(); } if (parent.size() == 0) { - return EmptyIterator.INSTANCE; + return EmptyIterator.getInstance(); } - return new KeySetIterator(parent); + return new KeySetIterator(parent); } } /** * KeySetIterator */ - static class KeySetIterator extends EntrySetIterator { - - KeySetIterator(Flat3Map parent) { - super(parent); + static class KeySetIterator extends EntryIterator implements Iterator{ + + @SuppressWarnings("unchecked") + KeySetIterator(Flat3Map parent) { + super((Flat3Map) parent); } - public Object next() { - super.next(); + public K next() { + nextEntry(); return getKey(); } } - + /** * Gets the values view of the map. * Changes made to the view affect this map. * To simply iterate through the values, use {@link #mapIterator()}. - * + * * @return the values view */ - public Collection values() { + public Collection values() { if (delegateMap != null) { return delegateMap.values(); } - return new Values(this); + return new Values(this); } /** * Values */ - static class Values extends AbstractCollection { - private final Flat3Map parent; - - Values(Flat3Map parent) { + static class Values extends AbstractCollection { + private final Flat3Map parent; + + Values(Flat3Map parent) { super(); this.parent = parent; } @@ -948,37 +959,38 @@ public class Flat3Map implements IterableMap, Serializable, Cloneable { public int size() { return parent.size(); } - + public void clear() { parent.clear(); } - + public boolean contains(Object value) { return parent.containsValue(value); } - public Iterator iterator() { + public Iterator iterator() { if (parent.delegateMap != null) { return parent.delegateMap.values().iterator(); } if (parent.size() == 0) { - return EmptyIterator.INSTANCE; + return EmptyIterator.getInstance(); } - return new ValuesIterator(parent); + return new ValuesIterator(parent); } } /** * ValuesIterator */ - static class ValuesIterator extends EntrySetIterator { - - ValuesIterator(Flat3Map parent) { - super(parent); + static class ValuesIterator extends EntryIterator implements Iterator { + + @SuppressWarnings("unchecked") + ValuesIterator(Flat3Map parent) { + super((Flat3Map) parent); } - public Object next() { - super.next(); + public V next() { + nextEntry(); return getValue(); } } @@ -990,7 +1002,7 @@ public class Flat3Map implements IterableMap, Serializable, Cloneable { private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeInt(size()); - for (MapIterator it = mapIterator(); it.hasNext();) { + for (MapIterator it = mapIterator(); it.hasNext();) { out.writeObject(it.next()); // key out.writeObject(it.getValue()); // value } @@ -999,6 +1011,7 @@ public class Flat3Map implements IterableMap, Serializable, Cloneable { /** * Read the map in using a custom routine. */ + @SuppressWarnings("unchecked") private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); int count = in.readInt(); @@ -1006,7 +1019,7 @@ public class Flat3Map implements IterableMap, Serializable, Cloneable { delegateMap = createDelegateMap(); } for (int i = count; i > 0; i--) { - put(in.readObject(), in.readObject()); + put((K) in.readObject(), (V) in.readObject()); } } @@ -1017,11 +1030,12 @@ public class Flat3Map implements IterableMap, Serializable, Cloneable { * @return a shallow clone * @since Commons Collections 3.1 */ - public Object clone() { + @SuppressWarnings("unchecked") + public Flat3Map clone() { try { - Flat3Map cloned = (Flat3Map) super.clone(); + Flat3Map cloned = (Flat3Map) super.clone(); if (cloned.delegateMap != null) { - cloned.delegateMap = (HashedMap) cloned.delegateMap.clone(); + cloned.delegateMap = (HashedMap) cloned.delegateMap.clone(); } return cloned; } catch (CloneNotSupportedException ex) { @@ -1031,7 +1045,7 @@ public class Flat3Map implements IterableMap, Serializable, Cloneable { /** * Compares this map with another. - * + * * @param obj the object to compare to * @return true if equal */ @@ -1045,7 +1059,7 @@ public class Flat3Map implements IterableMap, Serializable, Cloneable { if (obj instanceof Map == false) { return false; } - Map other = (Map) obj; + Map other = (Map) obj; if (size != other.size()) { return false; } @@ -1083,7 +1097,7 @@ public class Flat3Map implements IterableMap, Serializable, Cloneable { /** * Gets the standard Map hashCode. - * + * * @return the hash code defined in the Map interface */ public int hashCode() { @@ -1104,7 +1118,7 @@ public class Flat3Map implements IterableMap, Serializable, Cloneable { /** * Gets the map as a String. - * + * * @return a string version of the map */ public String toString() { diff --git a/src/java/org/apache/commons/collections/map/HashedMap.java b/src/java/org/apache/commons/collections/map/HashedMap.java index 84c38c094..c880ea715 100644 --- a/src/java/org/apache/commons/collections/map/HashedMap.java +++ b/src/java/org/apache/commons/collections/map/HashedMap.java @@ -26,14 +26,14 @@ import java.util.Map; * A Map implementation that is a general purpose alternative * to HashMap. *

- * This implementation improves on the JDK1.4 HashMap by adding the + * This implementation improves on the JDK1.4 HashMap by adding the * {@link org.apache.commons.collections.MapIterator MapIterator} * functionality and many methods for subclassing. *

* Note that HashedMap is not synchronized and is not thread-safe. * If you wish to use this map from multiple threads concurrently, you must use * appropriate synchronization. The simplest approach is to wrap this map - * using {@link java.util.Collections#synchronizedMap(Map)}. This class may throw + * using {@link java.util.Collections#synchronizedMap(Map)}. This class may throw * exceptions when accessed by concurrent threads without synchronization. * * @since Commons Collections 3.0 @@ -41,12 +41,12 @@ import java.util.Map; * * @author Stephen Colebourne */ -public class HashedMap - extends AbstractHashedMap implements Serializable, Cloneable { +public class HashedMap + extends AbstractHashedMap implements Serializable, Cloneable { /** Serialisation version */ private static final long serialVersionUID = -1788199231038721040L; - + /** * Constructs a new empty map with default size and load factor. */ @@ -55,7 +55,7 @@ public class HashedMap } /** - * Constructs a new, empty map with the specified initial capacity. + * Constructs a new, empty map with the specified initial capacity. * * @param initialCapacity the initial capacity * @throws IllegalArgumentException if the initial capacity is less than one @@ -66,7 +66,7 @@ public class HashedMap /** * Constructs a new, empty map with the specified initial capacity and - * load factor. + * load factor. * * @param initialCapacity the initial capacity * @param loadFactor the load factor @@ -83,7 +83,7 @@ public class HashedMap * @param map the map to copy * @throws NullPointerException if the map is null */ - public HashedMap(Map map) { + public HashedMap(Map map) { super(map); } @@ -93,10 +93,10 @@ public class HashedMap * * @return a shallow clone */ - public Object clone() { - return super.clone(); + public HashedMap clone() { + return (HashedMap) super.clone(); } - + /** * Write the map out using a custom routine. */ @@ -112,5 +112,5 @@ public class HashedMap in.defaultReadObject(); doReadObject(in); } - + } diff --git a/src/java/org/apache/commons/collections/map/IdentityMap.java b/src/java/org/apache/commons/collections/map/IdentityMap.java index 9afffec02..abf563e87 100644 --- a/src/java/org/apache/commons/collections/map/IdentityMap.java +++ b/src/java/org/apache/commons/collections/map/IdentityMap.java @@ -32,7 +32,7 @@ import java.util.Map; * Note that IdentityMap is not synchronized and is not thread-safe. * If you wish to use this map from multiple threads concurrently, you must use * appropriate synchronization. The simplest approach is to wrap this map - * using {@link java.util.Collections#synchronizedMap(Map)}. This class may throw + * using {@link java.util.Collections#synchronizedMap(Map)}. This class may throw * exceptions when accessed by concurrent threads without synchronization. * * @since Commons Collections 3.0 @@ -41,8 +41,8 @@ import java.util.Map; * @author java util HashMap * @author Stephen Colebourne */ -public class IdentityMap - extends AbstractHashedMap implements Serializable, Cloneable { +public class IdentityMap + extends AbstractHashedMap implements Serializable, Cloneable { /** Serialisation version */ private static final long serialVersionUID = 2028493495224302329L; @@ -55,7 +55,7 @@ public class IdentityMap } /** - * Constructs a new, empty map with the specified initial capacity. + * Constructs a new, empty map with the specified initial capacity. * * @param initialCapacity the initial capacity * @throws IllegalArgumentException if the initial capacity is less than one @@ -66,7 +66,7 @@ public class IdentityMap /** * Constructs a new, empty map with the specified initial capacity and - * load factor. + * load factor. * * @param initialCapacity the initial capacity * @param loadFactor the load factor @@ -83,7 +83,7 @@ public class IdentityMap * @param map the map to copy * @throws NullPointerException if the map is null */ - public IdentityMap(Map map) { + public IdentityMap(Map map) { super(map); } @@ -91,18 +91,18 @@ public class IdentityMap /** * Gets the hash code for the key specified. * This implementation uses the identity hash code. - * + * * @param key the key to get a hash code for * @return the hash code */ protected int hash(Object key) { return System.identityHashCode(key); } - + /** * Compares two keys for equals. * This implementation uses ==. - * + * * @param key1 the first key to compare * @param key2 the second key to compare * @return true if equal by identity @@ -110,11 +110,11 @@ public class IdentityMap protected boolean isEqualKey(Object key1, Object key2) { return (key1 == key2); } - + /** * Compares two values for equals. * This implementation uses ==. - * + * * @param value1 the first value to compare * @param value2 the second value to compare * @return true if equal by identity @@ -122,31 +122,31 @@ public class IdentityMap protected boolean isEqualValue(Object value1, Object value2) { return (value1 == value2); } - + /** * Creates an entry to store the data. * This implementation creates an IdentityEntry instance. - * + * * @param next the next entry in sequence * @param hashCode the hash code to use * @param key the key to store * @param value the value to store * @return the newly created entry */ - protected HashEntry createEntry(HashEntry next, int hashCode, Object key, Object value) { - return new IdentityEntry(next, hashCode, key, value); + protected IdentityEntry createEntry(HashEntry next, int hashCode, K key, V value) { + return new IdentityEntry(next, hashCode, key, value); } - + //----------------------------------------------------------------------- /** * HashEntry */ - protected static class IdentityEntry extends HashEntry { - - protected IdentityEntry(HashEntry next, int hashCode, Object key, Object value) { + protected static class IdentityEntry extends HashEntry { + + protected IdentityEntry(HashEntry next, int hashCode, K key, V value) { super(next, hashCode, key, value); } - + public boolean equals(Object obj) { if (obj == this) { return true; @@ -154,28 +154,28 @@ public class IdentityMap if (obj instanceof Map.Entry == false) { return false; } - Map.Entry other = (Map.Entry) obj; + Map.Entry other = (Map.Entry) obj; return (getKey() == other.getKey()) && (getValue() == other.getValue()); } - + public int hashCode() { return System.identityHashCode(getKey()) ^ System.identityHashCode(getValue()); } } - + //----------------------------------------------------------------------- /** * Clones the map without cloning the keys or values. * * @return a shallow clone */ - public Object clone() { - return super.clone(); + public IdentityMap clone() { + return (IdentityMap) super.clone(); } - + /** * Write the map out using a custom routine. */ @@ -191,5 +191,5 @@ public class IdentityMap in.defaultReadObject(); doReadObject(in); } - + } diff --git a/src/java/org/apache/commons/collections/map/LRUMap.java b/src/java/org/apache/commons/collections/map/LRUMap.java index 014de4ce1..185b7235d 100644 --- a/src/java/org/apache/commons/collections/map/LRUMap.java +++ b/src/java/org/apache/commons/collections/map/LRUMap.java @@ -35,7 +35,7 @@ import org.apache.commons.collections.BoundedMap; *

* The map implements OrderedMap and entries may be queried using * the bidirectional OrderedMapIterator. The order returned is - * least recently used to most recently used. Iterators from map views can + * least recently used to most recently used. Iterators from map views can * also be cast to OrderedIterator if required. *

* All the available iterators can be reset back to the start by casting to @@ -44,7 +44,7 @@ import org.apache.commons.collections.BoundedMap; * Note that LRUMap is not synchronized and is not thread-safe. * If you wish to use this map from multiple threads concurrently, you must use * appropriate synchronization. The simplest approach is to wrap this map - * using {@link java.util.Collections#synchronizedMap(Map)}. This class may throw + * using {@link java.util.Collections#synchronizedMap(Map)}. This class may throw * NullPointerException's when accessed by concurrent threads. * * @since Commons Collections 3.0 (previously in main package v1.0) @@ -56,14 +56,14 @@ import org.apache.commons.collections.BoundedMap; * @author Mike Pettypiece * @author Mario Ivankovits */ -public class LRUMap - extends AbstractLinkedMap implements BoundedMap, Serializable, Cloneable { - +public class LRUMap + extends AbstractLinkedMap implements BoundedMap, Serializable, Cloneable { + /** Serialisation version */ private static final long serialVersionUID = -612114643488955218L; /** Default maximum size */ protected static final int DEFAULT_MAX_SIZE = 100; - + /** Maximum size */ private transient int maxSize; /** Scan behaviour */ @@ -100,7 +100,7 @@ public class LRUMap /** * Constructs a new, empty map with the specified initial capacity and - * load factor. + * load factor. * * @param maxSize the maximum size of the map * @param loadFactor the load factor @@ -140,7 +140,7 @@ public class LRUMap * @throws NullPointerException if the map is null * @throws IllegalArgumentException if the map is empty */ - public LRUMap(Map map) { + public LRUMap(Map map) { this(map, false); } @@ -155,7 +155,7 @@ public class LRUMap * @throws IllegalArgumentException if the map is empty * @since Commons Collections 3.1 */ - public LRUMap(Map map, boolean scanUntilRemovable) { + public LRUMap(Map map, boolean scanUntilRemovable) { this(map.size(), DEFAULT_LOAD_FACTOR, scanUntilRemovable); putAll(map); } @@ -166,12 +166,12 @@ public class LRUMap *

* This operation changes the position of the key in the map to the * most recently used position (first). - * + * * @param key the key * @return the mapped value, null if no match */ - public Object get(Object key) { - LinkEntry entry = (LinkEntry) getEntry(key); + public V get(Object key) { + LinkEntry entry = getEntry(key); if (entry == null) { return null; } @@ -184,10 +184,10 @@ public class LRUMap * Moves an entry to the MRU position at the end of the list. *

* This implementation moves the updated entry to the end of the list. - * + * * @param entry the entry to update */ - protected void moveToMRU(LinkEntry entry) { + protected void moveToMRU(LinkEntry entry) { if (entry.after != header) { modCount++; // remove @@ -208,21 +208,21 @@ public class LRUMap " (please report this to dev@commons.apache.org)"); } } - + /** * Updates an existing key-value mapping. *

* This implementation moves the updated entry to the top of the list * using {@link #moveToMRU(AbstractLinkedMap.LinkEntry)}. - * + * * @param entry the entry to update * @param newValue the new value to store */ - protected void updateEntry(HashEntry entry, Object newValue) { - moveToMRU((LinkEntry) entry); // handles modCount + protected void updateEntry(HashEntry entry, V newValue) { + moveToMRU((LinkEntry) entry); // handles modCount entry.setValue(newValue); } - + /** * Adds a new key-value mapping into this map. *

@@ -232,15 +232,15 @@ public class LRUMap * From Commons Collections 3.1 this method uses {@link #isFull()} rather * than accessing size and maxSize directly. * It also handles the scanUntilRemovable functionality. - * + * * @param hashIndex the index into the data array to store at * @param hashCode the hash code of the key to add * @param key the key to add * @param value the value to add */ - protected void addMapping(int hashIndex, int hashCode, Object key, Object value) { + protected void addMapping(int hashIndex, int hashCode, K key, V value) { if (isFull()) { - LinkEntry reuse = header.after; + LinkEntry reuse = header.after; boolean removeLRUEntry = false; if (scanUntilRemovable) { while (reuse != header && reuse != null) { @@ -260,7 +260,7 @@ public class LRUMap } else { removeLRUEntry = removeLRU(reuse); } - + if (removeLRUEntry) { if (reuse == null) { throw new IllegalStateException( @@ -277,27 +277,27 @@ public class LRUMap super.addMapping(hashIndex, hashCode, key, value); } } - + /** * Reuses an entry by removing it and moving it to a new place in the map. *

* This method uses {@link #removeEntry}, {@link #reuseEntry} and {@link #addEntry}. - * + * * @param entry the entry to reuse * @param hashIndex the index into the data array to store at * @param hashCode the hash code of the key to add * @param key the key to add * @param value the value to add */ - protected void reuseMapping(LinkEntry entry, int hashIndex, int hashCode, Object key, Object value) { + protected void reuseMapping(LinkEntry entry, int hashIndex, int hashCode, K key, V value) { // find the entry before the entry specified in the hash table // remember that the parameters (except the first) refer to the new entry, // not the old one try { int removeIndex = hashIndex(entry.hashCode, data.length); - HashEntry[] tmp = data; // may protect against some sync issues - HashEntry loop = tmp[removeIndex]; - HashEntry previous = null; + HashEntry[] tmp = data; // may protect against some sync issues + HashEntry loop = tmp[removeIndex]; + HashEntry previous = null; while (loop != entry && loop != null) { previous = loop; loop = loop.next; @@ -309,7 +309,7 @@ public class LRUMap " Please check that your keys are immutable, and that you have used synchronization properly." + " If so, then please report this to dev@commons.apache.org as a bug."); } - + // reuse the entry modCount++; removeEntry(entry, removeIndex, previous); @@ -323,7 +323,7 @@ public class LRUMap " If so, then please report this to dev@commons.apache.org as a bug."); } } - + /** * Subclass method to control removal of the least recently used entry from the map. *

@@ -354,10 +354,10 @@ public class LRUMap *

* NOTE: Commons Collections 3.0 passed the wrong entry to this method. * This is fixed in version 3.1 onwards. - * + * * @param entry the entry to be removed */ - protected boolean removeLRU(LinkEntry entry) { + protected boolean removeLRU(LinkEntry entry) { return true; } @@ -397,10 +397,10 @@ public class LRUMap * * @return a shallow clone */ - public Object clone() { - return super.clone(); + public LRUMap clone() { + return (LRUMap) super.clone(); } - + /** * Write the map out using a custom routine. */ @@ -416,7 +416,7 @@ public class LRUMap in.defaultReadObject(); doReadObject(in); } - + /** * Writes the data necessary for put() to work in deserialization. */ @@ -432,5 +432,5 @@ public class LRUMap maxSize = in.readInt(); super.doReadObject(in); } - + } diff --git a/src/java/org/apache/commons/collections/map/LinkedMap.java b/src/java/org/apache/commons/collections/map/LinkedMap.java index e98569049..529675b89 100644 --- a/src/java/org/apache/commons/collections/map/LinkedMap.java +++ b/src/java/org/apache/commons/collections/map/LinkedMap.java @@ -62,8 +62,7 @@ import org.apache.commons.collections.list.UnmodifiableList; * * @author Stephen Colebourne */ -public class LinkedMap - extends AbstractLinkedMap implements Serializable, Cloneable { +public class LinkedMap extends AbstractLinkedMap implements Serializable, Cloneable { /** Serialisation version */ private static final long serialVersionUID = 9077234323521161066L; @@ -104,7 +103,7 @@ public class LinkedMap * @param map the map to copy * @throws NullPointerException if the map is null */ - public LinkedMap(Map map) { + public LinkedMap(Map map) { super(map); } @@ -114,8 +113,8 @@ public class LinkedMap * * @return a shallow clone */ - public Object clone() { - return super.clone(); + public LinkedMap clone() { + return (LinkedMap) super.clone(); } /** @@ -142,7 +141,7 @@ public class LinkedMap * @return the key at the specified index * @throws IndexOutOfBoundsException if the index is invalid */ - public Object get(int index) { + public K get(int index) { return getEntry(index).getKey(); } @@ -153,7 +152,7 @@ public class LinkedMap * @return the value at the specified index * @throws IndexOutOfBoundsException if the index is invalid */ - public Object getValue(int index) { + public V getValue(int index) { return getEntry(index).getValue(); } @@ -166,7 +165,7 @@ public class LinkedMap public int indexOf(Object key) { key = convertKey(key); int i = 0; - for (LinkEntry entry = header.after; entry != header; entry = entry.after, i++) { + for (LinkEntry entry = header.after; entry != header; entry = entry.after, i++) { if (isEqualKey(key, entry.key)) { return i; } @@ -182,7 +181,7 @@ public class LinkedMap * or null if none existed * @throws IndexOutOfBoundsException if the index is invalid */ - public Object remove(int index) { + public V remove(int index) { return remove(get(index)); } @@ -201,29 +200,29 @@ public class LinkedMap * @see #keySet() * @return The ordered list of keys. */ - public List asList() { - return new LinkedMapList(this); + public List asList() { + return new LinkedMapList(this); } /** * List view of map. */ - static class LinkedMapList extends AbstractList { - - final LinkedMap parent; - - LinkedMapList(LinkedMap parent) { + static class LinkedMapList extends AbstractList { + + final LinkedMap parent; + + LinkedMapList(LinkedMap parent) { this.parent = parent; } - + public int size() { return parent.size(); } - - public Object get(int index) { + + public K get(int index) { return parent.get(index); } - + public boolean contains(Object obj) { return parent.containsKey(obj); } @@ -231,58 +230,58 @@ public class LinkedMap public int indexOf(Object obj) { return parent.indexOf(obj); } - + public int lastIndexOf(Object obj) { return parent.indexOf(obj); } - - public boolean containsAll(Collection coll) { + + public boolean containsAll(Collection coll) { return parent.keySet().containsAll(coll); } - - public Object remove(int index) { + + public K remove(int index) { throw new UnsupportedOperationException(); } - + public boolean remove(Object obj) { 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 void clear() { throw new UnsupportedOperationException(); } - + public Object[] toArray() { return parent.keySet().toArray(); } - public Object[] toArray(Object[] array) { + public T[] toArray(T[] array) { return parent.keySet().toArray(array); } - - public Iterator iterator() { + + public Iterator iterator() { return UnmodifiableIterator.decorate(parent.keySet().iterator()); } - - public ListIterator listIterator() { + + public ListIterator listIterator() { return UnmodifiableListIterator.decorate(super.listIterator()); } - - public ListIterator listIterator(int fromIndex) { + + public ListIterator listIterator(int fromIndex) { return UnmodifiableListIterator.decorate(super.listIterator(fromIndex)); } - - public List subList(int fromIndexInclusive, int toIndexExclusive) { + + public List subList(int fromIndexInclusive, int toIndexExclusive) { return UnmodifiableList.decorate(super.subList(fromIndexInclusive, toIndexExclusive)); } } - + } diff --git a/src/java/org/apache/commons/collections/map/MultiKeyMap.java b/src/java/org/apache/commons/collections/map/MultiKeyMap.java index 968f26b72..ce39401f2 100644 --- a/src/java/org/apache/commons/collections/map/MultiKeyMap.java +++ b/src/java/org/apache/commons/collections/map/MultiKeyMap.java @@ -17,10 +17,7 @@ package org.apache.commons.collections.map; import java.io.Serializable; -import java.util.Collection; -import java.util.Iterator; import java.util.Map; -import java.util.Set; import org.apache.commons.collections.IterableMap; import org.apache.commons.collections.MapIterator; @@ -77,14 +74,15 @@ import org.apache.commons.collections.keyvalue.MultiKey; * * @author Stephen Colebourne */ -public class MultiKeyMap - implements IterableMap, Serializable { +public class MultiKeyMap extends AbstractMapDecorator, V> + implements IterableMap, V>, Serializable { /** Serialisation version */ private static final long serialVersionUID = -1788199231038721040L; /** The decorated map */ - protected final AbstractHashedMap map; + //keep this member around for serialization BC with older Collections releases assuming we want to do that + protected AbstractHashedMap, V> map; //----------------------------------------------------------------------- /** @@ -94,14 +92,14 @@ public class MultiKeyMap * @param map the map to decorate, not null * @throws IllegalArgumentException if the map is null or not empty */ - public static MultiKeyMap decorate(AbstractHashedMap map) { + public static MultiKeyMap decorate(AbstractHashedMap, V> map) { if (map == null) { throw new IllegalArgumentException("Map must not be null"); } if (map.size() > 0) { throw new IllegalArgumentException("Map must be empty"); } - return new MultiKeyMap(map); + return new MultiKeyMap(map); } //----------------------------------------------------------------------- @@ -109,8 +107,7 @@ public class MultiKeyMap * Constructs a new MultiKeyMap that decorates a HashedMap. */ public MultiKeyMap() { - super(); - map = new HashedMap(); + this(new HashedMap, V>()); } /** @@ -121,8 +118,8 @@ public class MultiKeyMap * * @param map the map to decorate */ - protected MultiKeyMap(AbstractHashedMap map) { - super(); + protected MultiKeyMap(AbstractHashedMap, V> map) { + super(map); this.map = map; } @@ -134,9 +131,9 @@ public class MultiKeyMap * @param key2 the second key * @return the mapped value, null if no match */ - public Object get(Object key1, Object key2) { + public V get(Object key1, Object key2) { int hashCode = hash(key1, key2); - AbstractHashedMap.HashEntry entry = map.data[map.hashIndex(hashCode, map.data.length)]; + AbstractHashedMap.HashEntry, V> entry = decorated().data[decorated().hashIndex(hashCode, decorated().data.length)]; while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(entry, key1, key2)) { return entry.getValue(); @@ -155,7 +152,7 @@ public class MultiKeyMap */ public boolean containsKey(Object key1, Object key2) { int hashCode = hash(key1, key2); - AbstractHashedMap.HashEntry entry = map.data[map.hashIndex(hashCode, map.data.length)]; + AbstractHashedMap.HashEntry, V> entry = decorated().data[decorated().hashIndex(hashCode, decorated().data.length)]; while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(entry, key1, key2)) { return true; @@ -173,20 +170,19 @@ public class MultiKeyMap * @param value the value to store * @return the value previously mapped to this combined key, null if none */ - public Object put(Object key1, Object key2, Object value) { + public V put(K key1, K key2, V value) { int hashCode = hash(key1, key2); - int index = map.hashIndex(hashCode, map.data.length); - AbstractHashedMap.HashEntry entry = map.data[index]; + int index = decorated().hashIndex(hashCode, decorated().data.length); + AbstractHashedMap.HashEntry, V> entry = decorated().data[index]; while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(entry, key1, key2)) { - Object oldValue = entry.getValue(); - map.updateEntry(entry, value); + V oldValue = entry.getValue(); + decorated().updateEntry(entry, value); return oldValue; } entry = entry.next; } - - map.addMapping(index, hashCode, new MultiKey(key1, key2), value); + decorated().addMapping(index, hashCode, new MultiKey(key1, key2), value); return null; } @@ -197,15 +193,15 @@ public class MultiKeyMap * @param key2 the second key * @return the value mapped to the removed key, null if key not in map */ - public Object remove(Object key1, Object key2) { + public V remove(Object key1, Object key2) { int hashCode = hash(key1, key2); - int index = map.hashIndex(hashCode, map.data.length); - AbstractHashedMap.HashEntry entry = map.data[index]; - AbstractHashedMap.HashEntry previous = null; + int index = decorated().hashIndex(hashCode, decorated().data.length); + AbstractHashedMap.HashEntry, V> entry = decorated().data[index]; + AbstractHashedMap.HashEntry, V> previous = null; while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(entry, key1, key2)) { - Object oldValue = entry.getValue(); - map.removeMapping(entry, index, previous); + V oldValue = entry.getValue(); + decorated().removeMapping(entry, index, previous); return oldValue; } previous = entry; @@ -244,12 +240,13 @@ public class MultiKeyMap * @param key2 the second key * @return true if the key matches */ - protected boolean isEqualKey(AbstractHashedMap.HashEntry entry, Object key1, Object key2) { - MultiKey multi = (MultiKey) entry.getKey(); + protected boolean isEqualKey(AbstractHashedMap.HashEntry, V> entry, + Object key1, Object key2) { + MultiKey multi = entry.getKey(); return multi.size() == 2 && - (key1 == null ? multi.getKey(0) == null : key1.equals(multi.getKey(0))) && - (key2 == null ? multi.getKey(1) == null : key2.equals(multi.getKey(1))); + (key1 == multi.getKey(0) || key1 != null && key1.equals(multi.getKey(0))) && + (key2 == multi.getKey(1) || key1 != null && key2.equals(multi.getKey(1))); } //----------------------------------------------------------------------- @@ -261,9 +258,9 @@ public class MultiKeyMap * @param key3 the third key * @return the mapped value, null if no match */ - public Object get(Object key1, Object key2, Object key3) { + public V get(Object key1, Object key2, Object key3) { int hashCode = hash(key1, key2, key3); - AbstractHashedMap.HashEntry entry = map.data[map.hashIndex(hashCode, map.data.length)]; + AbstractHashedMap.HashEntry, V> entry = decorated().data[decorated().hashIndex(hashCode, decorated().data.length)]; while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(entry, key1, key2, key3)) { return entry.getValue(); @@ -283,7 +280,7 @@ public class MultiKeyMap */ public boolean containsKey(Object key1, Object key2, Object key3) { int hashCode = hash(key1, key2, key3); - AbstractHashedMap.HashEntry entry = map.data[map.hashIndex(hashCode, map.data.length)]; + AbstractHashedMap.HashEntry, V> entry = decorated().data[decorated().hashIndex(hashCode, decorated().data.length)]; while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(entry, key1, key2, key3)) { return true; @@ -302,20 +299,19 @@ public class MultiKeyMap * @param value the value to store * @return the value previously mapped to this combined key, null if none */ - public Object put(Object key1, Object key2, Object key3, Object value) { + public V put(K key1, K key2, K key3, V value) { int hashCode = hash(key1, key2, key3); - int index = map.hashIndex(hashCode, map.data.length); - AbstractHashedMap.HashEntry entry = map.data[index]; + int index = decorated().hashIndex(hashCode, decorated().data.length); + AbstractHashedMap.HashEntry, V> entry = decorated().data[index]; while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(entry, key1, key2, key3)) { - Object oldValue = entry.getValue(); - map.updateEntry(entry, value); + V oldValue = entry.getValue(); + decorated().updateEntry(entry, value); return oldValue; } entry = entry.next; } - - map.addMapping(index, hashCode, new MultiKey(key1, key2, key3), value); + decorated().addMapping(index, hashCode, new MultiKey(key1, key2, key3), value); return null; } @@ -327,15 +323,15 @@ public class MultiKeyMap * @param key3 the third key * @return the value mapped to the removed key, null if key not in map */ - public Object remove(Object key1, Object key2, Object key3) { + public V remove(Object key1, Object key2, Object key3) { int hashCode = hash(key1, key2, key3); - int index = map.hashIndex(hashCode, map.data.length); - AbstractHashedMap.HashEntry entry = map.data[index]; - AbstractHashedMap.HashEntry previous = null; + int index = decorated().hashIndex(hashCode, decorated().data.length); + AbstractHashedMap.HashEntry, V> entry = decorated().data[index]; + AbstractHashedMap.HashEntry, V> previous = null; while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(entry, key1, key2, key3)) { - Object oldValue = entry.getValue(); - map.removeMapping(entry, index, previous); + V oldValue = entry.getValue(); + decorated().removeMapping(entry, index, previous); return oldValue; } previous = entry; @@ -379,13 +375,13 @@ public class MultiKeyMap * @param key3 the third key * @return true if the key matches */ - protected boolean isEqualKey(AbstractHashedMap.HashEntry entry, Object key1, Object key2, Object key3) { - MultiKey multi = (MultiKey) entry.getKey(); + protected boolean isEqualKey(AbstractHashedMap.HashEntry, V> entry, Object key1, Object key2, Object key3) { + MultiKey multi = entry.getKey(); return multi.size() == 3 && - (key1 == null ? multi.getKey(0) == null : key1.equals(multi.getKey(0))) && - (key2 == null ? multi.getKey(1) == null : key2.equals(multi.getKey(1))) && - (key3 == null ? multi.getKey(2) == null : key3.equals(multi.getKey(2))); + (key1 == multi.getKey(0) || key1 != null && key1.equals(multi.getKey(0))) && + (key2 == multi.getKey(1) || key2 != null && key2.equals(multi.getKey(1))) && + (key3 == multi.getKey(2) || key3 != null && key3.equals(multi.getKey(2))); } //----------------------------------------------------------------------- @@ -398,9 +394,9 @@ public class MultiKeyMap * @param key4 the fourth key * @return the mapped value, null if no match */ - public Object get(Object key1, Object key2, Object key3, Object key4) { + public V get(Object key1, Object key2, Object key3, Object key4) { int hashCode = hash(key1, key2, key3, key4); - AbstractHashedMap.HashEntry entry = map.data[map.hashIndex(hashCode, map.data.length)]; + AbstractHashedMap.HashEntry, V> entry = decorated().data[decorated().hashIndex(hashCode, decorated().data.length)]; while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(entry, key1, key2, key3, key4)) { return entry.getValue(); @@ -421,7 +417,7 @@ public class MultiKeyMap */ public boolean containsKey(Object key1, Object key2, Object key3, Object key4) { int hashCode = hash(key1, key2, key3, key4); - AbstractHashedMap.HashEntry entry = map.data[map.hashIndex(hashCode, map.data.length)]; + AbstractHashedMap.HashEntry, V> entry = decorated().data[decorated().hashIndex(hashCode, decorated().data.length)]; while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(entry, key1, key2, key3, key4)) { return true; @@ -441,20 +437,19 @@ public class MultiKeyMap * @param value the value to store * @return the value previously mapped to this combined key, null if none */ - public Object put(Object key1, Object key2, Object key3, Object key4, Object value) { + public V put(K key1, K key2, K key3, K key4, V value) { int hashCode = hash(key1, key2, key3, key4); - int index = map.hashIndex(hashCode, map.data.length); - AbstractHashedMap.HashEntry entry = map.data[index]; + int index = decorated().hashIndex(hashCode, decorated().data.length); + AbstractHashedMap.HashEntry, V> entry = decorated().data[index]; while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(entry, key1, key2, key3, key4)) { - Object oldValue = entry.getValue(); - map.updateEntry(entry, value); + V oldValue = entry.getValue(); + decorated().updateEntry(entry, value); return oldValue; } entry = entry.next; } - - map.addMapping(index, hashCode, new MultiKey(key1, key2, key3, key4), value); + decorated().addMapping(index, hashCode, new MultiKey(key1, key2, key3, key4), value); return null; } @@ -467,15 +462,15 @@ public class MultiKeyMap * @param key4 the fourth key * @return the value mapped to the removed key, null if key not in map */ - public Object remove(Object key1, Object key2, Object key3, Object key4) { + public V remove(Object key1, Object key2, Object key3, Object key4) { int hashCode = hash(key1, key2, key3, key4); - int index = map.hashIndex(hashCode, map.data.length); - AbstractHashedMap.HashEntry entry = map.data[index]; - AbstractHashedMap.HashEntry previous = null; + int index = decorated().hashIndex(hashCode, decorated().data.length); + AbstractHashedMap.HashEntry, V> entry = decorated().data[index]; + AbstractHashedMap.HashEntry, V> previous = null; while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(entry, key1, key2, key3, key4)) { - Object oldValue = entry.getValue(); - map.removeMapping(entry, index, previous); + V oldValue = entry.getValue(); + decorated().removeMapping(entry, index, previous); return oldValue; } previous = entry; @@ -524,14 +519,14 @@ public class MultiKeyMap * @param key4 the fourth key * @return true if the key matches */ - protected boolean isEqualKey(AbstractHashedMap.HashEntry entry, Object key1, Object key2, Object key3, Object key4) { - MultiKey multi = (MultiKey) entry.getKey(); + protected boolean isEqualKey(AbstractHashedMap.HashEntry, V> entry, Object key1, Object key2, Object key3, Object key4) { + MultiKey multi = entry.getKey(); return multi.size() == 4 && - (key1 == null ? multi.getKey(0) == null : key1.equals(multi.getKey(0))) && - (key2 == null ? multi.getKey(1) == null : key2.equals(multi.getKey(1))) && - (key3 == null ? multi.getKey(2) == null : key3.equals(multi.getKey(2))) && - (key4 == null ? multi.getKey(3) == null : key4.equals(multi.getKey(3))); + (key1 == multi.getKey(0) || key1 != null && key1.equals(multi.getKey(0))) && + (key2 == multi.getKey(1) || key2 != null && key2.equals(multi.getKey(1))) && + (key3 == multi.getKey(2) || key3 != null && key3.equals(multi.getKey(2))) && + (key4 == multi.getKey(3) || key4 != null && key4.equals(multi.getKey(3))); } //----------------------------------------------------------------------- @@ -545,9 +540,9 @@ public class MultiKeyMap * @param key5 the fifth key * @return the mapped value, null if no match */ - public Object get(Object key1, Object key2, Object key3, Object key4, Object key5) { + public V get(Object key1, Object key2, Object key3, Object key4, Object key5) { int hashCode = hash(key1, key2, key3, key4, key5); - AbstractHashedMap.HashEntry entry = map.data[map.hashIndex(hashCode, map.data.length)]; + AbstractHashedMap.HashEntry, V> entry = decorated().data[decorated().hashIndex(hashCode, decorated().data.length)]; while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(entry, key1, key2, key3, key4, key5)) { return entry.getValue(); @@ -569,7 +564,7 @@ public class MultiKeyMap */ public boolean containsKey(Object key1, Object key2, Object key3, Object key4, Object key5) { int hashCode = hash(key1, key2, key3, key4, key5); - AbstractHashedMap.HashEntry entry = map.data[map.hashIndex(hashCode, map.data.length)]; + AbstractHashedMap.HashEntry, V> entry = decorated().data[decorated().hashIndex(hashCode, decorated().data.length)]; while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(entry, key1, key2, key3, key4, key5)) { return true; @@ -590,20 +585,19 @@ public class MultiKeyMap * @param value the value to store * @return the value previously mapped to this combined key, null if none */ - public Object put(Object key1, Object key2, Object key3, Object key4, Object key5, Object value) { + public V put(K key1, K key2, K key3, K key4, K key5, V value) { int hashCode = hash(key1, key2, key3, key4, key5); - int index = map.hashIndex(hashCode, map.data.length); - AbstractHashedMap.HashEntry entry = map.data[index]; + int index = decorated().hashIndex(hashCode, decorated().data.length); + AbstractHashedMap.HashEntry, V> entry = decorated().data[index]; while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(entry, key1, key2, key3, key4, key5)) { - Object oldValue = entry.getValue(); - map.updateEntry(entry, value); + V oldValue = entry.getValue(); + decorated().updateEntry(entry, value); return oldValue; } entry = entry.next; } - - map.addMapping(index, hashCode, new MultiKey(key1, key2, key3, key4, key5), value); + decorated().addMapping(index, hashCode, new MultiKey(key1, key2, key3, key4, key5), value); return null; } @@ -617,15 +611,15 @@ public class MultiKeyMap * @param key5 the fifth key * @return the value mapped to the removed key, null if key not in map */ - public Object remove(Object key1, Object key2, Object key3, Object key4, Object key5) { + public V remove(Object key1, Object key2, Object key3, Object key4, Object key5) { int hashCode = hash(key1, key2, key3, key4, key5); - int index = map.hashIndex(hashCode, map.data.length); - AbstractHashedMap.HashEntry entry = map.data[index]; - AbstractHashedMap.HashEntry previous = null; + int index = decorated().hashIndex(hashCode, decorated().data.length); + AbstractHashedMap.HashEntry, V> entry = decorated().data[index]; + AbstractHashedMap.HashEntry, V> previous = null; while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(entry, key1, key2, key3, key4, key5)) { - Object oldValue = entry.getValue(); - map.removeMapping(entry, index, previous); + V oldValue = entry.getValue(); + decorated().removeMapping(entry, index, previous); return oldValue; } previous = entry; @@ -679,15 +673,16 @@ public class MultiKeyMap * @param key5 the fifth key * @return true if the key matches */ - protected boolean isEqualKey(AbstractHashedMap.HashEntry entry, Object key1, Object key2, Object key3, Object key4, Object key5) { - MultiKey multi = (MultiKey) entry.getKey(); + protected boolean isEqualKey(AbstractHashedMap.HashEntry, V> entry, + Object key1, Object key2, Object key3, Object key4, Object key5) { + MultiKey multi = entry.getKey(); return multi.size() == 5 && - (key1 == null ? multi.getKey(0) == null : key1.equals(multi.getKey(0))) && - (key2 == null ? multi.getKey(1) == null : key2.equals(multi.getKey(1))) && - (key3 == null ? multi.getKey(2) == null : key3.equals(multi.getKey(2))) && - (key4 == null ? multi.getKey(3) == null : key4.equals(multi.getKey(3))) && - (key5 == null ? multi.getKey(4) == null : key5.equals(multi.getKey(4))); + (key1 == multi.getKey(0) || key1 != null && key1.equals(multi.getKey(0))) && + (key2 == multi.getKey(1) || key2 != null && key2.equals(multi.getKey(1))) && + (key3 == multi.getKey(2) || key3 != null && key3.equals(multi.getKey(2))) && + (key4 == multi.getKey(3) || key4 != null && key4.equals(multi.getKey(3))) && + (key5 == multi.getKey(4) || key5 != null && key5.equals(multi.getKey(4))); } //----------------------------------------------------------------------- @@ -702,9 +697,9 @@ public class MultiKeyMap */ public boolean removeAll(Object key1) { boolean modified = false; - MapIterator it = mapIterator(); + MapIterator, V> it = mapIterator(); while (it.hasNext()) { - MultiKey multi = (MultiKey) it.next(); + MultiKey multi = it.next(); if (multi.size() >= 1 && (key1 == null ? multi.getKey(0) == null : key1.equals(multi.getKey(0)))) { it.remove(); @@ -726,9 +721,9 @@ public class MultiKeyMap */ public boolean removeAll(Object key1, Object key2) { boolean modified = false; - MapIterator it = mapIterator(); + MapIterator, V> it = mapIterator(); while (it.hasNext()) { - MultiKey multi = (MultiKey) it.next(); + MultiKey multi = it.next(); if (multi.size() >= 2 && (key1 == null ? multi.getKey(0) == null : key1.equals(multi.getKey(0))) && (key2 == null ? multi.getKey(1) == null : key2.equals(multi.getKey(1)))) { @@ -752,9 +747,9 @@ public class MultiKeyMap */ public boolean removeAll(Object key1, Object key2, Object key3) { boolean modified = false; - MapIterator it = mapIterator(); + MapIterator, V> it = mapIterator(); while (it.hasNext()) { - MultiKey multi = (MultiKey) it.next(); + MultiKey multi = it.next(); if (multi.size() >= 3 && (key1 == null ? multi.getKey(0) == null : key1.equals(multi.getKey(0))) && (key2 == null ? multi.getKey(1) == null : key2.equals(multi.getKey(1))) && @@ -780,9 +775,9 @@ public class MultiKeyMap */ public boolean removeAll(Object key1, Object key2, Object key3, Object key4) { boolean modified = false; - MapIterator it = mapIterator(); + MapIterator, V> it = mapIterator(); while (it.hasNext()) { - MultiKey multi = (MultiKey) it.next(); + MultiKey multi = it.next(); if (multi.size() >= 4 && (key1 == null ? multi.getKey(0) == null : key1.equals(multi.getKey(0))) && (key2 == null ? multi.getKey(1) == null : key2.equals(multi.getKey(1))) && @@ -801,13 +796,10 @@ public class MultiKeyMap * * @param key the key to check */ - protected void checkKey(Object key) { + protected void checkKey(MultiKey key) { if (key == null) { throw new NullPointerException("Key must not be null"); } - if (key instanceof MultiKey == false) { - throw new ClassCastException("Key must be a MultiKey"); - } } /** @@ -815,8 +807,8 @@ public class MultiKeyMap * * @return a shallow clone */ - public Object clone() { - return new MultiKeyMap((AbstractHashedMap) map.clone()); + public MultiKeyMap clone() { + return new MultiKeyMap(decorated().clone()); } /** @@ -829,9 +821,9 @@ public class MultiKeyMap * @throws NullPointerException if the key is null * @throws ClassCastException if the key is not a MultiKey */ - public Object put(Object key, Object value) { + public V put(MultiKey key, V value) { checkKey(key); - return map.put(key, value); + return super.put(key, value); } /** @@ -842,72 +834,24 @@ public class MultiKeyMap * @throws NullPointerException if the mapToCopy or any key within is null * @throws ClassCastException if any key in mapToCopy is not a MultiKey */ - public void putAll(Map mapToCopy) { - for (Iterator it = mapToCopy.keySet().iterator(); it.hasNext();) { - Object key = it.next(); + @Override + public void putAll(Map, ? extends V> mapToCopy) { + for (MultiKey key : mapToCopy.keySet()) { checkKey(key); } - map.putAll(mapToCopy); + super.putAll(mapToCopy); } //----------------------------------------------------------------------- - public MapIterator mapIterator() { - return map.mapIterator(); + public MapIterator, V> mapIterator() { + return decorated().mapIterator(); } - public int size() { - return map.size(); + /** + * {@inheritDoc} + */ + @Override + protected AbstractHashedMap, V> decorated() { + return map; } - - public boolean isEmpty() { - return map.isEmpty(); - } - - public boolean containsKey(Object key) { - return map.containsKey(key); - } - - public boolean containsValue(Object value) { - return map.containsValue(value); - } - - public Object get(Object key) { - return map.get(key); - } - - public Object remove(Object key) { - return map.remove(key); - } - - public void clear() { - map.clear(); - } - - public Set keySet() { - return map.keySet(); - } - - public Collection values() { - return map.values(); - } - - public Set entrySet() { - return map.entrySet(); - } - - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - return map.equals(obj); - } - - public int hashCode() { - return map.hashCode(); - } - - public String toString() { - return map.toString(); - } - } diff --git a/src/java/org/apache/commons/collections/map/PredicatedSortedMap.java b/src/java/org/apache/commons/collections/map/PredicatedSortedMap.java index ea06ef18e..3bbf93a07 100644 --- a/src/java/org/apache/commons/collections/map/PredicatedSortedMap.java +++ b/src/java/org/apache/commons/collections/map/PredicatedSortedMap.java @@ -46,9 +46,7 @@ import org.apache.commons.collections.Predicate; * @author Stephen Colebourne * @author Paul Jack */ -public class PredicatedSortedMap - extends PredicatedMap - implements SortedMap { +public class PredicatedSortedMap extends PredicatedMap implements SortedMap { /** Serialization version */ private static final long serialVersionUID = 3359846175935304332L; @@ -64,8 +62,9 @@ public class PredicatedSortedMap * @param valuePredicate the predicate to validate to values, null means no check * @throws IllegalArgumentException if the map is null */ - public static SortedMap decorate(SortedMap map, Predicate keyPredicate, Predicate valuePredicate) { - return new PredicatedSortedMap(map, keyPredicate, valuePredicate); + public static SortedMap decorate(SortedMap map, + Predicate keyPredicate, Predicate valuePredicate) { + return new PredicatedSortedMap(map, keyPredicate, valuePredicate); } //----------------------------------------------------------------------- @@ -77,7 +76,8 @@ public class PredicatedSortedMap * @param valuePredicate the predicate to validate to values, null means no check * @throws IllegalArgumentException if the map is null */ - protected PredicatedSortedMap(SortedMap map, Predicate keyPredicate, Predicate valuePredicate) { + protected PredicatedSortedMap(SortedMap map, Predicate keyPredicate, + Predicate valuePredicate) { super(map, keyPredicate, valuePredicate); } @@ -87,36 +87,36 @@ public class PredicatedSortedMap * * @return the decorated map */ - protected SortedMap getSortedMap() { - return (SortedMap) map; + protected SortedMap getSortedMap() { + return (SortedMap) map; } //----------------------------------------------------------------------- - public Object firstKey() { + public K firstKey() { return getSortedMap().firstKey(); } - public Object lastKey() { + public K lastKey() { return getSortedMap().lastKey(); } - public Comparator comparator() { + public Comparator comparator() { return getSortedMap().comparator(); } - public SortedMap subMap(Object fromKey, Object toKey) { - SortedMap map = getSortedMap().subMap(fromKey, toKey); - return new PredicatedSortedMap(map, keyPredicate, valuePredicate); + public SortedMap subMap(K fromKey, K toKey) { + SortedMap map = getSortedMap().subMap(fromKey, toKey); + return new PredicatedSortedMap(map, keyPredicate, valuePredicate); } - public SortedMap headMap(Object toKey) { - SortedMap map = getSortedMap().headMap(toKey); - return new PredicatedSortedMap(map, keyPredicate, valuePredicate); + public SortedMap headMap(K toKey) { + SortedMap map = getSortedMap().headMap(toKey); + return new PredicatedSortedMap(map, keyPredicate, valuePredicate); } - public SortedMap tailMap(Object fromKey) { - SortedMap map = getSortedMap().tailMap(fromKey); - return new PredicatedSortedMap(map, keyPredicate, valuePredicate); + public SortedMap tailMap(K fromKey) { + SortedMap map = getSortedMap().tailMap(fromKey); + return new PredicatedSortedMap(map, keyPredicate, valuePredicate); } } diff --git a/src/java/org/apache/commons/collections/map/ReferenceIdentityMap.java b/src/java/org/apache/commons/collections/map/ReferenceIdentityMap.java index 5c743138a..74447ea53 100644 --- a/src/java/org/apache/commons/collections/map/ReferenceIdentityMap.java +++ b/src/java/org/apache/commons/collections/map/ReferenceIdentityMap.java @@ -70,7 +70,7 @@ import java.lang.ref.Reference; * * @author Stephen Colebourne */ -public class ReferenceIdentityMap extends AbstractReferenceMap implements Serializable { +public class ReferenceIdentityMap extends AbstractReferenceMap implements Serializable { /** Serialization version */ private static final long serialVersionUID = -1266190134568365852L; @@ -80,7 +80,8 @@ public class ReferenceIdentityMap extends AbstractReferenceMap implements Serial * use hard references to keys and soft references to values. */ public ReferenceIdentityMap() { - super(HARD, SOFT, DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR, false); + super(ReferenceStrength.HARD, ReferenceStrength.SOFT, DEFAULT_CAPACITY, + DEFAULT_LOAD_FACTOR, false); } /** @@ -92,7 +93,7 @@ public class ReferenceIdentityMap extends AbstractReferenceMap implements Serial * @param valueType the type of reference to use for values; * must be {@link #HARD}, {@link #SOFT}, {@link #WEAK} */ - public ReferenceIdentityMap(int keyType, int valueType) { + public ReferenceIdentityMap(ReferenceStrength keyType, ReferenceStrength valueType) { super(keyType, valueType, DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR, false); } @@ -107,7 +108,8 @@ public class ReferenceIdentityMap extends AbstractReferenceMap implements Serial * @param purgeValues should the value be automatically purged when the * key is garbage collected */ - public ReferenceIdentityMap(int keyType, int valueType, boolean purgeValues) { + public ReferenceIdentityMap(ReferenceStrength keyType, ReferenceStrength valueType, + boolean purgeValues) { super(keyType, valueType, DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR, purgeValues); } @@ -122,7 +124,8 @@ public class ReferenceIdentityMap extends AbstractReferenceMap implements Serial * @param capacity the initial capacity for the map * @param loadFactor the load factor for the map */ - public ReferenceIdentityMap(int keyType, int valueType, int capacity, float loadFactor) { + public ReferenceIdentityMap(ReferenceStrength keyType, ReferenceStrength valueType, + int capacity, float loadFactor) { super(keyType, valueType, capacity, loadFactor, false); } @@ -139,8 +142,8 @@ public class ReferenceIdentityMap extends AbstractReferenceMap implements Serial * @param purgeValues should the value be automatically purged when the * key is garbage collected */ - public ReferenceIdentityMap(int keyType, int valueType, int capacity, - float loadFactor, boolean purgeValues) { + public ReferenceIdentityMap(ReferenceStrength keyType, ReferenceStrength valueType, + int capacity, float loadFactor, boolean purgeValues) { super(keyType, valueType, capacity, loadFactor, purgeValues); } @@ -182,8 +185,8 @@ public class ReferenceIdentityMap extends AbstractReferenceMap implements Serial * @return true if equal by identity */ protected boolean isEqualKey(Object key1, Object key2) { - key2 = (keyType > HARD ? ((Reference) key2).get() : key2); - return (key1 == key2); + key2 = keyType == ReferenceStrength.HARD ? key2 : ((Reference) key2).get(); + return key1 == key2; } /** @@ -196,7 +199,7 @@ public class ReferenceIdentityMap extends AbstractReferenceMap implements Serial * @return true if equal by identity */ protected boolean isEqualValue(Object value1, Object value2) { - return (value1 == value2); + return value1 == value2; } //----------------------------------------------------------------------- diff --git a/src/java/org/apache/commons/collections/map/ReferenceMap.java b/src/java/org/apache/commons/collections/map/ReferenceMap.java index 6aae2bc99..3ffc5bb52 100644 --- a/src/java/org/apache/commons/collections/map/ReferenceMap.java +++ b/src/java/org/apache/commons/collections/map/ReferenceMap.java @@ -73,7 +73,7 @@ import java.io.Serializable; * @author Paul Jack * @author Stephen Colebourne */ -public class ReferenceMap extends AbstractReferenceMap implements Serializable { +public class ReferenceMap extends AbstractReferenceMap implements Serializable { /** Serialization version */ private static final long serialVersionUID = 1555089888138299607L; @@ -83,7 +83,8 @@ public class ReferenceMap extends AbstractReferenceMap implements Serializable { * use hard references to keys and soft references to values. */ public ReferenceMap() { - super(HARD, SOFT, DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR, false); + super(ReferenceStrength.HARD, ReferenceStrength.SOFT, DEFAULT_CAPACITY, + DEFAULT_LOAD_FACTOR, false); } /** @@ -95,7 +96,7 @@ public class ReferenceMap extends AbstractReferenceMap implements Serializable { * @param valueType the type of reference to use for values; * must be {@link #HARD}, {@link #SOFT}, {@link #WEAK} */ - public ReferenceMap(int keyType, int valueType) { + public ReferenceMap(ReferenceStrength keyType, ReferenceStrength valueType) { super(keyType, valueType, DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR, false); } @@ -110,7 +111,7 @@ public class ReferenceMap extends AbstractReferenceMap implements Serializable { * @param purgeValues should the value be automatically purged when the * key is garbage collected */ - public ReferenceMap(int keyType, int valueType, boolean purgeValues) { + public ReferenceMap(ReferenceStrength keyType, ReferenceStrength valueType, boolean purgeValues) { super(keyType, valueType, DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR, purgeValues); } @@ -126,7 +127,8 @@ public class ReferenceMap extends AbstractReferenceMap implements Serializable { * @param capacity the initial capacity for the map * @param loadFactor the load factor for the map */ - public ReferenceMap(int keyType, int valueType, int capacity, float loadFactor) { + public ReferenceMap(ReferenceStrength keyType, ReferenceStrength valueType, int capacity, + float loadFactor) { super(keyType, valueType, capacity, loadFactor, false); } @@ -144,8 +146,8 @@ public class ReferenceMap extends AbstractReferenceMap implements Serializable { * @param purgeValues should the value be automatically purged when the * key is garbage collected */ - public ReferenceMap(int keyType, int valueType, int capacity, - float loadFactor, boolean purgeValues) { + public ReferenceMap(ReferenceStrength keyType, ReferenceStrength valueType, int capacity, + float loadFactor, boolean purgeValues) { super(keyType, valueType, capacity, loadFactor, purgeValues); } diff --git a/src/java/org/apache/commons/collections/map/SingletonMap.java b/src/java/org/apache/commons/collections/map/SingletonMap.java index 20dcbbc97..4c670cfbf 100644 --- a/src/java/org/apache/commons/collections/map/SingletonMap.java +++ b/src/java/org/apache/commons/collections/map/SingletonMap.java @@ -27,7 +27,6 @@ import java.util.Set; import org.apache.commons.collections.BoundedMap; import org.apache.commons.collections.KeyValue; -import org.apache.commons.collections.MapIterator; import org.apache.commons.collections.OrderedMap; import org.apache.commons.collections.OrderedMapIterator; import org.apache.commons.collections.ResettableIterator; @@ -59,16 +58,16 @@ import org.apache.commons.collections.keyvalue.TiedMapEntry; * * @author Stephen Colebourne */ -public class SingletonMap - implements OrderedMap, BoundedMap, KeyValue, Serializable, Cloneable { +public class SingletonMap + implements OrderedMap, BoundedMap, KeyValue, Serializable, Cloneable { /** Serialization version */ private static final long serialVersionUID = -8931271118676803261L; /** Singleton key */ - private final Object key; + private final K key; /** Singleton value */ - private Object value; + private V value; /** * Constructor that creates a map of null to null. @@ -84,7 +83,7 @@ public class SingletonMap * @param key the key to use * @param value the value to use */ - public SingletonMap(Object key, Object value) { + public SingletonMap(K key, V value) { super(); this.key = key; this.value = value; @@ -95,7 +94,7 @@ public class SingletonMap * * @param keyValue the key value pair to use */ - public SingletonMap(KeyValue keyValue) { + public SingletonMap(KeyValue keyValue) { super(); this.key = keyValue.getKey(); this.value = keyValue.getValue(); @@ -106,7 +105,7 @@ public class SingletonMap * * @param mapEntry the mapEntry to use */ - public SingletonMap(Map.Entry mapEntry) { + public SingletonMap(Map.Entry mapEntry) { super(); this.key = mapEntry.getKey(); this.value = mapEntry.getValue(); @@ -119,12 +118,12 @@ public class SingletonMap * @throws NullPointerException if the map is null * @throws IllegalArgumentException if the size is not 1 */ - public SingletonMap(Map map) { + public SingletonMap(Map map) { super(); if (map.size() != 1) { throw new IllegalArgumentException("The map size must be 1"); } - Map.Entry entry = (Map.Entry) map.entrySet().iterator().next(); + Map.Entry entry = map.entrySet().iterator().next(); this.key = entry.getKey(); this.value = entry.getValue(); } @@ -136,7 +135,7 @@ public class SingletonMap * * @return the key */ - public Object getKey() { + public K getKey() { return key; } @@ -145,7 +144,7 @@ public class SingletonMap * * @return the value */ - public Object getValue() { + public V getValue() { return value; } @@ -155,8 +154,8 @@ public class SingletonMap * @param value the new value to set * @return the old value */ - public Object setValue(Object value) { - Object old = this.value; + public V setValue(V value) { + V old = this.value; this.value = value; return old; } @@ -189,7 +188,7 @@ public class SingletonMap * @param key the key * @return the mapped value, null if no match */ - public Object get(Object key) { + public V get(Object key) { if (isEqualKey(key)) { return value; } @@ -247,7 +246,7 @@ public class SingletonMap * @return the value previously mapped to this key, null if none * @throws IllegalArgumentException if the key does not match */ - public Object put(Object key, Object value) { + public V put(K key, V value) { if (isEqualKey(key)) { return setValue(value); } @@ -265,21 +264,21 @@ public class SingletonMap * @throws NullPointerException if the map is null * @throws IllegalArgumentException if the key does not match */ - public void putAll(Map map) { + public void putAll(Map map) { switch (map.size()) { case 0: return; - + case 1: - Map.Entry entry = (Map.Entry) map.entrySet().iterator().next(); + Map.Entry entry = map.entrySet().iterator().next(); put(entry.getKey(), entry.getValue()); return; - + default: throw new IllegalArgumentException("The map size must be 0 or 1"); } } - + /** * Unsupported operation. * @@ -287,7 +286,7 @@ public class SingletonMap * @return the value mapped to the removed key, null if key not in map * @throws UnsupportedOperationException always */ - public Object remove(Object key) { + public V remove(Object key) { throw new UnsupportedOperationException(); } @@ -306,8 +305,8 @@ public class SingletonMap * * @return the entrySet view */ - public Set entrySet() { - Map.Entry entry = new TiedMapEntry(this, getKey()); + public Set> entrySet() { + Map.Entry entry = new TiedMapEntry(this, getKey()); return Collections.singleton(entry); } @@ -318,7 +317,7 @@ public class SingletonMap * * @return the keySet view */ - public Set keySet() { + public Set keySet() { return Collections.singleton(key); } @@ -329,38 +328,15 @@ public class SingletonMap * * @return the values view */ - public Collection values() { - return new SingletonValues(this); + public Collection values() { + return new SingletonValues(this); } /** - * Gets an iterator over the map. - * Changes made to the iterator using setValue affect this map. - * The remove method is unsupported. - *

- * A MapIterator returns the keys in the map. It also provides convenient - * methods to get the key and value, and set the value. - * It avoids the need to create an entrySet/keySet/values object. - * It also avoids creating the Map Entry object. - * - * @return the map iterator + * {@inheritDoc} */ - public MapIterator mapIterator() { - return new SingletonMapIterator(this); - } - - // OrderedMap - //----------------------------------------------------------------------- - /** - * Obtains an OrderedMapIterator over the map. - *

- * A ordered map iterator is an efficient way of iterating over maps - * in both directions. - * - * @return an ordered map iterator - */ - public OrderedMapIterator orderedMapIterator() { - return new SingletonMapIterator(this); + public OrderedMapIterator mapIterator() { + return new SingletonMapIterator(this); } /** @@ -368,7 +344,7 @@ public class SingletonMap * * @return the key */ - public Object firstKey() { + public K firstKey() { return getKey(); } @@ -377,7 +353,7 @@ public class SingletonMap * * @return the key */ - public Object lastKey() { + public K lastKey() { return getKey(); } @@ -387,7 +363,7 @@ public class SingletonMap * @param key the next key * @return null always */ - public Object nextKey(Object key) { + public K nextKey(K key) { return null; } @@ -397,7 +373,7 @@ public class SingletonMap * @param key the next key * @return null always */ - public Object previousKey(Object key) { + public K previousKey(K key) { return null; } @@ -426,12 +402,12 @@ public class SingletonMap /** * SingletonMapIterator. */ - static class SingletonMapIterator implements OrderedMapIterator, ResettableIterator { - private final SingletonMap parent; + static class SingletonMapIterator implements OrderedMapIterator, ResettableIterator { + private final SingletonMap parent; private boolean hasNext = true; private boolean canGetSet = false; - SingletonMapIterator(SingletonMap parent) { + SingletonMapIterator(SingletonMap parent) { super(); this.parent = parent; } @@ -440,7 +416,7 @@ public class SingletonMap return hasNext; } - public Object next() { + public K next() { if (hasNext == false) { throw new NoSuchElementException(AbstractHashedMap.NO_NEXT_ENTRY); } @@ -453,7 +429,7 @@ public class SingletonMap return (hasNext == false); } - public Object previous() { + public K previous() { if (hasNext == true) { throw new NoSuchElementException(AbstractHashedMap.NO_PREVIOUS_ENTRY); } @@ -465,21 +441,21 @@ public class SingletonMap throw new UnsupportedOperationException(); } - public Object getKey() { + public K getKey() { if (canGetSet == false) { throw new IllegalStateException(AbstractHashedMap.GETKEY_INVALID); } return parent.getKey(); } - public Object getValue() { + public V getValue() { if (canGetSet == false) { throw new IllegalStateException(AbstractHashedMap.GETVALUE_INVALID); } return parent.getValue(); } - public Object setValue(Object value) { + public V setValue(V value) { if (canGetSet == false) { throw new IllegalStateException(AbstractHashedMap.SETVALUE_INVALID); } @@ -493,9 +469,8 @@ public class SingletonMap public String toString() { if (hasNext) { return "Iterator[]"; - } else { - return "Iterator[" + getKey() + "=" + getValue() + "]"; } + return "Iterator[" + getKey() + "=" + getValue() + "]"; } } @@ -503,11 +478,11 @@ public class SingletonMap * Values implementation for the SingletonMap. * This class is needed as values is a view that must update as the map updates. */ - static class SingletonValues extends AbstractSet implements Serializable { + static class SingletonValues extends AbstractSet implements Serializable { private static final long serialVersionUID = -3689524741863047872L; - private final SingletonMap parent; + private final SingletonMap parent; - SingletonValues(SingletonMap parent) { + SingletonValues(SingletonMap parent) { super(); this.parent = parent; } @@ -524,8 +499,8 @@ public class SingletonMap public void clear() { throw new UnsupportedOperationException(); } - public Iterator iterator() { - return new SingletonIterator(parent.getValue(), false); + public Iterator iterator() { + return new SingletonIterator(parent.getValue(), false); } } @@ -535,10 +510,10 @@ public class SingletonMap * * @return a shallow clone */ - public Object clone() { + @SuppressWarnings("unchecked") + public SingletonMap clone() { try { - SingletonMap cloned = (SingletonMap) super.clone(); - return cloned; + return (SingletonMap) super.clone(); } catch (CloneNotSupportedException ex) { throw new InternalError(); } @@ -550,6 +525,7 @@ public class SingletonMap * @param obj the object to compare to * @return true if equal */ + @SuppressWarnings("unchecked") public boolean equals(Object obj) { if (obj == this) { return true; diff --git a/src/java/org/apache/commons/collections/map/UnmodifiableEntrySet.java b/src/java/org/apache/commons/collections/map/UnmodifiableEntrySet.java index 484cb27ea..e17f6f96d 100644 --- a/src/java/org/apache/commons/collections/map/UnmodifiableEntrySet.java +++ b/src/java/org/apache/commons/collections/map/UnmodifiableEntrySet.java @@ -37,8 +37,11 @@ import org.apache.commons.collections.set.AbstractSetDecorator; * * @author Stephen Colebourne */ -public final class UnmodifiableEntrySet - extends AbstractSetDecorator implements Unmodifiable { +public final class UnmodifiableEntrySet + extends AbstractSetDecorator> implements Unmodifiable { + + /** Serialization version */ + private static final long serialVersionUID = 1678353579659253473L; /** * Factory method to create an unmodifiable set of Map Entry objects. @@ -46,11 +49,11 @@ public final class UnmodifiableEntrySet * @param set the set to decorate, must not be null * @throws IllegalArgumentException if set is null */ - public static Set decorate(Set set) { + public static Set> decorate(Set> set) { if (set instanceof Unmodifiable) { return set; } - return new UnmodifiableEntrySet(set); + return new UnmodifiableEntrySet(set); } //----------------------------------------------------------------------- @@ -60,16 +63,16 @@ public final class UnmodifiableEntrySet * @param set the set to decorate, must not be null * @throws IllegalArgumentException if set is null */ - private UnmodifiableEntrySet(Set set) { + private UnmodifiableEntrySet(Set> set) { super(set); } //----------------------------------------------------------------------- - public boolean add(Object object) { + public boolean add(Map.Entry object) { throw new UnsupportedOperationException(); } - public boolean addAll(Collection coll) { + public boolean addAll(Collection> coll) { throw new UnsupportedOperationException(); } @@ -81,28 +84,30 @@ public final class UnmodifiableEntrySet 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 Iterator iterator() { + public Iterator> iterator() { return new UnmodifiableEntrySetIterator(collection.iterator()); } + @SuppressWarnings("unchecked") public Object[] toArray() { Object[] array = collection.toArray(); for (int i = 0; i < array.length; i++) { - array[i] = new UnmodifiableEntry((Map.Entry) array[i]); + array[i] = new UnmodifiableEntry((Map.Entry) array[i]); } return array; } - public Object[] toArray(Object array[]) { + @SuppressWarnings("unchecked") + public T[] toArray(T[] array) { Object[] result = array; if (array.length > 0) { // we must create a new array to handle multi-threaded situations @@ -111,15 +116,15 @@ public final class UnmodifiableEntrySet } result = collection.toArray(result); for (int i = 0; i < result.length; i++) { - result[i] = new UnmodifiableEntry((Map.Entry) result[i]); + result[i] = new UnmodifiableEntry((Map.Entry) result[i]); } // check to see if result should be returned straight if (result.length > array.length) { - return result; + return (T[]) result; } - // copy back into input array to fulfil the method contract + // copy back into input array to fulfill the method contract System.arraycopy(result, 0, array, 0, result.length); if (array.length > result.length) { array[result.length] = null; @@ -131,17 +136,16 @@ public final class UnmodifiableEntrySet /** * Implementation of an entry set iterator. */ - final static class UnmodifiableEntrySetIterator extends AbstractIteratorDecorator { - - protected UnmodifiableEntrySetIterator(Iterator iterator) { + private class UnmodifiableEntrySetIterator extends AbstractIteratorDecorator> { + + protected UnmodifiableEntrySetIterator(Iterator> iterator) { super(iterator); } - - public Object next() { - Map.Entry entry = (Map.Entry) iterator.next(); - return new UnmodifiableEntry(entry); + + public Map.Entry next() { + return new UnmodifiableEntry(iterator.next()); } - + public void remove() { throw new UnsupportedOperationException(); } @@ -151,13 +155,13 @@ public final class UnmodifiableEntrySet /** * Implementation of a map entry that is unmodifiable. */ - final static class UnmodifiableEntry extends AbstractMapEntryDecorator { + private class UnmodifiableEntry extends AbstractMapEntryDecorator { - protected UnmodifiableEntry(Map.Entry entry) { + protected UnmodifiableEntry(Map.Entry entry) { super(entry); } - public Object setValue(Object obj) { + public V setValue(V obj) { throw new UnsupportedOperationException(); } } diff --git a/src/java/org/apache/commons/collections/map/UnmodifiableMap.java b/src/java/org/apache/commons/collections/map/UnmodifiableMap.java index accd685fd..433aead27 100644 --- a/src/java/org/apache/commons/collections/map/UnmodifiableMap.java +++ b/src/java/org/apache/commons/collections/map/UnmodifiableMap.java @@ -44,9 +44,9 @@ import org.apache.commons.collections.set.UnmodifiableSet; * * @author Stephen Colebourne */ -public final class UnmodifiableMap - extends AbstractMapDecorator - implements IterableMap, Unmodifiable, Serializable { +public final class UnmodifiableMap + extends AbstractMapDecorator + implements IterableMap, Unmodifiable, Serializable { /** Serialization version */ private static final long serialVersionUID = 2737023427269031941L; @@ -57,11 +57,11 @@ public final class UnmodifiableMap * @param map the map to decorate, must not be null * @throws IllegalArgumentException if map is null */ - public static Map decorate(Map map) { + public static Map decorate(Map map) { if (map instanceof Unmodifiable) { return map; } - return new UnmodifiableMap(map); + return new UnmodifiableMap(map); } //----------------------------------------------------------------------- @@ -71,7 +71,7 @@ public final class UnmodifiableMap * @param map the map to decorate, must not be null * @throws IllegalArgumentException if map is null */ - private UnmodifiableMap(Map map) { + private UnmodifiableMap(Map map) { super(map); } @@ -96,9 +96,10 @@ public final class UnmodifiableMap * @throws ClassNotFoundException * @since Commons Collections 3.1 */ + @SuppressWarnings("unchecked") private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); - map = (Map) in.readObject(); + map = (Map) in.readObject(); } //----------------------------------------------------------------------- @@ -106,40 +107,39 @@ public final class UnmodifiableMap 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 mapToCopy) { throw new UnsupportedOperationException(); } - public Object remove(Object key) { + public V remove(Object key) { throw new UnsupportedOperationException(); } - public MapIterator mapIterator() { + public MapIterator mapIterator() { if (map instanceof IterableMap) { - MapIterator it = ((IterableMap) map).mapIterator(); - return UnmodifiableMapIterator.decorate(it); - } else { - MapIterator it = new EntrySetMapIterator(map); + MapIterator it = ((IterableMap) map).mapIterator(); return UnmodifiableMapIterator.decorate(it); } + MapIterator it = new EntrySetMapIterator(map); + return UnmodifiableMapIterator.decorate(it); } - public Set entrySet() { - Set set = super.entrySet(); + public Set> entrySet() { + Set> set = super.entrySet(); return UnmodifiableEntrySet.decorate(set); } - public Set keySet() { - Set set = super.keySet(); + public Set keySet() { + Set set = super.keySet(); return UnmodifiableSet.decorate(set); } - public Collection values() { - Collection coll = super.values(); + public Collection values() { + Collection coll = super.values(); return UnmodifiableCollection.decorate(coll); } diff --git a/src/java/org/apache/commons/collections/set/AbstractSerializableSetDecorator.java b/src/java/org/apache/commons/collections/set/AbstractSerializableSetDecorator.java index df8d11a44..ab65872ec 100644 --- a/src/java/org/apache/commons/collections/set/AbstractSerializableSetDecorator.java +++ b/src/java/org/apache/commons/collections/set/AbstractSerializableSetDecorator.java @@ -29,8 +29,8 @@ import java.util.Set; * @author Stephen Colebourne * @since Commons Collections 3.1 */ -public abstract class AbstractSerializableSetDecorator - extends AbstractSetDecorator +public abstract class AbstractSerializableSetDecorator + extends AbstractSetDecorator implements Serializable { /** Serialization version */ @@ -39,7 +39,7 @@ public abstract class AbstractSerializableSetDecorator /** * Constructor. */ - protected AbstractSerializableSetDecorator(Set set) { + protected AbstractSerializableSetDecorator(Set set) { super(set); } @@ -62,9 +62,10 @@ public abstract class AbstractSerializableSetDecorator * @throws IOException * @throws ClassNotFoundException */ + @SuppressWarnings("unchecked") private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); - collection = (Collection) in.readObject(); + collection = (Collection) in.readObject(); } } diff --git a/src/java/org/apache/commons/collections/set/CompositeSet.java b/src/java/org/apache/commons/collections/set/CompositeSet.java index 7c40d9ed9..1e53d8d06 100644 --- a/src/java/org/apache/commons/collections/set/CompositeSet.java +++ b/src/java/org/apache/commons/collections/set/CompositeSet.java @@ -17,7 +17,7 @@ package org.apache.commons.collections.set; import java.util.Collection; -import java.util.Iterator; +import java.util.List; import java.util.Set; import org.apache.commons.collections.CollectionUtils; @@ -35,29 +35,30 @@ import org.apache.commons.collections.collection.CompositeCollection; * * @author Brian McCallister */ -public class CompositeSet extends CompositeCollection implements Set { +public class CompositeSet extends CompositeCollection implements Set { + /** * Create an empty CompositeSet */ public CompositeSet() { super(); } - + /** * Create a CompositeSet with just set composited * @param set The initial set in the composite */ - public CompositeSet(Set set) { + public CompositeSet(Set set) { super(set); } - + /** * Create a composite set with sets as the initial set of composited Sets */ - public CompositeSet(Set[] sets) { + public CompositeSet(Set[] sets) { super(sets); } - + /** * Add a Set to this composite * @@ -69,14 +70,13 @@ public class CompositeSet extends CompositeCollection implements Set { * @see org.apache.commons.collections.collection.CompositeCollection.CollectionMutator * @see SetMutator */ - public synchronized void addComposited(Collection c) { + public synchronized void addComposited(Collection c) { if (!(c instanceof Set)) { throw new IllegalArgumentException("Collections added must implement java.util.Set"); } - - for (Iterator i = this.getCollections().iterator(); i.hasNext();) { - Set set = (Set) i.next(); - Collection intersects = CollectionUtils.intersection(set, c); + + for (Set set : getCollections()) { + Collection intersects = CollectionUtils.intersection(set, c); if (intersects.size() > 0) { if (this.mutator == null) { throw new UnsupportedOperationException( @@ -86,38 +86,48 @@ public class CompositeSet extends CompositeCollection implements Set { throw new UnsupportedOperationException( "Collision adding composited collection to a CompositeSet with a CollectionMutator instead of a SetMutator"); } - ((SetMutator) this.mutator).resolveCollision(this, set, (Set) c, intersects); + getMutator().resolveCollision(this, set, (Set) c, intersects); if (CollectionUtils.intersection(set, c).size() > 0) { throw new IllegalArgumentException( "Attempt to add illegal entry unresolved by SetMutator.resolveCollision()"); } } } - super.addComposited(new Collection[]{c}); + super.addComposited(c); } - + + /** + * {@inheritDoc} + */ + @SuppressWarnings("unchecked") + @Override + public List> getCollections() { + return (List>) super.getCollections(); + } + /** * Add two sets to this composite * * @throws IllegalArgumentException if c or d does not implement java.util.Set */ - public synchronized void addComposited(Collection c, Collection d) { + @SuppressWarnings("unchecked") + public synchronized void addComposited(Collection c, Collection d) { if (!(c instanceof Set)) throw new IllegalArgumentException("Argument must implement java.util.Set"); if (!(d instanceof Set)) throw new IllegalArgumentException("Argument must implement java.util.Set"); - this.addComposited(new Set[]{(Set) c, (Set) d}); + this.addComposited(new Set[] { (Set) c, (Set) d }); } - + /** * Add an array of sets to this composite * @param comps * @throws IllegalArgumentException if any of the collections in comps do not implement Set */ - public synchronized void addComposited(Collection[] comps) { + public synchronized void addComposited(Collection[] comps) { for (int i = comps.length - 1; i >= 0; --i) { this.addComposited(comps[i]); } } - + /** * This can receive either a CompositeCollection.CollectionMutator * or a CompositeSet.SetMutator. If a @@ -125,12 +135,12 @@ public class CompositeSet extends CompositeCollection implements Set { * composited sets will throw IllegalArgumentException *

*/ - public void setMutator(CollectionMutator mutator) { + public void setMutator(CollectionMutator mutator) { super.setMutator(mutator); } - + /* Set operations */ - + /** * If a CollectionMutator is defined for this CompositeSet then this * method will be called anyway. @@ -139,46 +149,51 @@ public class CompositeSet extends CompositeCollection implements Set { * @return true if the object is removed, false otherwise */ public boolean remove(Object obj) { - for (Iterator i = this.getCollections().iterator(); i.hasNext();) { - Set set = (Set) i.next(); + for (Set set : getCollections()) { if (set.contains(obj)) return set.remove(obj); } return false; } - - + /** * @see Set#equals */ + @SuppressWarnings("unchecked") public boolean equals(Object obj) { if (obj instanceof Set) { Set set = (Set) obj; - if (set.containsAll(this) && set.size() == this.size()) { - return true; - } + return set.containsAll(this) && set.size() == this.size(); } return false; } - + /** * @see Set#hashCode */ public int hashCode() { int code = 0; - for (Iterator i = this.iterator(); i.hasNext();) { - Object next = i.next(); - code += (next != null ? next.hashCode() : 0); + for (E e : this) { + code += (e == null ? 0 : e.hashCode()); } return code; } - + + /** + * {@inheritDoc} + */ + @Override + protected SetMutator getMutator() { + return (SetMutator) super.getMutator(); + } + /** * Define callbacks for mutation operations. *

* Defining remove() on implementations of SetMutator is pointless * as they are never called by CompositeSet. */ - public static interface SetMutator extends CompositeCollection.CollectionMutator { + public static interface SetMutator extends CompositeCollection.CollectionMutator { + /** *

* Called when a Set is added to the CompositeSet and there is a @@ -193,6 +208,6 @@ public class CompositeSet extends CompositeCollection implements Set { * @param added the Set being added to the composite * @param intersects the intersection of th existing and added sets */ - public void resolveCollision(CompositeSet comp, Set existing, Set added, Collection intersects); + public void resolveCollision(CompositeSet comp, Set existing, Set added, Collection intersects); } } diff --git a/src/java/org/apache/commons/collections/set/MapBackedSet.java b/src/java/org/apache/commons/collections/set/MapBackedSet.java index 84713cc27..a208f7bad 100644 --- a/src/java/org/apache/commons/collections/set/MapBackedSet.java +++ b/src/java/org/apache/commons/collections/set/MapBackedSet.java @@ -37,15 +37,16 @@ import java.util.Set; * * @author Stephen Colebourne */ -public final class MapBackedSet implements Set, Serializable { +public final class MapBackedSet implements Set, Serializable { /** Serialization version */ private static final long serialVersionUID = 6723912213766056587L; /** The map being used as the backing store */ - protected final Map map; + protected final Map map; + /** The dummyValue to use */ - protected final Object dummyValue; + protected final V dummyValue; /** * Factory method to create a set from a map. @@ -53,7 +54,7 @@ public final class MapBackedSet implements Set, Serializable { * @param map the map to decorate, must not be null * @throws IllegalArgumentException if set is null */ - public static Set decorate(Map map) { + public static Set decorate(Map map) { return decorate(map, null); } @@ -64,11 +65,11 @@ public final class MapBackedSet implements Set, Serializable { * @param dummyValue the dummy value to use * @throws IllegalArgumentException if map is null */ - public static Set decorate(Map map, Object dummyValue) { + public static Set decorate(Map map, V dummyValue) { if (map == null) { throw new IllegalArgumentException("The map must not be null"); } - return new MapBackedSet(map, dummyValue); + return new MapBackedSet(map, dummyValue); } //----------------------------------------------------------------------- @@ -79,7 +80,7 @@ public final class MapBackedSet implements Set, Serializable { * @param dummyValue the dummy value to use * @throws IllegalArgumentException if map is null */ - private MapBackedSet(Map map, Object dummyValue) { + private MapBackedSet(Map map, V dummyValue) { super(); this.map = map; this.dummyValue = dummyValue; @@ -94,7 +95,7 @@ public final class MapBackedSet implements Set, Serializable { return map.isEmpty(); } - public Iterator iterator() { + public Iterator iterator() { return map.keySet().iterator(); } @@ -102,21 +103,20 @@ public final class MapBackedSet implements Set, Serializable { return map.containsKey(obj); } - public boolean containsAll(Collection coll) { + public boolean containsAll(Collection coll) { return map.keySet().containsAll(coll); } - public boolean add(Object obj) { + public boolean add(E obj) { int size = map.size(); map.put(obj, dummyValue); return (map.size() != size); } - public boolean addAll(Collection coll) { + public boolean addAll(Collection coll) { int size = map.size(); - for (Iterator it = coll.iterator(); it.hasNext();) { - Object obj = it.next(); - map.put(obj, dummyValue); + for (E e : coll) { + map.put(e, dummyValue); } return (map.size() != size); } @@ -127,11 +127,11 @@ public final class MapBackedSet implements Set, Serializable { return (map.size() != size); } - public boolean removeAll(Collection coll) { + public boolean removeAll(Collection coll) { return map.keySet().removeAll(coll); } - public boolean retainAll(Collection coll) { + public boolean retainAll(Collection coll) { return map.keySet().retainAll(coll); } @@ -143,7 +143,7 @@ public final class MapBackedSet implements Set, Serializable { return map.keySet().toArray(); } - public Object[] toArray(Object[] array) { + public T[] toArray(T[] array) { return map.keySet().toArray(array); } diff --git a/src/java/org/apache/commons/collections/set/TransformedSet.java b/src/java/org/apache/commons/collections/set/TransformedSet.java index b6277746f..d34725b57 100644 --- a/src/java/org/apache/commons/collections/set/TransformedSet.java +++ b/src/java/org/apache/commons/collections/set/TransformedSet.java @@ -36,7 +36,7 @@ import org.apache.commons.collections.collection.TransformedCollection; * * @author Stephen Colebourne */ -public class TransformedSet extends TransformedCollection implements Set { +public class TransformedSet extends TransformedCollection implements Set { /** Serialization version */ private static final long serialVersionUID = 306127383500410386L; @@ -52,8 +52,8 @@ public class TransformedSet extends TransformedCollection implements Set { * @param transformer the transformer to use for conversion, must not be null * @throws IllegalArgumentException if set or transformer is null */ - public static Set decorate(Set set, Transformer transformer) { - return new TransformedSet(set, transformer); + public static Set decorate(Set set, Transformer transformer) { + return new TransformedSet(set, transformer); } /** @@ -70,13 +70,14 @@ public class TransformedSet extends TransformedCollection implements Set { * @throws IllegalArgumentException if set or transformer is null * @since Commons Collections 3.3 */ + // TODO: Generics public static Set decorateTransform(Set set, Transformer transformer) { TransformedSet decorated = new TransformedSet(set, transformer); if (transformer != null && set != null && set.size() > 0) { Object[] values = set.toArray(); set.clear(); for(int i=0; i set, Transformer transformer) { super(set, transformer); } diff --git a/src/java/org/apache/commons/collections/set/TransformedSortedSet.java b/src/java/org/apache/commons/collections/set/TransformedSortedSet.java index 9cfb09967..47ee9f71e 100644 --- a/src/java/org/apache/commons/collections/set/TransformedSortedSet.java +++ b/src/java/org/apache/commons/collections/set/TransformedSortedSet.java @@ -36,7 +36,7 @@ import org.apache.commons.collections.Transformer; * * @author Stephen Colebourne */ -public class TransformedSortedSet extends TransformedSet implements SortedSet { +public class TransformedSortedSet extends TransformedSet implements SortedSet { /** Serialization version */ private static final long serialVersionUID = -1675486811351124386L; @@ -52,8 +52,8 @@ public class TransformedSortedSet extends TransformedSet implements SortedSet { * @param transformer the transformer to use for conversion, must not be null * @throws IllegalArgumentException if set or transformer is null */ - public static SortedSet decorate(SortedSet set, Transformer transformer) { - return new TransformedSortedSet(set, transformer); + public static SortedSet decorate(SortedSet set, Transformer transformer) { + return new TransformedSortedSet(set, transformer); } /** @@ -70,13 +70,14 @@ public class TransformedSortedSet extends TransformedSet implements SortedSet { * @throws IllegalArgumentException if set or transformer is null * @since Commons Collections 3.3 */ + // TODO: Generics public static SortedSet decorateTransform(SortedSet set, Transformer transformer) { TransformedSortedSet decorated = new TransformedSortedSet(set, transformer); if (transformer != null && set != null && set.size() > 0) { Object[] values = set.toArray(); set.clear(); for(int i=0; i set, Transformer transformer) { super(set, transformer); } @@ -102,37 +103,37 @@ public class TransformedSortedSet extends TransformedSet implements SortedSet { * * @return the decorated set */ - protected SortedSet getSortedSet() { - return (SortedSet) collection; + protected SortedSet getSortedSet() { + return (SortedSet) collection; } //----------------------------------------------------------------------- - public Object first() { + public E first() { return getSortedSet().first(); } - public Object last() { + public E last() { return getSortedSet().last(); } - public Comparator comparator() { + public Comparator comparator() { return getSortedSet().comparator(); } //----------------------------------------------------------------------- - public SortedSet subSet(Object fromElement, Object toElement) { - SortedSet set = getSortedSet().subSet(fromElement, toElement); - return new TransformedSortedSet(set, transformer); + public SortedSet subSet(E fromElement, E toElement) { + SortedSet set = getSortedSet().subSet(fromElement, toElement); + return new TransformedSortedSet(set, transformer); } - public SortedSet headSet(Object toElement) { - SortedSet set = getSortedSet().headSet(toElement); - return new TransformedSortedSet(set, transformer); + public SortedSet headSet(E toElement) { + SortedSet set = getSortedSet().headSet(toElement); + return new TransformedSortedSet(set, transformer); } - public SortedSet tailSet(Object fromElement) { - SortedSet set = getSortedSet().tailSet(fromElement); - return new TransformedSortedSet(set, transformer); + public SortedSet tailSet(E fromElement) { + SortedSet set = getSortedSet().tailSet(fromElement); + return new TransformedSortedSet(set, transformer); } } diff --git a/src/test/org/apache/commons/collections/AbstractTestObject.java b/src/test/org/apache/commons/collections/AbstractTestObject.java index 7e6570af9..b6128079e 100644 --- a/src/test/org/apache/commons/collections/AbstractTestObject.java +++ b/src/test/org/apache/commons/collections/AbstractTestObject.java @@ -173,7 +173,7 @@ public abstract class AbstractTestObject extends BulkTest { Object o = makeObject(); if (o instanceof Serializable && isTestSerialization()) { byte[] objekt = writeExternalFormToBytes((Serializable) o); - Object p = readExternalFormFromBytes(objekt); + readExternalFormFromBytes(objekt); } } diff --git a/src/test/org/apache/commons/collections/BulkTest.java b/src/test/org/apache/commons/collections/BulkTest.java index 999681a92..35cb26757 100644 --- a/src/test/org/apache/commons/collections/BulkTest.java +++ b/src/test/org/apache/commons/collections/BulkTest.java @@ -246,7 +246,7 @@ public class BulkTest extends TestCase implements Cloneable { * @return a {@link TestSuite} containing all the simple and bulk tests * defined by that class */ - public static TestSuite makeSuite(Class c) { + public static TestSuite makeSuite(Class c) { if (Modifier.isAbstract(c.getModifiers())) { throw new IllegalArgumentException("Class must not be abstract."); } @@ -265,10 +265,10 @@ public class BulkTest extends TestCase implements Cloneable { class BulkTestSuiteMaker { /** The class that defines simple and bulk tests methods. */ - private Class startingClass; + private Class startingClass; /** List of ignored simple test names. */ - private List ignored; + private List ignored; /** The TestSuite we're currently populating. Can change over time. */ private TestSuite result; @@ -284,7 +284,7 @@ class BulkTestSuiteMaker { * * @param startingClass the starting class */ - public BulkTestSuiteMaker(Class startingClass) { + public BulkTestSuiteMaker(Class startingClass) { this.startingClass = startingClass; } @@ -299,7 +299,7 @@ class BulkTestSuiteMaker { result.setName(prefix); BulkTest bulk = makeFirstTestCase(startingClass); - ignored = new ArrayList(); + ignored = new ArrayList(); String[] s = bulk.ignoredTests(); if (s != null) { ignored.addAll(Arrays.asList(s)); @@ -316,7 +316,7 @@ class BulkTestSuiteMaker { * tests for us to append */ void make(BulkTest bulk) { - Class c = bulk.getClass(); + Class c = bulk.getClass(); Method[] all = c.getMethods(); for (int i = 0; i < all.length; i++) { if (isTest(all[i])) addTest(bulk, all[i]); @@ -388,7 +388,7 @@ class BulkTestSuiteMaker { * @param c the class * @return the name of that class, minus any package names */ - private static String getBaseName(Class c) { + private static String getBaseName(Class c) { String name = c.getName(); int p = name.lastIndexOf('.'); if (p > 0) { @@ -401,7 +401,7 @@ class BulkTestSuiteMaker { // These three methods are used to create a valid BulkTest instance // from a class. - private static Constructor getTestCaseConstructor(Class c) { + private static Constructor getTestCaseConstructor(Class c) { try { return c.getConstructor(new Class[] { String.class }); } catch (NoSuchMethodException e) { @@ -410,10 +410,10 @@ class BulkTestSuiteMaker { } } - private static BulkTest makeTestCase(Class c, Method m) { - Constructor con = getTestCaseConstructor(c); + private static BulkTest makeTestCase(Class c, Method m) { + Constructor con = getTestCaseConstructor(c); try { - return (BulkTest)con.newInstance(new Object[] {m.getName()}); + return (BulkTest) con.newInstance(new Object[] { m.getName() }); } catch (InvocationTargetException e) { e.printStackTrace(); throw new RuntimeException(); // FIXME; @@ -424,7 +424,7 @@ class BulkTestSuiteMaker { } } - private static BulkTest makeFirstTestCase(Class c) { + private static BulkTest makeFirstTestCase(Class c) { Method[] all = c.getMethods(); for (int i = 0; i < all.length; i++) { if (isTest(all[i])) return makeTestCase(c, all[i]); diff --git a/src/test/org/apache/commons/collections/LocalTestNode.java b/src/test/org/apache/commons/collections/LocalTestNode.java index 0bc7cb4e7..ae6f709c8 100644 --- a/src/test/org/apache/commons/collections/LocalTestNode.java +++ b/src/test/org/apache/commons/collections/LocalTestNode.java @@ -23,46 +23,50 @@ package org.apache.commons.collections; * * @author Marc Johnson (marcj at users dot sourceforge dot net) */ -class LocalTestNode implements Comparable { +class LocalTestNode, V extends Comparable> implements Comparable> { - private Comparable key; - private Comparable value; + private K key; + private V value; + + static LocalTestNode createLocalTestNode(final int key) { + return new LocalTestNode(key, String.valueOf(key)); + } /** * construct a LocalTestNode * * @param key value used to create the key and value */ - LocalTestNode(final int key) { - this.key = new Integer(key); - this.value = String.valueOf(key); + private LocalTestNode(K key, V value) { + this.key = key; + this.value = value; } /** * @param key the unique key associated with the current node. */ - void setKey(Comparable key) { + void setKey(K key) { this.key = key; } /** * @return the unique key associated with the current node */ - Comparable getKey() { + K getKey() { return key; } /** * @param value the unique value associated with the current node. */ - void setValue(Comparable value) { + void setValue(V value) { this.value = value; } /** * @return the unique value associated with the current node */ - Comparable getValue() { + V getValue() { return value; } @@ -74,10 +78,9 @@ class LocalTestNode implements Comparable { * @return a negative integer, zero, or a positive integer * as this object is less than, equal to, or greater than the specified object. */ - public int compareTo(Object o) { + public int compareTo(LocalTestNode other) { - LocalTestNode other = (LocalTestNode) o; - int rval = getKey().compareTo(other.getKey()); + int rval = getKey().compareTo(other.getKey()); if (rval == 0) { rval = getValue().compareTo(other.getValue()); @@ -93,6 +96,7 @@ class LocalTestNode implements Comparable { * * @return true if equal */ + @SuppressWarnings("unchecked") public boolean equals(Object o) { if (o == null) { diff --git a/src/test/org/apache/commons/collections/TestArrayList.java b/src/test/org/apache/commons/collections/TestArrayList.java index 905ccab3a..85a59b6fe 100644 --- a/src/test/org/apache/commons/collections/TestArrayList.java +++ b/src/test/org/apache/commons/collections/TestArrayList.java @@ -30,10 +30,8 @@ import org.apache.commons.collections.list.AbstractTestList; * * @author Jason van Zyl */ -public abstract class TestArrayList extends AbstractTestList { - - protected ArrayList list = null; - +public abstract class TestArrayList extends AbstractTestList { + public TestArrayList(String testName) { super(testName); } @@ -47,12 +45,15 @@ public abstract class TestArrayList extends AbstractTestList { junit.textui.TestRunner.main(testCaseName); } - public void setUp() { - list = (ArrayList) makeEmptyList(); - } + /** + * {@inheritDoc} + */ + @Override + public abstract ArrayList makeObject(); //----------------------------------------------------------------------- public void testNewArrayList() { + ArrayList list = makeObject(); assertTrue("New list is empty", list.isEmpty()); assertEquals("New list has size zero", 0, list.size()); @@ -64,9 +65,11 @@ public abstract class TestArrayList extends AbstractTestList { } } + @SuppressWarnings("unchecked") public void testSearch() { - list.add("First Item"); - list.add("Last Item"); + ArrayList list = makeObject(); + list.add((E) "First Item"); + list.add((E) "Last Item"); assertEquals("First item is 'First Item'", "First Item", list.get(0)); assertEquals("Last Item is 'Last Item'", "Last Item", list.get(1)); } diff --git a/src/test/org/apache/commons/collections/TestArrayStack.java b/src/test/org/apache/commons/collections/TestArrayStack.java index 6587c8555..fd922e630 100644 --- a/src/test/org/apache/commons/collections/TestArrayStack.java +++ b/src/test/org/apache/commons/collections/TestArrayStack.java @@ -17,7 +17,6 @@ package org.apache.commons.collections; import java.util.EmptyStackException; -import java.util.List; import junit.framework.Test; @@ -28,10 +27,8 @@ import junit.framework.Test; * * @author Craig McClanahan */ -public class TestArrayStack extends TestArrayList { +public class TestArrayStack extends TestArrayList { - protected ArrayStack stack = null; - public TestArrayStack(String testName) { super(testName); } @@ -45,18 +42,13 @@ public class TestArrayStack extends TestArrayList { junit.textui.TestRunner.main(testCaseName); } - public List makeEmptyList() { - return new ArrayStack(); - } - - public void setUp() { - stack = (ArrayStack) makeEmptyList(); - list = stack; + public ArrayStack makeObject() { + return new ArrayStack(); } //----------------------------------------------------------------------- public void testNewStack() { - + ArrayStack stack = makeObject(); assertTrue("New stack is empty", stack.empty()); assertEquals("New stack has size zero", 0, stack.size()); @@ -76,16 +68,18 @@ public class TestArrayStack extends TestArrayList { } + @SuppressWarnings("unchecked") public void testPushPeekPop() { + ArrayStack stack = makeObject(); - stack.push("First Item"); + stack.push((E) "First Item"); assertTrue("Stack is not empty", !stack.empty()); assertEquals("Stack size is one", 1, stack.size()); assertEquals("Top item is 'First Item'", "First Item", (String) stack.peek()); assertEquals("Stack size is one", 1, stack.size()); - stack.push("Second Item"); + stack.push((E) "Second Item"); assertEquals("Stack size is two", 2, stack.size()); assertEquals("Top item is 'Second Item'", "Second Item", (String) stack.peek()); @@ -103,10 +97,12 @@ public class TestArrayStack extends TestArrayList { } + @SuppressWarnings("unchecked") public void testSearch() { + ArrayStack stack = makeObject(); - stack.push("First Item"); - stack.push("Second Item"); + stack.push((E) "First Item"); + stack.push((E) "Second Item"); assertEquals("Top item is 'Second Item'", 1, stack.search("Second Item")); assertEquals("Next Item is 'First Item'", diff --git a/src/test/org/apache/commons/collections/TestBufferUtils.java b/src/test/org/apache/commons/collections/TestBufferUtils.java index 64c5a6200..2697c6111 100644 --- a/src/test/org/apache/commons/collections/TestBufferUtils.java +++ b/src/test/org/apache/commons/collections/TestBufferUtils.java @@ -42,16 +42,16 @@ public class TestBufferUtils extends BulkTest { } public void testpredicatedBuffer() { - Predicate predicate = new Predicate() { + Predicate predicate = new Predicate() { public boolean evaluate(Object o) { return o instanceof String; } }; - Buffer buffer = BufferUtils.predicatedBuffer(new ArrayStack(), predicate); + Buffer buffer = BufferUtils.predicatedBuffer(new ArrayStack(), predicate); assertTrue("returned object should be a PredicatedBuffer", buffer instanceof PredicatedBuffer); try { - buffer = BufferUtils.predicatedBuffer(new ArrayStack(), null); + buffer = BufferUtils.predicatedBuffer(new ArrayStack(), null); fail("Expecting IllegalArgumentException for null predicate."); } catch (IllegalArgumentException ex) { // expected diff --git a/src/test/org/apache/commons/collections/TestEnumerationUtils.java b/src/test/org/apache/commons/collections/TestEnumerationUtils.java index 8a699a0a3..4f9e02f69 100644 --- a/src/test/org/apache/commons/collections/TestEnumerationUtils.java +++ b/src/test/org/apache/commons/collections/TestEnumerationUtils.java @@ -39,46 +39,46 @@ public class TestEnumerationUtils extends BulkTest { public static final String TO_LIST_FIXTURE = "this is a test"; public void testToListWithStringTokenizer() { - List expectedList1 = new ArrayList(); + List expectedList1 = new ArrayList(); StringTokenizer st = new StringTokenizer(TO_LIST_FIXTURE); while (st.hasMoreTokens()) { expectedList1.add(st.nextToken()); - } - List expectedList2 = new ArrayList(); + } + List expectedList2 = new ArrayList(); expectedList2.add("this"); expectedList2.add("is"); expectedList2.add("a"); expectedList2.add("test"); - List actualList = EnumerationUtils.toList(new StringTokenizer(TO_LIST_FIXTURE)); + List actualList = EnumerationUtils.toList(new StringTokenizer(TO_LIST_FIXTURE)); Assert.assertEquals(expectedList1, expectedList2); Assert.assertEquals(expectedList1, actualList); Assert.assertEquals(expectedList2, actualList); } public void testToListWithHashtable() { - Hashtable expected = new Hashtable(); + Hashtable expected = new Hashtable(); expected.put("one", new Integer(1)); expected.put("two", new Integer(2)); expected.put("three", new Integer(3)); // validate elements. - List actualEltList = EnumerationUtils.toList(expected.elements()); + List actualEltList = EnumerationUtils.toList(expected.elements()); Assert.assertEquals(expected.size(), actualEltList.size()); Assert.assertTrue(actualEltList.contains(new Integer(1))); Assert.assertTrue(actualEltList.contains(new Integer(2))); Assert.assertTrue(actualEltList.contains(new Integer(3))); - List expectedEltList = new ArrayList(); + List expectedEltList = new ArrayList(); expectedEltList.add(new Integer(1)); expectedEltList.add(new Integer(2)); expectedEltList.add(new Integer(3)); Assert.assertTrue(actualEltList.containsAll(expectedEltList)); // validate keys. - List actualKeyList = EnumerationUtils.toList(expected.keys()); + List actualKeyList = EnumerationUtils.toList(expected.keys()); Assert.assertEquals(expected.size(), actualEltList.size()); Assert.assertTrue(actualKeyList.contains("one")); Assert.assertTrue(actualKeyList.contains("two")); Assert.assertTrue(actualKeyList.contains("three")); - List expectedKeyList = new ArrayList(); + List expectedKeyList = new ArrayList(); expectedKeyList.add("one"); expectedKeyList.add("two"); expectedKeyList.add("three"); diff --git a/src/test/org/apache/commons/collections/TestLinkedList.java b/src/test/org/apache/commons/collections/TestLinkedList.java index 4c4cab29d..bd6a33434 100644 --- a/src/test/org/apache/commons/collections/TestLinkedList.java +++ b/src/test/org/apache/commons/collections/TestLinkedList.java @@ -38,46 +38,21 @@ import org.apache.commons.collections.list.AbstractTestList; * * @author Rich Dougherty */ -public abstract class TestLinkedList extends AbstractTestList { +public abstract class TestLinkedList extends AbstractTestList { public TestLinkedList(String testName) { super(testName); } - public List makeEmptyList() { - return makeEmptyLinkedList(); - } - - public List makeFullList() { - return makeFullLinkedList(); - } - - /** - * Return a new, empty {@link LinkedList} to be used for testing. - * - * @return an empty list for testing. - */ - protected abstract LinkedList makeEmptyLinkedList(); - - /** - * Return a new, full {@link List} to be used for testing. - * - * @return a full list for testing - */ - protected LinkedList makeFullLinkedList() { - // only works if list supports optional "addAll(Collection)" - LinkedList list = makeEmptyLinkedList(); - list.addAll(Arrays.asList(getFullElements())); - return list; - } + public abstract LinkedList makeObject(); /** * Returns the {@link #collection} field cast to a {@link LinkedList}. * * @return the collection field as a List */ - protected LinkedList getLinkedList() { - return (LinkedList)collection; + public LinkedList getCollection() { + return (LinkedList) super.getCollection(); } /** @@ -85,24 +60,25 @@ public abstract class TestLinkedList extends AbstractTestList { * * @return the confirmed field as a List */ - protected LinkedList getConfirmedLinkedList() { - return (LinkedList)confirmed; + protected LinkedList getConfirmedLinkedList() { + return (LinkedList) getConfirmed(); } /** * Tests {@link LinkedList#addFirst(Object)}. */ + @SuppressWarnings("unchecked") public void testLinkedListAddFirst() { if (!isAddSupported()) return; - Object o = "hello"; + T o = (T) "hello"; resetEmpty(); - getLinkedList().addFirst(o); + getCollection().addFirst(o); getConfirmedLinkedList().addFirst(o); verify(); resetFull(); - getLinkedList().addFirst(o); + getCollection().addFirst(o); getConfirmedLinkedList().addFirst(o); verify(); } @@ -110,17 +86,18 @@ public abstract class TestLinkedList extends AbstractTestList { /** * Tests {@link LinkedList#addLast(Object)}. */ + @SuppressWarnings("unchecked") public void testLinkedListAddLast() { if (!isAddSupported()) return; - Object o = "hello"; + T o = (T) "hello"; resetEmpty(); - getLinkedList().addLast(o); + getCollection().addLast(o); getConfirmedLinkedList().addLast(o); verify(); resetFull(); - getLinkedList().addLast(o); + getCollection().addLast(o); getConfirmedLinkedList().addLast(o); verify(); } @@ -131,7 +108,7 @@ public abstract class TestLinkedList extends AbstractTestList { public void testLinkedListGetFirst() { resetEmpty(); try { - getLinkedList().getFirst(); + getCollection().getFirst(); fail("getFirst() should throw a NoSuchElementException for an " + "empty list."); } catch (NoSuchElementException e) { @@ -140,7 +117,7 @@ public abstract class TestLinkedList extends AbstractTestList { verify(); resetFull(); - Object first = getLinkedList().getFirst(); + Object first = getCollection().getFirst(); Object confirmedFirst = getConfirmedLinkedList().getFirst(); assertEquals("Result returned by getFirst() was wrong.", confirmedFirst, first); @@ -153,7 +130,7 @@ public abstract class TestLinkedList extends AbstractTestList { public void testLinkedListGetLast() { resetEmpty(); try { - getLinkedList().getLast(); + getCollection().getLast(); fail("getLast() should throw a NoSuchElementException for an " + "empty list."); } catch (NoSuchElementException e) { @@ -162,7 +139,7 @@ public abstract class TestLinkedList extends AbstractTestList { verify(); resetFull(); - Object last = getLinkedList().getLast(); + Object last = getCollection().getLast(); Object confirmedLast = getConfirmedLinkedList().getLast(); assertEquals("Result returned by getLast() was wrong.", confirmedLast, last); @@ -177,7 +154,7 @@ public abstract class TestLinkedList extends AbstractTestList { resetEmpty(); try { - getLinkedList().removeFirst(); + getCollection().removeFirst(); fail("removeFirst() should throw a NoSuchElementException for " + "an empty list."); } catch (NoSuchElementException e) { @@ -186,7 +163,7 @@ public abstract class TestLinkedList extends AbstractTestList { verify(); resetFull(); - Object first = getLinkedList().removeFirst(); + Object first = getCollection().removeFirst(); Object confirmedFirst = getConfirmedLinkedList().removeFirst(); assertEquals("Result returned by removeFirst() was wrong.", confirmedFirst, first); @@ -201,7 +178,7 @@ public abstract class TestLinkedList extends AbstractTestList { resetEmpty(); try { - getLinkedList().removeLast(); + getCollection().removeLast(); fail("removeLast() should throw a NoSuchElementException for " + "an empty list."); } catch (NoSuchElementException e) { @@ -210,7 +187,7 @@ public abstract class TestLinkedList extends AbstractTestList { verify(); resetFull(); - Object last = getLinkedList().removeLast(); + Object last = getCollection().removeLast(); Object confirmedLast = getConfirmedLinkedList().removeLast(); assertEquals("Result returned by removeLast() was wrong.", confirmedLast, last); @@ -220,15 +197,15 @@ public abstract class TestLinkedList extends AbstractTestList { /** * Returns an empty {@link LinkedList}. */ - public Collection makeConfirmedCollection() { - return new LinkedList(); + public Collection makeConfirmedCollection() { + return new LinkedList(); } /** * Returns a full {@link LinkedList}. */ - public Collection makeConfirmedFullCollection() { - List list = new LinkedList(); + public Collection makeConfirmedFullCollection() { + List list = new LinkedList(); list.addAll(Arrays.asList(getFullElements())); return list; } diff --git a/src/test/org/apache/commons/collections/TestSetUtils.java b/src/test/org/apache/commons/collections/TestSetUtils.java index 80a951136..2b2fdaa24 100644 --- a/src/test/org/apache/commons/collections/TestSetUtils.java +++ b/src/test/org/apache/commons/collections/TestSetUtils.java @@ -46,18 +46,17 @@ public class TestSetUtils extends BulkTest { public void testNothing() { } - + public void testpredicatedSet() { - Predicate predicate = new Predicate() { + Predicate predicate = new Predicate() { public boolean evaluate(Object o) { return o instanceof String; } }; - Set set = SetUtils.predicatedSet(new HashSet(), predicate); - assertTrue("returned object should be a PredicatedSet", - set instanceof PredicatedSet); + Set set = SetUtils.predicatedSet(new HashSet(), predicate); + assertTrue("returned object should be a PredicatedSet", set instanceof PredicatedSet); try { - set = SetUtils.predicatedSet(new HashSet(), null); + set = SetUtils.predicatedSet(new HashSet(), null); fail("Expecting IllegalArgumentException for null predicate."); } catch (IllegalArgumentException ex) { // expected @@ -71,11 +70,11 @@ public class TestSetUtils extends BulkTest { } public void testEquals() { - Collection data = Arrays.asList( new String[] { "a", "b", "c" }); - - Set a = new HashSet( data ); - Set b = new HashSet( data ); - + Collection data = Arrays.asList( new String[] { "a", "b", "c" }); + + Set a = new HashSet(data); + Set b = new HashSet(data); + assertEquals(true, a.equals(b)); assertEquals(true, SetUtils.isEqualSet(a, b)); a.clear(); @@ -84,13 +83,13 @@ public class TestSetUtils extends BulkTest { assertEquals(false, SetUtils.isEqualSet(null, b)); assertEquals(true, SetUtils.isEqualSet(null, null)); } - + public void testHashCode() { - Collection data = Arrays.asList( new String[] { "a", "b", "c" }); - - Set a = new HashSet( data ); - Set b = new HashSet( data ); - + Collection data = Arrays.asList( new String[] { "a", "b", "c" }); + + Set a = new HashSet(data); + Set b = new HashSet(data); + assertEquals(true, a.hashCode() == b.hashCode()); assertEquals(true, a.hashCode() == SetUtils.hashCodeForSet(a)); assertEquals(true, b.hashCode() == SetUtils.hashCodeForSet(b)); @@ -98,6 +97,6 @@ public class TestSetUtils extends BulkTest { a.clear(); assertEquals(false, SetUtils.hashCodeForSet(a) == SetUtils.hashCodeForSet(b)); assertEquals(0, SetUtils.hashCodeForSet(null)); - } + } } diff --git a/src/test/org/apache/commons/collections/TestTreeMap.java b/src/test/org/apache/commons/collections/TestTreeMap.java index c32778251..d517d5063 100644 --- a/src/test/org/apache/commons/collections/TestTreeMap.java +++ b/src/test/org/apache/commons/collections/TestTreeMap.java @@ -27,8 +27,8 @@ import org.apache.commons.collections.map.AbstractTestMap; * * @author Jason van Zyl */ -public abstract class TestTreeMap extends AbstractTestMap { - +public abstract class TestTreeMap extends AbstractTestMap { + public TestTreeMap(String testName) { super(testName); } @@ -42,23 +42,27 @@ public abstract class TestTreeMap extends AbstractTestMap { return false; } - protected TreeMap map = null; - - public void setUp() { - map = (TreeMap) makeEmptyMap(); - } + /** + * {@inheritDoc} + */ + @Override + public abstract TreeMap makeObject(); public void testNewMap() { + TreeMap map = makeObject(); assertTrue("New map is empty", map.isEmpty()); assertEquals("New map has size zero", 0, map.size()); } + @SuppressWarnings("unchecked") public void testSearch() { - map.put("first", "First Item"); - map.put("second", "Second Item"); + TreeMap map = makeObject(); + map.put((K) "first", (V) "First Item"); + map.put((K) "second", (V) "Second Item"); assertEquals("Top item is 'Second Item'", "First Item", map.get("first")); assertEquals("Next Item is 'First Item'", "Second Item", map.get("second")); } + } diff --git a/src/test/org/apache/commons/collections/TestTypedCollection.java b/src/test/org/apache/commons/collections/TestTypedCollection.java index df35ce484..167f666c2 100644 --- a/src/test/org/apache/commons/collections/TestTypedCollection.java +++ b/src/test/org/apache/commons/collections/TestTypedCollection.java @@ -27,25 +27,25 @@ import java.util.List; * * @author Stephen Colebourne */ -public abstract class TestTypedCollection extends BulkTest { +public abstract class TestTypedCollection extends BulkTest { public TestTypedCollection(String name) { super(name); } + protected abstract Collection typedCollection(); - protected abstract Collection typedCollection(); - - protected Class getType() { - return String.class; + @SuppressWarnings("unchecked") + protected Class getType() { + return (Class) String.class; } - + @SuppressWarnings("unchecked") public void testIllegalAdd() { - Collection c = typedCollection(); + Collection c = typedCollection(); Integer i = new Integer(3); try { - c.add(i); + c.add((T) i); fail("Integer should fail string predicate."); } catch (IllegalArgumentException e) { // expected @@ -55,15 +55,16 @@ public abstract class TestTypedCollection extends BulkTest { } + @SuppressWarnings("unchecked") public void testIllegalAddAll() { - Collection c = typedCollection(); - List elements = new ArrayList(); + Collection c = typedCollection(); + List elements = new ArrayList(); elements.add("one"); elements.add("two"); elements.add(new Integer(3)); elements.add("four"); try { - c.addAll(elements); + c.addAll((Collection) elements); fail("Integer should fail string predicate."); } catch (IllegalArgumentException e) { // expected diff --git a/src/test/org/apache/commons/collections/bag/AbstractTestSortedBag.java b/src/test/org/apache/commons/collections/bag/AbstractTestSortedBag.java index ed16d3e3f..c530b6378 100644 --- a/src/test/org/apache/commons/collections/bag/AbstractTestSortedBag.java +++ b/src/test/org/apache/commons/collections/bag/AbstractTestSortedBag.java @@ -16,6 +16,8 @@ */ package org.apache.commons.collections.bag; +import org.apache.commons.collections.SortedBag; + /** * Abstract test class for * {@link org.apache.commons.collections.SortedBag SortedBag} @@ -26,11 +28,17 @@ package org.apache.commons.collections.bag; * * @author Stephen Colebourne */ -public abstract class AbstractTestSortedBag extends AbstractTestBag { +public abstract class AbstractTestSortedBag extends AbstractTestBag { public AbstractTestSortedBag(String testName) { super(testName); } - + + /** + * {@inheritDoc} + */ + @Override + public abstract SortedBag makeObject(); + // TODO: Add the SortedBag tests! } diff --git a/src/test/org/apache/commons/collections/bag/TestHashBag.java b/src/test/org/apache/commons/collections/bag/TestHashBag.java index 9e78ac201..64caa7844 100644 --- a/src/test/org/apache/commons/collections/bag/TestHashBag.java +++ b/src/test/org/apache/commons/collections/bag/TestHashBag.java @@ -29,7 +29,7 @@ import org.apache.commons.collections.Bag; * * @author Chuck Burdick */ -public class TestHashBag extends AbstractTestBag { +public class TestHashBag extends AbstractTestBag { public TestHashBag(String testName) { super(testName); @@ -44,8 +44,8 @@ public class TestHashBag extends AbstractTestBag { junit.textui.TestRunner.main(testCaseName); } - public Bag makeBag() { - return new HashBag(); + public Bag makeObject() { + return new HashBag(); } public String getCompatibilityVersion() { diff --git a/src/test/org/apache/commons/collections/bag/TestPredicatedBag.java b/src/test/org/apache/commons/collections/bag/TestPredicatedBag.java index 5faa84dea..c2e419e9d 100644 --- a/src/test/org/apache/commons/collections/bag/TestPredicatedBag.java +++ b/src/test/org/apache/commons/collections/bag/TestPredicatedBag.java @@ -23,7 +23,7 @@ import junit.framework.TestSuite; import org.apache.commons.collections.Bag; import org.apache.commons.collections.Predicate; -import org.apache.commons.collections.PredicateUtils; +import org.apache.commons.collections.functors.TruePredicate; /** * Extension of {@link AbstractTestBag} for exercising the {@link PredicatedBag} @@ -34,8 +34,8 @@ import org.apache.commons.collections.PredicateUtils; * * @author Phil Steitz */ -public class TestPredicatedBag extends AbstractTestBag { - +public class TestPredicatedBag extends AbstractTestBag { + public TestPredicatedBag(String testName) { super(testName); } @@ -48,81 +48,84 @@ public class TestPredicatedBag extends AbstractTestBag { String[] testCaseName = { TestPredicatedBag.class.getName()}; junit.textui.TestRunner.main(testCaseName); } - + //-------------------------------------------------------------------------- - protected Predicate stringPredicate() { - return new Predicate() { - public boolean evaluate(Object o) { + protected Predicate stringPredicate() { + return new Predicate() { + public boolean evaluate(T o) { return o instanceof String; } }; - } - - protected Predicate truePredicate = PredicateUtils.truePredicate(); - - protected Bag decorateBag(HashBag bag, Predicate predicate) { + } + + protected Predicate truePredicate = TruePredicate.truePredicate(); + + protected Bag decorateBag(HashBag bag, Predicate predicate) { return PredicatedBag.decorate(bag, predicate); } - public Bag makeBag() { - return decorateBag(new HashBag(), truePredicate); + public Bag makeObject() { + return decorateBag(new HashBag(), truePredicate); } - - protected Bag makeTestBag() { - return decorateBag(new HashBag(), stringPredicate()); + + protected Bag makeTestBag() { + return decorateBag(new HashBag(), stringPredicate()); } - + //-------------------------------------------------------------------------- + @SuppressWarnings("unchecked") public void testlegalAddRemove() { - Bag bag = makeTestBag(); + Bag bag = makeTestBag(); assertEquals(0, bag.size()); - Object[] els = new Object[] {"1", "3", "5", "7", "2", "4", "1"}; + T[] els = (T[]) new Object[] { "1", "3", "5", "7", "2", "4", "1" }; for (int i = 0; i < els.length; i++) { bag.add(els[i]); assertEquals(i + 1, bag.size()); assertEquals(true, bag.contains(els[i])); } - Set set = ((PredicatedBag) bag).uniqueSet(); + Set set = ((PredicatedBag) bag).uniqueSet(); assertTrue("Unique set contains the first element",set.contains(els[0])); - assertEquals(true, bag.remove(els[0])); - set = ((PredicatedBag) bag).uniqueSet(); + assertEquals(true, bag.remove(els[0])); + set = ((PredicatedBag) bag).uniqueSet(); assertTrue("Unique set now does not contain the first element", - !set.contains(els[0])); + !set.contains(els[0])); } - + + @SuppressWarnings("unchecked") public void testIllegalAdd() { - Bag bag = makeTestBag(); + Bag bag = makeTestBag(); Integer i = new Integer(3); try { - bag.add(i); + bag.add((T) i); fail("Integer should fail string predicate."); } catch (IllegalArgumentException e) { // expected } - assertTrue("Collection shouldn't contain illegal element", - !bag.contains(i)); + assertTrue("Collection shouldn't contain illegal element", + !bag.contains(i)); } + @SuppressWarnings("unchecked") public void testIllegalDecorate() { - HashBag elements = new HashBag(); + HashBag elements = new HashBag(); elements.add("one"); elements.add("two"); elements.add(new Integer(3)); elements.add("four"); try { - Bag bag = decorateBag(elements, stringPredicate()); + decorateBag((HashBag) elements, stringPredicate()); fail("Bag contains an element that should fail the predicate."); } catch (IllegalArgumentException e) { // expected } try { - Bag bag = decorateBag(new HashBag(), null); + decorateBag(new HashBag(), null); fail("Expectiing IllegalArgumentException for null predicate."); } catch (IllegalArgumentException e) { // expected - } + } } public String getCompatibilityVersion() { diff --git a/src/test/org/apache/commons/collections/bag/TestTransformedBag.java b/src/test/org/apache/commons/collections/bag/TestTransformedBag.java index 9530dec68..2a263f469 100644 --- a/src/test/org/apache/commons/collections/bag/TestTransformedBag.java +++ b/src/test/org/apache/commons/collections/bag/TestTransformedBag.java @@ -20,6 +20,7 @@ import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections.Bag; +import org.apache.commons.collections.Transformer; import org.apache.commons.collections.collection.TestTransformedCollection; /** @@ -31,8 +32,8 @@ import org.apache.commons.collections.collection.TestTransformedCollection; * * @author Stephen Colebourne */ -public class TestTransformedBag extends AbstractTestBag { - +public class TestTransformedBag extends AbstractTestBag { + public TestTransformedBag(String testName) { super(testName); } @@ -46,25 +47,29 @@ public class TestTransformedBag extends AbstractTestBag { junit.textui.TestRunner.main(testCaseName); } - public Bag makeBag() { - return TransformedBag.decorate(new HashBag(), TestTransformedCollection.NOOP_TRANSFORMER); + @SuppressWarnings("unchecked") + public Bag makeObject() { + return TransformedBag.decorate(new HashBag(), (Transformer) TestTransformedCollection.NOOP_TRANSFORMER); } + @SuppressWarnings("unchecked") public void testTransformedBag() { - Bag bag = TransformedBag.decorate(new HashBag(), TestTransformedCollection.STRING_TO_INTEGER_TRANSFORMER); + //T had better be Object! + Bag bag = TransformedBag.decorate(new HashBag(), (Transformer) TestTransformedCollection.STRING_TO_INTEGER_TRANSFORMER); assertEquals(0, bag.size()); Object[] els = new Object[] {"1", "3", "5", "7", "2", "4", "6"}; for (int i = 0; i < els.length; i++) { - bag.add(els[i]); + bag.add((T) els[i]); assertEquals(i + 1, bag.size()); assertEquals(true, bag.contains(new Integer((String) els[i]))); assertEquals(false, bag.contains(els[i])); } - + assertEquals(false, bag.remove(els[0])); assertEquals(true, bag.remove(new Integer((String) els[0]))); } + // TODO: Generics public void testTransformedBag_decorateTransform() { Bag originalBag = new HashBag(); Object[] els = new Object[] {"1", "3", "5", "7", "2", "4", "6"}; diff --git a/src/test/org/apache/commons/collections/bag/TestTransformedSortedBag.java b/src/test/org/apache/commons/collections/bag/TestTransformedSortedBag.java index 1d83c0a54..81f284583 100644 --- a/src/test/org/apache/commons/collections/bag/TestTransformedSortedBag.java +++ b/src/test/org/apache/commons/collections/bag/TestTransformedSortedBag.java @@ -20,6 +20,8 @@ import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections.Bag; +import org.apache.commons.collections.SortedBag; +import org.apache.commons.collections.Transformer; import org.apache.commons.collections.collection.TestTransformedCollection; /** @@ -31,8 +33,8 @@ import org.apache.commons.collections.collection.TestTransformedCollection; * * @author Stephen Colebourne */ -public class TestTransformedSortedBag extends AbstractTestSortedBag { - +public class TestTransformedSortedBag extends AbstractTestSortedBag { + public TestTransformedSortedBag(String testName) { super(testName); } @@ -46,22 +48,24 @@ public class TestTransformedSortedBag extends AbstractTestSortedBag { junit.textui.TestRunner.main(testCaseName); } - public Bag makeBag() { - return TransformedSortedBag.decorate(new TreeBag(), TestTransformedCollection.NOOP_TRANSFORMER); + @SuppressWarnings("unchecked") + public SortedBag makeObject() { + return TransformedSortedBag.decorate(new TreeBag(), (Transformer) TestTransformedCollection.NOOP_TRANSFORMER); } + @SuppressWarnings("unchecked") public void testTransformedBag() { - Bag bag = TransformedSortedBag.decorate(new TreeBag(), TestTransformedCollection.STRING_TO_INTEGER_TRANSFORMER); + SortedBag bag = TransformedSortedBag.decorate(new TreeBag(), (Transformer) TestTransformedCollection.STRING_TO_INTEGER_TRANSFORMER); assertEquals(0, bag.size()); Object[] els = new Object[] {"1", "3", "5", "7", "2", "4", "6"}; for (int i = 0; i < els.length; i++) { - bag.add(els[i]); + bag.add((T) els[i]); assertEquals(i + 1, bag.size()); assertEquals(true, bag.contains(new Integer((String) els[i]))); } - + assertEquals(true, bag.remove(new Integer((String) els[0]))); - + } public void testTransformedBag_decorateTransform() { diff --git a/src/test/org/apache/commons/collections/bag/TestTreeBag.java b/src/test/org/apache/commons/collections/bag/TestTreeBag.java index 39ab7b228..7a4eae37c 100644 --- a/src/test/org/apache/commons/collections/bag/TestTreeBag.java +++ b/src/test/org/apache/commons/collections/bag/TestTreeBag.java @@ -30,48 +30,26 @@ import org.apache.commons.collections.SortedBag; * * @author Chuck Burdick */ -public class TestTreeBag extends AbstractTestBag { - - public TestTreeBag(String testName) { - super(testName); - } +public class TestTreeBag extends AbstractTestSortedBag { - public static Test suite() { - return new TestSuite(TestTreeBag.class); - } + public TestTreeBag(String testName) { + super(testName); + } - public static void main(String args[]) { - String[] testCaseName = { TestTreeBag.class.getName() }; - junit.textui.TestRunner.main(testCaseName); - } + public static Test suite() { + return new TestSuite(TestTreeBag.class); + } - public Bag makeBag() { - return new TreeBag(); - } + public static void main(String args[]) { + String[] testCaseName = { TestTreeBag.class.getName() }; + junit.textui.TestRunner.main(testCaseName); + } - public SortedBag setupBag() { - SortedBag bag = (SortedBag)makeBag(); - bag.add("C"); - bag.add("A"); - bag.add("B"); - bag.add("D"); - return bag; - } - - public void testOrdering() { - Bag bag = setupBag(); - assertEquals("Should get elements in correct order", - "A", bag.toArray()[0]); - assertEquals("Should get elements in correct order", - "B", bag.toArray()[1]); - assertEquals("Should get elements in correct order", - "C", bag.toArray()[2]); - assertEquals("Should get first key", - "A", ((SortedBag)bag).first()); - assertEquals("Should get last key", - "D", ((SortedBag)bag).last()); - } + public SortedBag makeObject() { + return new TreeBag(); + } + // TODO: Generics (for example... is this even needed?) public void testCollections265() { Bag bag = new TreeBag(); try { @@ -82,19 +60,38 @@ public class TestTreeBag extends AbstractTestBag { } } - public String getCompatibilityVersion() { - return "3"; - } - -// public void testCreate() throws Exception { -// Bag bag = makeBag(); -// writeExternalFormToDisk((Serializable) bag, "D:/dev/collections/data/test/TreeBag.emptyCollection.version3.obj"); -// bag = makeBag(); -// bag.add("A"); -// bag.add("A"); -// bag.add("B"); -// bag.add("B"); -// bag.add("C"); -// writeExternalFormToDisk((Serializable) bag, "D:/dev/collections/data/test/TreeBag.fullCollection.version3.obj"); -// } + @SuppressWarnings("unchecked") + public SortedBag setupBag() { + SortedBag bag = makeObject(); + bag.add((T) "C"); + bag.add((T) "A"); + bag.add((T) "B"); + bag.add((T) "D"); + return bag; + } + + public void testOrdering() { + Bag bag = setupBag(); + assertEquals("Should get elements in correct order", "A", bag.toArray()[0]); + assertEquals("Should get elements in correct order", "B", bag.toArray()[1]); + assertEquals("Should get elements in correct order", "C", bag.toArray()[2]); + assertEquals("Should get first key", "A", ((SortedBag) bag).first()); + assertEquals("Should get last key", "D", ((SortedBag) bag).last()); + } + + public String getCompatibilityVersion() { + return "3"; + } + + // public void testCreate() throws Exception { + // Bag bag = makeBag(); + // writeExternalFormToDisk((Serializable) bag, "D:/dev/collections/data/test/TreeBag.emptyCollection.version3.obj"); + // bag = makeBag(); + // bag.add("A"); + // bag.add("A"); + // bag.add("B"); + // bag.add("B"); + // bag.add("C"); + // writeExternalFormToDisk((Serializable) bag, "D:/dev/collections/data/test/TreeBag.fullCollection.version3.obj"); + // } } diff --git a/src/test/org/apache/commons/collections/bidimap/AbstractTestOrderedBidiMap.java b/src/test/org/apache/commons/collections/bidimap/AbstractTestOrderedBidiMap.java index 7e583e3a7..dcf7e2900 100644 --- a/src/test/org/apache/commons/collections/bidimap/AbstractTestOrderedBidiMap.java +++ b/src/test/org/apache/commons/collections/bidimap/AbstractTestOrderedBidiMap.java @@ -36,7 +36,7 @@ import org.apache.commons.collections.iterators.AbstractTestMapIterator; * @author Matthew Hawthorne * @author Stephen Colebourne */ -public abstract class AbstractTestOrderedBidiMap extends AbstractTestBidiMap { +public abstract class AbstractTestOrderedBidiMap extends AbstractTestBidiMap { public AbstractTestOrderedBidiMap(String testName) { super(testName); @@ -49,39 +49,39 @@ public abstract class AbstractTestOrderedBidiMap extends AbstractTestBidiMap { //----------------------------------------------------------------------- public void testFirstKey() { resetEmpty(); - OrderedBidiMap bidi = (OrderedBidiMap) map; + OrderedBidiMap bidi = getMap(); try { bidi.firstKey(); fail(); } catch (NoSuchElementException ex) {} - + resetFull(); - bidi = (OrderedBidiMap) map; - Object confirmedFirst = confirmed.keySet().iterator().next(); + bidi = getMap(); + K confirmedFirst = confirmed.keySet().iterator().next(); assertEquals(confirmedFirst, bidi.firstKey()); } - + public void testLastKey() { resetEmpty(); - OrderedBidiMap bidi = (OrderedBidiMap) map; + OrderedBidiMap bidi = getMap(); try { bidi.lastKey(); fail(); } catch (NoSuchElementException ex) {} - + resetFull(); - bidi = (OrderedBidiMap) map; - Object confirmedLast = null; - for (Iterator it = confirmed.keySet().iterator(); it.hasNext();) { + bidi = getMap(); + K confirmedLast = null; + for (Iterator it = confirmed.keySet().iterator(); it.hasNext();) { confirmedLast = it.next(); } assertEquals(confirmedLast, bidi.lastKey()); } - //----------------------------------------------------------------------- + //----------------------------------------------------------------------- public void testNextKey() { resetEmpty(); - OrderedBidiMap bidi = (OrderedBidiMap) map; + OrderedBidiMap bidi = (OrderedBidiMap) map; assertEquals(null, bidi.nextKey(getOtherKeys()[0])); if (isAllowNullKey() == false) { try { @@ -90,18 +90,18 @@ public abstract class AbstractTestOrderedBidiMap extends AbstractTestBidiMap { } else { assertEquals(null, bidi.nextKey(null)); } - + resetFull(); - bidi = (OrderedBidiMap) map; - Iterator it = confirmed.keySet().iterator(); - Object confirmedLast = it.next(); + bidi = (OrderedBidiMap) map; + Iterator it = confirmed.keySet().iterator(); + K confirmedLast = it.next(); while (it.hasNext()) { - Object confirmedObject = it.next(); + K confirmedObject = it.next(); assertEquals(confirmedObject, bidi.nextKey(confirmedLast)); confirmedLast = confirmedObject; } assertEquals(null, bidi.nextKey(confirmedLast)); - + if (isAllowNullKey() == false) { try { bidi.nextKey(null); @@ -111,10 +111,10 @@ public abstract class AbstractTestOrderedBidiMap extends AbstractTestBidiMap { assertEquals(null, bidi.nextKey(null)); } } - + public void testPreviousKey() { resetEmpty(); - OrderedBidiMap bidi = (OrderedBidiMap) map; + OrderedBidiMap bidi = getMap(); assertEquals(null, bidi.previousKey(getOtherKeys()[0])); if (isAllowNullKey() == false) { try { @@ -123,20 +123,20 @@ public abstract class AbstractTestOrderedBidiMap extends AbstractTestBidiMap { } else { assertEquals(null, bidi.previousKey(null)); } - + resetFull(); - bidi = (OrderedBidiMap) map; - List list = new ArrayList(confirmed.keySet()); + bidi = getMap(); + List list = new ArrayList(confirmed.keySet()); Collections.reverse(list); - Iterator it = list.iterator(); - Object confirmedLast = it.next(); + Iterator it = list.iterator(); + K confirmedLast = it.next(); while (it.hasNext()) { - Object confirmedObject = it.next(); + K confirmedObject = it.next(); assertEquals(confirmedObject, bidi.previousKey(confirmedLast)); confirmedLast = confirmedObject; } assertEquals(null, bidi.previousKey(confirmedLast)); - + if (isAllowNullKey() == false) { try { bidi.previousKey(null); @@ -146,21 +146,29 @@ public abstract class AbstractTestOrderedBidiMap extends AbstractTestBidiMap { assertEquals(null, bidi.previousKey(null)); } } - + //----------------------------------------------------------------------- public BulkTest bulkTestOrderedMapIterator() { return new TestBidiOrderedMapIterator(); } - - public class TestBidiOrderedMapIterator extends AbstractTestMapIterator { + + /** + * {@inheritDoc} + */ + @Override + public OrderedBidiMap getMap() { + return (OrderedBidiMap) super.getMap(); + } + + public class TestBidiOrderedMapIterator extends AbstractTestMapIterator { public TestBidiOrderedMapIterator() { super("TestBidiOrderedMapIterator"); } - - public Object[] addSetValues() { + + public V[] addSetValues() { return AbstractTestOrderedBidiMap.this.getNewSampleValues(); } - + public boolean supportsRemove() { return AbstractTestOrderedBidiMap.this.isRemoveSupported(); } @@ -169,30 +177,30 @@ public abstract class AbstractTestOrderedBidiMap extends AbstractTestBidiMap { return AbstractTestOrderedBidiMap.this.isSetValueSupported(); } - public MapIterator makeEmptyMapIterator() { + public MapIterator makeEmptyIterator() { resetEmpty(); - return ((OrderedBidiMap) AbstractTestOrderedBidiMap.this.map).orderedMapIterator(); + return AbstractTestOrderedBidiMap.this.getMap().mapIterator(); } - public MapIterator makeFullMapIterator() { + public MapIterator makeObject() { resetFull(); - return ((OrderedBidiMap) AbstractTestOrderedBidiMap.this.map).orderedMapIterator(); + return AbstractTestOrderedBidiMap.this.getMap().mapIterator(); } - - public Map getMap() { + + public Map getMap() { // assumes makeFullMapIterator() called first return AbstractTestOrderedBidiMap.this.map; } - - public Map getConfirmedMap() { + + public Map getConfirmedMap() { // assumes makeFullMapIterator() called first return AbstractTestOrderedBidiMap.this.confirmed; } - + public void verify() { super.verify(); AbstractTestOrderedBidiMap.this.verify(); } } - + } diff --git a/src/test/org/apache/commons/collections/bidimap/AbstractTestSortedBidiMap.java b/src/test/org/apache/commons/collections/bidimap/AbstractTestSortedBidiMap.java index b0386a5f7..8d1a85709 100644 --- a/src/test/org/apache/commons/collections/bidimap/AbstractTestSortedBidiMap.java +++ b/src/test/org/apache/commons/collections/bidimap/AbstractTestSortedBidiMap.java @@ -40,68 +40,83 @@ import org.apache.commons.collections.map.AbstractTestSortedMap; * @author Matthew Hawthorne * @author Stephen Colebourne */ -public abstract class AbstractTestSortedBidiMap extends AbstractTestOrderedBidiMap { +public abstract class AbstractTestSortedBidiMap, V extends Comparable> extends AbstractTestOrderedBidiMap { - protected List sortedKeys = new ArrayList(); - protected List sortedValues = new ArrayList(); - protected SortedSet sortedNewValues = new TreeSet(); + protected List sortedKeys = new ArrayList(); + protected List sortedValues = new ArrayList(); + protected SortedSet sortedNewValues = new TreeSet(); public AbstractTestSortedBidiMap(String testName) { super(testName); sortedKeys.addAll(Arrays.asList(getSampleKeys())); Collections.sort(sortedKeys); sortedKeys = Collections.unmodifiableList(sortedKeys); - - Map map = new TreeMap(); - for (int i = 0; i < getSampleKeys().length; i++) { - map.put(getSampleKeys()[i], getSampleValues()[i]); - } + + Map map = new TreeMap(); + addSampleMappings(map); + sortedValues.addAll(map.values()); sortedValues = Collections.unmodifiableList(sortedValues); - + sortedNewValues.addAll(Arrays.asList(getNewSampleValues())); } - public AbstractTestSortedBidiMap() { - super(); - sortedKeys.addAll(Arrays.asList(getSampleValues())); - Collections.sort(sortedKeys); - sortedKeys = Collections.unmodifiableList(sortedKeys); - - Map map = new TreeMap(); - for (int i = 0; i < getSampleKeys().length; i++) { - map.put(getSampleValues()[i], getSampleKeys()[i]); - } - sortedValues.addAll(map.values()); - sortedValues = Collections.unmodifiableList(sortedValues); - - sortedNewValues.addAll(Arrays.asList(getNewSampleValues())); - } +// public AbstractTestSortedBidiMap() { +// super(); +// sortedKeys.addAll(Arrays.asList(getSampleValues())); +// Collections.sort(sortedKeys); +// sortedKeys = Collections.unmodifiableList(sortedKeys); +// +// Map map = new TreeMap(); +// for (int i = 0; i < getSampleKeys().length; i++) { +// map.put(getSampleValues()[i], getSampleKeys()[i]); +// } +// sortedValues.addAll(map.values()); +// sortedValues = Collections.unmodifiableList(sortedValues); +// +// sortedNewValues.addAll(Arrays.asList(getNewSampleValues())); +// } //----------------------------------------------------------------------- public boolean isAllowNullKey() { return false; } + public boolean isAllowNullValue() { return false; } - public Map makeConfirmedMap() { - return new TreeMap(); + + /** + * {@inheritDoc} + */ + @Override + public abstract SortedBidiMap makeObject(); + + /** + * {@inheritDoc} + */ + @Override + public SortedBidiMap makeFullMap() { + return (SortedBidiMap) super.makeFullMap(); + } + + public SortedMap makeConfirmedMap() { + return new TreeMap(); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- public void testBidiHeadMapContains() { // extra test as other tests get complex - SortedBidiMap sm = (SortedBidiMap) makeFullMap(); - Iterator it = sm.keySet().iterator(); - Object first = it.next(); - Object toKey = it.next(); - Object second = it.next(); - Object firstValue = sm.get(first); - Object secondValue = sm.get(second); - - SortedMap head = sm.headMap(toKey); + SortedBidiMap sm = makeFullMap(); + Iterator it = sm.keySet().iterator(); + K first = it.next(); + K toKey = it.next(); + K second = it.next(); + V firstValue = sm.get(first); + V secondValue = sm.get(second); + + SortedMap head = sm.headMap(toKey); assertEquals(1, head.size()); assertEquals(true, sm.containsKey(first)); assertEquals(true, head.containsKey(first)); @@ -112,44 +127,44 @@ public abstract class AbstractTestSortedBidiMap extends AbstractTestOrderedBidiM assertEquals(true, sm.containsValue(secondValue)); assertEquals(false, head.containsValue(secondValue)); } - + //----------------------------------------------------------------------- public void testBidiClearByHeadMap() { if (isRemoveSupported() == false) return; - + // extra test as other tests get complex - SortedBidiMap sm = (SortedBidiMap) makeFullMap(); - Iterator it = sm.keySet().iterator(); - Object first = it.next(); - Object second = it.next(); - Object toKey = it.next(); - - Object firstValue = sm.get(first); - Object secondValue = sm.get(second); - Object toKeyValue = sm.get(toKey); - - SortedMap sub = sm.headMap(toKey); + SortedBidiMap sm = makeFullMap(); + Iterator it = sm.keySet().iterator(); + K first = it.next(); + K second = it.next(); + K toKey = it.next(); + + V firstValue = sm.get(first); + V secondValue = sm.get(second); + V toKeyValue = sm.get(toKey); + + SortedMap sub = sm.headMap(toKey); int size = sm.size(); assertEquals(2, sub.size()); sub.clear(); assertEquals(0, sub.size()); assertEquals(size - 2, sm.size()); assertEquals(size - 2, sm.inverseBidiMap().size()); - + assertEquals(false, sm.containsKey(first)); assertEquals(false, sm.containsValue(firstValue)); assertEquals(false, sm.inverseBidiMap().containsKey(firstValue)); assertEquals(false, sm.inverseBidiMap().containsValue(first)); assertEquals(false, sub.containsKey(first)); assertEquals(false, sub.containsValue(firstValue)); - + assertEquals(false, sm.containsKey(second)); assertEquals(false, sm.containsValue(secondValue)); assertEquals(false, sm.inverseBidiMap().containsKey(secondValue)); assertEquals(false, sm.inverseBidiMap().containsValue(second)); assertEquals(false, sub.containsKey(second)); assertEquals(false, sub.containsValue(secondValue)); - + assertEquals(true, sm.containsKey(toKey)); assertEquals(true, sm.containsValue(toKeyValue)); assertEquals(true, sm.inverseBidiMap().containsKey(toKeyValue)); @@ -161,23 +176,23 @@ public abstract class AbstractTestSortedBidiMap extends AbstractTestOrderedBidiM //----------------------------------------------------------------------- public void testBidiRemoveByHeadMap() { if (isRemoveSupported() == false) return; - + // extra test as other tests get complex - SortedBidiMap sm = (SortedBidiMap) makeFullMap(); - Iterator it = sm.keySet().iterator(); - Object first = it.next(); - Object second = it.next(); - Object toKey = it.next(); - + SortedBidiMap sm = makeFullMap(); + Iterator it = sm.keySet().iterator(); + K first = it.next(); + K second = it.next(); + K toKey = it.next(); + int size = sm.size(); - SortedMap sub = sm.headMap(toKey); + SortedMap sub = sm.headMap(toKey); assertEquals(2, sub.size()); assertEquals(true, sm.containsKey(first)); assertEquals(true, sub.containsKey(first)); assertEquals(true, sm.containsKey(second)); assertEquals(true, sub.containsKey(second)); - - Object firstValue = sub.remove(first); + + V firstValue = sub.remove(first); assertEquals(1, sub.size()); assertEquals(size - 1, sm.size()); assertEquals(size - 1, sm.inverseBidiMap().size()); @@ -187,8 +202,8 @@ public abstract class AbstractTestSortedBidiMap extends AbstractTestOrderedBidiM assertEquals(false, sm.inverseBidiMap().containsValue(first)); assertEquals(false, sub.containsKey(first)); assertEquals(false, sub.containsValue(firstValue)); - - Object secondValue = sub.remove(second); + + V secondValue = sub.remove(second); assertEquals(0, sub.size()); assertEquals(size - 2, sm.size()); assertEquals(size - 2, sm.inverseBidiMap().size()); @@ -203,30 +218,30 @@ public abstract class AbstractTestSortedBidiMap extends AbstractTestOrderedBidiM //----------------------------------------------------------------------- public void testBidiRemoveByHeadMapEntrySet() { if (isRemoveSupported() == false) return; - + // extra test as other tests get complex - SortedBidiMap sm = (SortedBidiMap) makeFullMap(); - Iterator it = sm.keySet().iterator(); - Object first = it.next(); - Object second = it.next(); - Object toKey = it.next(); - + SortedBidiMap sm = makeFullMap(); + Iterator it = sm.keySet().iterator(); + K first = it.next(); + K second = it.next(); + K toKey = it.next(); + int size = sm.size(); - SortedMap sub = sm.headMap(toKey); - Set set = sub.entrySet(); + SortedMap sub = sm.headMap(toKey); + Set> set = sub.entrySet(); assertEquals(2, sub.size()); assertEquals(2, set.size()); - - Iterator it2 = set.iterator(); - Map.Entry firstEntry = cloneMapEntry((Map.Entry) it2.next()); - Map.Entry secondEntry = cloneMapEntry((Map.Entry) it2.next()); + + Iterator> it2 = set.iterator(); + Map.Entry firstEntry = cloneMapEntry(it2.next()); + Map.Entry secondEntry = cloneMapEntry(it2.next()); assertEquals(true, sm.containsKey(first)); assertEquals(true, sub.containsKey(first)); assertEquals(true, set.contains(firstEntry)); assertEquals(true, sm.containsKey(second)); assertEquals(true, sub.containsKey(second)); assertEquals(true, set.contains(secondEntry)); - + set.remove(firstEntry); assertEquals(1, sub.size()); assertEquals(size - 1, sm.size()); @@ -238,7 +253,7 @@ public abstract class AbstractTestSortedBidiMap extends AbstractTestOrderedBidiM assertEquals(false, sub.containsKey(firstEntry.getKey())); assertEquals(false, sub.containsValue(firstEntry.getValue())); assertEquals(false, set.contains(firstEntry)); - + set.remove(secondEntry); assertEquals(0, sub.size()); assertEquals(size - 2, sm.size()); @@ -256,16 +271,16 @@ public abstract class AbstractTestSortedBidiMap extends AbstractTestOrderedBidiM //----------------------------------------------------------------------- public void testBidiTailMapContains() { // extra test as other tests get complex - SortedBidiMap sm = (SortedBidiMap) makeFullMap(); - Iterator it = sm.keySet().iterator(); - Object first = it.next(); - Object fromKey = it.next(); - Object second = it.next(); - Object firstValue = sm.get(first); - Object fromKeyValue = sm.get(fromKey); - Object secondValue = sm.get(second); - - SortedMap sub = sm.tailMap(fromKey); + SortedBidiMap sm = makeFullMap(); + Iterator it = sm.keySet().iterator(); + K first = it.next(); + K fromKey = it.next(); + K second = it.next(); + V firstValue = sm.get(first); + V fromKeyValue = sm.get(fromKey); + V secondValue = sm.get(second); + + SortedMap sub = sm.tailMap(fromKey); assertEquals(sm.size() - 1, sub.size()); assertEquals(true, sm.containsKey(first)); assertEquals(false, sub.containsKey(first)); @@ -284,42 +299,42 @@ public abstract class AbstractTestSortedBidiMap extends AbstractTestOrderedBidiM //----------------------------------------------------------------------- public void testBidiClearByTailMap() { if (isRemoveSupported() == false) return; - + // extra test as other tests get complex - SortedBidiMap sm = (SortedBidiMap) makeFullMap(); - Iterator it = sm.keySet().iterator(); + SortedBidiMap sm = makeFullMap(); + Iterator it = sm.keySet().iterator(); it.next(); it.next(); - Object first = it.next(); - Object fromKey = it.next(); - Object second = it.next(); - - Object firstValue = sm.get(first); - Object fromKeyValue = sm.get(fromKey); - Object secondValue = sm.get(second); - - SortedMap sub = sm.tailMap(fromKey); + K first = it.next(); + K fromKey = it.next(); + K second = it.next(); + + V firstValue = sm.get(first); + V fromKeyValue = sm.get(fromKey); + V secondValue = sm.get(second); + + SortedMap sub = sm.tailMap(fromKey); int size = sm.size(); assertEquals(size - 3, sub.size()); sub.clear(); assertEquals(0, sub.size()); assertEquals(3, sm.size()); assertEquals(3, sm.inverseBidiMap().size()); - + assertEquals(true, sm.containsKey(first)); assertEquals(true, sm.containsValue(firstValue)); assertEquals(true, sm.inverseBidiMap().containsKey(firstValue)); assertEquals(true, sm.inverseBidiMap().containsValue(first)); assertEquals(false, sub.containsKey(first)); assertEquals(false, sub.containsValue(firstValue)); - + assertEquals(false, sm.containsKey(fromKey)); assertEquals(false, sm.containsValue(fromKeyValue)); assertEquals(false, sm.inverseBidiMap().containsKey(fromKeyValue)); assertEquals(false, sm.inverseBidiMap().containsValue(fromKey)); assertEquals(false, sub.containsKey(fromKey)); assertEquals(false, sub.containsValue(fromKeyValue)); - + assertEquals(false, sm.containsKey(second)); assertEquals(false, sm.containsValue(secondValue)); assertEquals(false, sm.inverseBidiMap().containsKey(secondValue)); @@ -328,26 +343,26 @@ public abstract class AbstractTestSortedBidiMap extends AbstractTestOrderedBidiM assertEquals(false, sub.containsValue(secondValue)); } - //----------------------------------------------------------------------- + //----------------------------------------------------------------------- public void testBidiRemoveByTailMap() { if (isRemoveSupported() == false) return; - + // extra test as other tests get complex - SortedBidiMap sm = (SortedBidiMap) makeFullMap(); - Iterator it = sm.keySet().iterator(); + SortedBidiMap sm = makeFullMap(); + Iterator it = sm.keySet().iterator(); it.next(); it.next(); - Object fromKey = it.next(); - Object first = it.next(); - Object second = it.next(); - + K fromKey = it.next(); + K first = it.next(); + K second = it.next(); + int size = sm.size(); - SortedMap sub = sm.tailMap(fromKey); + SortedMap sub = sm.tailMap(fromKey); assertEquals(true, sm.containsKey(first)); assertEquals(true, sub.containsKey(first)); assertEquals(true, sm.containsKey(second)); assertEquals(true, sub.containsKey(second)); - + Object firstValue = sub.remove(first); assertEquals(size - 3, sub.size()); assertEquals(size - 1, sm.size()); @@ -358,7 +373,7 @@ public abstract class AbstractTestSortedBidiMap extends AbstractTestOrderedBidiM assertEquals(false, sm.inverseBidiMap().containsValue(first)); assertEquals(false, sub.containsKey(first)); assertEquals(false, sub.containsValue(firstValue)); - + Object secondValue = sub.remove(second); assertEquals(size - 4, sub.size()); assertEquals(size - 2, sm.size()); @@ -374,30 +389,30 @@ public abstract class AbstractTestSortedBidiMap extends AbstractTestOrderedBidiM //----------------------------------------------------------------------- public void testBidiRemoveByTailMapEntrySet() { if (isRemoveSupported() == false) return; - + // extra test as other tests get complex - SortedBidiMap sm = (SortedBidiMap) makeFullMap(); - Iterator it = sm.keySet().iterator(); + SortedBidiMap sm = makeFullMap(); + Iterator it = sm.keySet().iterator(); it.next(); it.next(); - Object fromKey = it.next(); - Object first = it.next(); - Object second = it.next(); - + K fromKey = it.next(); + K first = it.next(); + K second = it.next(); + int size = sm.size(); - SortedMap sub = sm.tailMap(fromKey); - Set set = sub.entrySet(); - Iterator it2 = set.iterator(); - Object fromEntry = it2.next(); - Map.Entry firstEntry = cloneMapEntry((Map.Entry) it2.next()); - Map.Entry secondEntry = cloneMapEntry((Map.Entry) it2.next()); + SortedMap sub = sm.tailMap(fromKey); + Set> set = sub.entrySet(); + Iterator> it2 = set.iterator(); + it2.next(); + Map.Entry firstEntry = cloneMapEntry(it2.next()); + Map.Entry secondEntry = cloneMapEntry(it2.next()); assertEquals(true, sm.containsKey(first)); assertEquals(true, sub.containsKey(first)); assertEquals(true, set.contains(firstEntry)); assertEquals(true, sm.containsKey(second)); assertEquals(true, sub.containsKey(second)); assertEquals(true, set.contains(secondEntry)); - + set.remove(firstEntry); assertEquals(size - 3, sub.size()); assertEquals(size - 1, sm.size()); @@ -409,7 +424,7 @@ public abstract class AbstractTestSortedBidiMap extends AbstractTestOrderedBidiM assertEquals(false, sub.containsKey(firstEntry.getKey())); assertEquals(false, sub.containsValue(firstEntry.getValue())); assertEquals(false, set.contains(firstEntry)); - + set.remove(secondEntry); assertEquals(size - 4, sub.size()); assertEquals(size - 2, sm.size()); @@ -427,19 +442,19 @@ public abstract class AbstractTestSortedBidiMap extends AbstractTestOrderedBidiM //----------------------------------------------------------------------- public void testBidiSubMapContains() { // extra test as other tests get complex - SortedBidiMap sm = (SortedBidiMap) makeFullMap(); - Iterator it = sm.keySet().iterator(); - Object first = it.next(); - Object fromKey = it.next(); - Object second = it.next(); - Object toKey = it.next(); - Object third = it.next(); - Object firstValue = sm.get(first); - Object fromKeyValue = sm.get(fromKey); - Object secondValue = sm.get(second); - Object thirdValue = sm.get(third); - - SortedMap sub = sm.subMap(fromKey, toKey); + SortedBidiMap sm = makeFullMap(); + Iterator it = sm.keySet().iterator(); + K first = it.next(); + K fromKey = it.next(); + K second = it.next(); + K toKey = it.next(); + K third = it.next(); + V firstValue = sm.get(first); + V fromKeyValue = sm.get(fromKey); + V secondValue = sm.get(second); + V thirdValue = sm.get(third); + + SortedMap sub = sm.subMap(fromKey, toKey); assertEquals(2, sub.size()); assertEquals(true, sm.containsKey(first)); assertEquals(false, sub.containsKey(first)); @@ -462,50 +477,50 @@ public abstract class AbstractTestSortedBidiMap extends AbstractTestOrderedBidiM //----------------------------------------------------------------------- public void testBidiClearBySubMap() { if (isRemoveSupported() == false) return; - + // extra test as other tests get complex - SortedBidiMap sm = (SortedBidiMap) makeFullMap(); - Iterator it = sm.keySet().iterator(); + SortedBidiMap sm = makeFullMap(); + Iterator it = sm.keySet().iterator(); it.next(); - Object fromKey = it.next(); - Object first = it.next(); - Object second = it.next(); - Object toKey = it.next(); - - Object fromKeyValue = sm.get(fromKey); - Object firstValue = sm.get(first); - Object secondValue = sm.get(second); - Object toKeyValue = sm.get(toKey); - - SortedMap sub = sm.subMap(fromKey, toKey); + K fromKey = it.next(); + K first = it.next(); + K second = it.next(); + K toKey = it.next(); + + V fromKeyValue = sm.get(fromKey); + V firstValue = sm.get(first); + V secondValue = sm.get(second); + V toKeyValue = sm.get(toKey); + + SortedMap sub = sm.subMap(fromKey, toKey); int size = sm.size(); assertEquals(3, sub.size()); sub.clear(); assertEquals(0, sub.size()); assertEquals(size - 3, sm.size()); assertEquals(size - 3, sm.inverseBidiMap().size()); - + assertEquals(false, sm.containsKey(fromKey)); assertEquals(false, sm.containsValue(fromKeyValue)); assertEquals(false, sm.inverseBidiMap().containsKey(fromKeyValue)); assertEquals(false, sm.inverseBidiMap().containsValue(fromKey)); assertEquals(false, sub.containsKey(fromKey)); assertEquals(false, sub.containsValue(fromKeyValue)); - + assertEquals(false, sm.containsKey(first)); assertEquals(false, sm.containsValue(firstValue)); assertEquals(false, sm.inverseBidiMap().containsKey(firstValue)); assertEquals(false, sm.inverseBidiMap().containsValue(first)); assertEquals(false, sub.containsKey(first)); assertEquals(false, sub.containsValue(firstValue)); - + assertEquals(false, sm.containsKey(second)); assertEquals(false, sm.containsValue(secondValue)); assertEquals(false, sm.inverseBidiMap().containsKey(secondValue)); assertEquals(false, sm.inverseBidiMap().containsValue(second)); assertEquals(false, sub.containsKey(second)); assertEquals(false, sub.containsValue(secondValue)); - + assertEquals(true, sm.containsKey(toKey)); assertEquals(true, sm.containsValue(toKeyValue)); assertEquals(true, sm.inverseBidiMap().containsKey(toKeyValue)); @@ -517,25 +532,25 @@ public abstract class AbstractTestSortedBidiMap extends AbstractTestOrderedBidiM //----------------------------------------------------------------------- public void testBidiRemoveBySubMap() { if (isRemoveSupported() == false) return; - + // extra test as other tests get complex - SortedBidiMap sm = (SortedBidiMap) makeFullMap(); - Iterator it = sm.keySet().iterator(); + SortedBidiMap sm = makeFullMap(); + Iterator it = sm.keySet().iterator(); it.next(); it.next(); - Object fromKey = it.next(); - Object first = it.next(); - Object second = it.next(); - Object toKey = it.next(); - + K fromKey = it.next(); + K first = it.next(); + K second = it.next(); + K toKey = it.next(); + int size = sm.size(); - SortedMap sub = sm.subMap(fromKey, toKey); + SortedMap sub = sm.subMap(fromKey, toKey); assertEquals(true, sm.containsKey(first)); assertEquals(true, sub.containsKey(first)); assertEquals(true, sm.containsKey(second)); assertEquals(true, sub.containsKey(second)); - - Object firstValue = sub.remove(first); + + V firstValue = sub.remove(first); assertEquals(2, sub.size()); assertEquals(size - 1, sm.size()); assertEquals(size - 1, sm.inverseBidiMap().size()); @@ -545,8 +560,8 @@ public abstract class AbstractTestSortedBidiMap extends AbstractTestOrderedBidiM assertEquals(false, sm.inverseBidiMap().containsValue(first)); assertEquals(false, sub.containsKey(first)); assertEquals(false, sub.containsValue(firstValue)); - - Object secondValue = sub.remove(second); + + V secondValue = sub.remove(second); assertEquals(1, sub.size()); assertEquals(size - 2, sm.size()); assertEquals(size - 2, sm.inverseBidiMap().size()); @@ -561,32 +576,32 @@ public abstract class AbstractTestSortedBidiMap extends AbstractTestOrderedBidiM //----------------------------------------------------------------------- public void testBidiRemoveBySubMapEntrySet() { if (isRemoveSupported() == false) return; - + // extra test as other tests get complex - SortedBidiMap sm = (SortedBidiMap) makeFullMap(); - Iterator it = sm.keySet().iterator(); + SortedBidiMap sm = makeFullMap(); + Iterator it = sm.keySet().iterator(); it.next(); it.next(); - Object fromKey = it.next(); - Object first = it.next(); - Object second = it.next(); - Object toKey = it.next(); - + K fromKey = it.next(); + K first = it.next(); + K second = it.next(); + K toKey = it.next(); + int size = sm.size(); - SortedMap sub = sm.subMap(fromKey, toKey); - Set set = sub.entrySet(); + SortedMap sub = sm.subMap(fromKey, toKey); + Set> set = sub.entrySet(); assertEquals(3, set.size()); - Iterator it2 = set.iterator(); - Object fromEntry = it2.next(); - Map.Entry firstEntry = cloneMapEntry((Map.Entry) it2.next()); - Map.Entry secondEntry = cloneMapEntry((Map.Entry) it2.next()); + Iterator> it2 = set.iterator(); + it2.next(); + Map.Entry firstEntry = cloneMapEntry(it2.next()); + Map.Entry secondEntry = cloneMapEntry(it2.next()); assertEquals(true, sm.containsKey(first)); assertEquals(true, sub.containsKey(first)); assertEquals(true, set.contains(firstEntry)); assertEquals(true, sm.containsKey(second)); assertEquals(true, sub.containsKey(second)); assertEquals(true, set.contains(secondEntry)); - + set.remove(firstEntry); assertEquals(2, sub.size()); assertEquals(size - 1, sm.size()); @@ -598,7 +613,7 @@ public abstract class AbstractTestSortedBidiMap extends AbstractTestOrderedBidiM assertEquals(false, sub.containsKey(firstEntry.getKey())); assertEquals(false, sub.containsValue(firstEntry.getValue())); assertEquals(false, set.contains(firstEntry)); - + set.remove(secondEntry); assertEquals(1, sub.size()); assertEquals(size - 2, sm.size()); @@ -612,17 +627,17 @@ public abstract class AbstractTestSortedBidiMap extends AbstractTestOrderedBidiM assertEquals(false, set.contains(secondEntry)); } - //----------------------------------------------------------------------- + //----------------------------------------------------------------------- public BulkTest bulkTestHeadMap() { - return new AbstractTestSortedMap.TestHeadMap(this); + return new AbstractTestSortedMap.TestHeadMap(this); } public BulkTest bulkTestTailMap() { - return new AbstractTestSortedMap.TestTailMap(this); + return new AbstractTestSortedMap.TestTailMap(this); } public BulkTest bulkTestSubMap() { - return new AbstractTestSortedMap.TestSubMap(this); + return new AbstractTestSortedMap.TestSubMap(this); } } diff --git a/src/test/org/apache/commons/collections/bidimap/TestAbstractOrderedBidiMapDecorator.java b/src/test/org/apache/commons/collections/bidimap/TestAbstractOrderedBidiMapDecorator.java index 4711be531..3223033fb 100644 --- a/src/test/org/apache/commons/collections/bidimap/TestAbstractOrderedBidiMapDecorator.java +++ b/src/test/org/apache/commons/collections/bidimap/TestAbstractOrderedBidiMapDecorator.java @@ -16,13 +16,12 @@ */ package org.apache.commons.collections.bidimap; -import java.util.Map; +import java.util.SortedMap; import java.util.TreeMap; import junit.framework.Test; import junit.framework.TestSuite; -import org.apache.commons.collections.BidiMap; import org.apache.commons.collections.OrderedBidiMap; /** @@ -30,8 +29,8 @@ import org.apache.commons.collections.OrderedBidiMap; * * @version $Revision$ $Date$ */ -public class TestAbstractOrderedBidiMapDecorator - extends AbstractTestOrderedBidiMap { +public class TestAbstractOrderedBidiMapDecorator + extends AbstractTestOrderedBidiMap { public TestAbstractOrderedBidiMapDecorator(String testName) { super(testName); @@ -41,12 +40,16 @@ public class TestAbstractOrderedBidiMapDecorator return new TestSuite(TestAbstractOrderedBidiMapDecorator.class); } - public BidiMap makeEmptyBidiMap() { - return new TestOrderedBidiMap(); + /** + * {@inheritDoc} + */ + @Override + public OrderedBidiMap makeObject() { + return new TestOrderedBidiMap(); } - public Map makeConfirmedMap() { - return new TreeMap(); + public SortedMap makeConfirmedMap() { + return new TreeMap(); } public boolean isAllowNullKey() { @@ -64,21 +67,21 @@ public class TestAbstractOrderedBidiMapDecorator /** * Simple class to actually test. */ - private static final class TestOrderedBidiMap extends AbstractOrderedBidiMapDecorator { - - private TestOrderedBidiMap inverse = null; + private static final class TestOrderedBidiMap extends AbstractOrderedBidiMapDecorator { + + private TestOrderedBidiMap inverse = null; public TestOrderedBidiMap() { - super(new DualTreeBidiMap()); + super(new DualTreeBidiMap()); } - - public TestOrderedBidiMap(OrderedBidiMap map) { + + public TestOrderedBidiMap(OrderedBidiMap map) { super(map); } - - public BidiMap inverseBidiMap() { + + public OrderedBidiMap inverseBidiMap() { if (inverse == null) { - inverse = new TestOrderedBidiMap((OrderedBidiMap) getBidiMap().inverseBidiMap()); + inverse = new TestOrderedBidiMap(decorated().inverseBidiMap()); inverse.inverse = this; } return inverse; diff --git a/src/test/org/apache/commons/collections/bidimap/TestDualHashBidiMap.java b/src/test/org/apache/commons/collections/bidimap/TestDualHashBidiMap.java index 61c7488fc..4ff34cb66 100644 --- a/src/test/org/apache/commons/collections/bidimap/TestDualHashBidiMap.java +++ b/src/test/org/apache/commons/collections/bidimap/TestDualHashBidiMap.java @@ -19,7 +19,6 @@ package org.apache.commons.collections.bidimap; import junit.framework.Test; import junit.textui.TestRunner; -import org.apache.commons.collections.BidiMap; import org.apache.commons.collections.BulkTest; /** @@ -30,7 +29,7 @@ import org.apache.commons.collections.BulkTest; * @author Matthew Hawthorne * @author Stephen Colebourne */ -public class TestDualHashBidiMap extends AbstractTestBidiMap { +public class TestDualHashBidiMap extends AbstractTestBidiMap { public static void main(String[] args) { TestRunner.run(suite()); @@ -44,15 +43,19 @@ public class TestDualHashBidiMap extends AbstractTestBidiMap { super(testName); } - public BidiMap makeEmptyBidiMap() { - return new DualHashBidiMap(); + /** + * {@inheritDoc} + */ + @Override + public DualHashBidiMap makeObject() { + return new DualHashBidiMap(); } /** * Override to prevent infinite recursion of tests. */ public String[] ignoredTests() { - return new String[] {"TestDualHashBidiMap.bulkTestInverseMap.bulkTestInverseMap"}; + return new String[] { "TestDualHashBidiMap.bulkTestInverseMap.bulkTestInverseMap" }; } // public void testCreate() throws Exception { diff --git a/src/test/org/apache/commons/collections/bidimap/TestDualTreeBidiMap.java b/src/test/org/apache/commons/collections/bidimap/TestDualTreeBidiMap.java index dbf36a474..815b1141a 100644 --- a/src/test/org/apache/commons/collections/bidimap/TestDualTreeBidiMap.java +++ b/src/test/org/apache/commons/collections/bidimap/TestDualTreeBidiMap.java @@ -19,7 +19,6 @@ package org.apache.commons.collections.bidimap; import junit.framework.Test; import junit.textui.TestRunner; -import org.apache.commons.collections.BidiMap; import org.apache.commons.collections.BulkTest; /** @@ -30,7 +29,7 @@ import org.apache.commons.collections.BulkTest; * @author Matthew Hawthorne * @author Stephen Colebourne */ -public class TestDualTreeBidiMap extends AbstractTestSortedBidiMap { +public class TestDualTreeBidiMap, V extends Comparable> extends AbstractTestSortedBidiMap { public static void main(String[] args) { TestRunner.run(suite()); @@ -44,8 +43,12 @@ public class TestDualTreeBidiMap extends AbstractTestSortedBidiMap { super(testName); } - public BidiMap makeEmptyBidiMap() { - return new DualTreeBidiMap(); + /** + * {@inheritDoc} + */ + @Override + public DualTreeBidiMap makeObject() { + return new DualTreeBidiMap(); } /** diff --git a/src/test/org/apache/commons/collections/bidimap/TestDualTreeBidiMap2.java b/src/test/org/apache/commons/collections/bidimap/TestDualTreeBidiMap2.java index 10add6649..7f4909e20 100644 --- a/src/test/org/apache/commons/collections/bidimap/TestDualTreeBidiMap2.java +++ b/src/test/org/apache/commons/collections/bidimap/TestDualTreeBidiMap2.java @@ -25,13 +25,11 @@ import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; -import java.util.Map; import java.util.TreeMap; import junit.framework.Test; import junit.textui.TestRunner; -import org.apache.commons.collections.BidiMap; import org.apache.commons.collections.BulkTest; import org.apache.commons.collections.SortedBidiMap; import org.apache.commons.collections.comparators.ComparableComparator; @@ -46,7 +44,7 @@ import org.apache.commons.collections.comparators.ReverseComparator; * @author Stephen Colebourne * @author Jonas Van Poucke */ -public class TestDualTreeBidiMap2 extends AbstractTestSortedBidiMap { +public class TestDualTreeBidiMap2, V extends Comparable> extends AbstractTestSortedBidiMap { public static void main(String[] args) { TestRunner.run(suite()); @@ -60,21 +58,24 @@ public class TestDualTreeBidiMap2 extends AbstractTestSortedBidiMap { super(testName); } - public BidiMap makeEmptyBidiMap() { - return new DualTreeBidiMap(new ReverseComparator(ComparableComparator.getInstance())); + public DualTreeBidiMap makeObject() { + return new DualTreeBidiMap( + new ReverseComparator(ComparableComparator. getInstance()), + new ReverseComparator(ComparableComparator. getInstance())); } - public Map makeConfirmedMap() { - return new TreeMap(new ReverseComparator(ComparableComparator.getInstance())); + public TreeMap makeConfirmedMap() { + return new TreeMap(new ReverseComparator(ComparableComparator.getInstance())); } public void testComparator() { resetEmpty(); - SortedBidiMap bidi = (SortedBidiMap) map; + SortedBidiMap bidi = (SortedBidiMap) map; assertNotNull(bidi.comparator()); assertTrue(bidi.comparator() instanceof ReverseComparator); } + @SuppressWarnings("unchecked") public void testSerializeDeserializeCheckComparator() throws Exception { SortedBidiMap obj = (SortedBidiMap) makeObject(); if (obj instanceof Serializable && isTestSerialization()) { @@ -95,18 +96,18 @@ public class TestDualTreeBidiMap2 extends AbstractTestSortedBidiMap { } public void testSortOrder() throws Exception { - SortedBidiMap sm = (SortedBidiMap) makeFullMap(); + SortedBidiMap sm = makeFullMap(); // Sort by the comparator used in the makeEmptyBidiMap() method - List newSortedKeys = Arrays.asList(getSampleKeys()); - Collections.sort(newSortedKeys, new ReverseComparator(ComparableComparator.getInstance())); + List newSortedKeys = Arrays.asList(getSampleKeys()); + Collections.sort(newSortedKeys, new ReverseComparator(ComparableComparator.getInstance())); newSortedKeys = Collections.unmodifiableList(newSortedKeys); - Iterator mapIter = sm.keySet().iterator(); - Iterator expectedIter = newSortedKeys.iterator(); + Iterator mapIter = sm.keySet().iterator(); + Iterator expectedIter = newSortedKeys.iterator(); while (expectedIter.hasNext()) { - Object expectedKey = expectedIter.next(); - Object mapKey = mapIter.next(); + K expectedKey = expectedIter.next(); + K mapKey = mapIter.next(); assertNotNull("key in sorted list may not be null", expectedKey); assertNotNull("key in map may not be null", mapKey); assertEquals("key from sorted list and map must be equal", expectedKey, mapKey); diff --git a/src/test/org/apache/commons/collections/bidimap/TestTreeBidiMap.java b/src/test/org/apache/commons/collections/bidimap/TestTreeBidiMap.java index 9809b8d9f..a741469c6 100644 --- a/src/test/org/apache/commons/collections/bidimap/TestTreeBidiMap.java +++ b/src/test/org/apache/commons/collections/bidimap/TestTreeBidiMap.java @@ -16,7 +16,6 @@ */ package org.apache.commons.collections.bidimap; -import java.util.Map; import java.util.TreeMap; import junit.framework.Test; @@ -32,7 +31,7 @@ import org.apache.commons.collections.BulkTest; * * @author Stephen Colebourne */ -public class TestTreeBidiMap extends AbstractTestOrderedBidiMap { +public class TestTreeBidiMap, V extends Comparable> extends AbstractTestOrderedBidiMap { public static void main(String[] args) { TestRunner.run(suite()); @@ -46,12 +45,12 @@ public class TestTreeBidiMap extends AbstractTestOrderedBidiMap { super(testName); } - public BidiMap makeEmptyBidiMap() { - return new TreeBidiMap(); + public BidiMap makeObject() { + return new TreeBidiMap(); } - public Map makeConfirmedMap() { - return new TreeMap(); + public TreeMap makeConfirmedMap() { + return new TreeMap(); } /** diff --git a/src/test/org/apache/commons/collections/bidimap/TestUnmodifiableBidiMap.java b/src/test/org/apache/commons/collections/bidimap/TestUnmodifiableBidiMap.java index e06fa5f4c..8af3f179d 100644 --- a/src/test/org/apache/commons/collections/bidimap/TestUnmodifiableBidiMap.java +++ b/src/test/org/apache/commons/collections/bidimap/TestUnmodifiableBidiMap.java @@ -32,12 +32,12 @@ import org.apache.commons.collections.BulkTest; * * @author Stephen Colebourne */ -public class TestUnmodifiableBidiMap extends AbstractTestBidiMap { +public class TestUnmodifiableBidiMap extends AbstractTestBidiMap { public static void main(String[] args) { TestRunner.run(suite()); } - + public static Test suite() { return BulkTest.makeSuite(TestUnmodifiableBidiMap.class); } @@ -46,24 +46,18 @@ public class TestUnmodifiableBidiMap extends AbstractTestBidiMap { super(testName); } - public BidiMap makeEmptyBidiMap() { - return UnmodifiableBidiMap.decorate(new DualHashBidiMap()); + public BidiMap makeObject() { + return UnmodifiableBidiMap.decorate(new DualHashBidiMap()); } - public BidiMap makeFullBidiMap() { - BidiMap bidi = new DualHashBidiMap(); - for (int i = 0; i < entries.length; i++) { - bidi.put(entries[i][0], entries[i][1]); - } - return UnmodifiableBidiMap.decorate(bidi); - } - public Map makeFullMap() { - BidiMap bidi = new DualHashBidiMap(); + + public BidiMap makeFullMap() { + BidiMap bidi = new DualHashBidiMap(); addSampleMappings(bidi); return UnmodifiableBidiMap.decorate(bidi); } - - public Map makeConfirmedMap() { - return new HashMap(); + + public Map makeConfirmedMap() { + return new HashMap(); } /** @@ -76,11 +70,13 @@ public class TestUnmodifiableBidiMap extends AbstractTestBidiMap { public boolean isPutAddSupported() { return false; } + public boolean isPutChangeSupported() { return false; } + public boolean isRemoveSupported() { return false; } - + } diff --git a/src/test/org/apache/commons/collections/bidimap/TestUnmodifiableOrderedBidiMap.java b/src/test/org/apache/commons/collections/bidimap/TestUnmodifiableOrderedBidiMap.java index a7dc05244..6c732e70c 100644 --- a/src/test/org/apache/commons/collections/bidimap/TestUnmodifiableOrderedBidiMap.java +++ b/src/test/org/apache/commons/collections/bidimap/TestUnmodifiableOrderedBidiMap.java @@ -33,12 +33,12 @@ import org.apache.commons.collections.OrderedBidiMap; * * @author Stephen Colebourne */ -public class TestUnmodifiableOrderedBidiMap extends AbstractTestOrderedBidiMap { +public class TestUnmodifiableOrderedBidiMap, V extends Comparable> extends AbstractTestOrderedBidiMap { public static void main(String[] args) { TestRunner.run(suite()); } - + public static Test suite() { return BulkTest.makeSuite(TestUnmodifiableOrderedBidiMap.class); } @@ -47,24 +47,18 @@ public class TestUnmodifiableOrderedBidiMap extends AbstractTestOrderedBidiMap { super(testName); } - public BidiMap makeEmptyBidiMap() { - return UnmodifiableOrderedBidiMap.decorate(new TreeBidiMap()); + public OrderedBidiMap makeObject() { + return UnmodifiableOrderedBidiMap.decorate(new TreeBidiMap()); } - public BidiMap makeFullBidiMap() { - OrderedBidiMap bidi = new TreeBidiMap(); - for (int i = 0; i < entries.length; i++) { - bidi.put(entries[i][0], entries[i][1]); - } - return UnmodifiableOrderedBidiMap.decorate(bidi); - } - public Map makeFullMap() { - OrderedBidiMap bidi = new TreeBidiMap(); + + public BidiMap makeFullMap() { + OrderedBidiMap bidi = new TreeBidiMap(); addSampleMappings(bidi); return UnmodifiableOrderedBidiMap.decorate(bidi); } - - public Map makeConfirmedMap() { - return new TreeMap(); + + public Map makeConfirmedMap() { + return new TreeMap(); } /** @@ -73,21 +67,25 @@ public class TestUnmodifiableOrderedBidiMap extends AbstractTestOrderedBidiMap { public String[] ignoredTests() { return new String[] {"TestUnmodifiableOrderedBidiMap.bulkTestInverseMap.bulkTestInverseMap"}; } - + public boolean isAllowNullKey() { return false; } + public boolean isAllowNullValue() { return false; } + public boolean isPutAddSupported() { return false; } + public boolean isPutChangeSupported() { return false; } + public boolean isRemoveSupported() { return false; } - + } diff --git a/src/test/org/apache/commons/collections/bidimap/TestUnmodifiableSortedBidiMap.java b/src/test/org/apache/commons/collections/bidimap/TestUnmodifiableSortedBidiMap.java index a44cb8ed5..7b4597c91 100644 --- a/src/test/org/apache/commons/collections/bidimap/TestUnmodifiableSortedBidiMap.java +++ b/src/test/org/apache/commons/collections/bidimap/TestUnmodifiableSortedBidiMap.java @@ -16,13 +16,12 @@ */ package org.apache.commons.collections.bidimap; -import java.util.Map; +import java.util.SortedMap; import java.util.TreeMap; import junit.framework.Test; import junit.textui.TestRunner; -import org.apache.commons.collections.BidiMap; import org.apache.commons.collections.BulkTest; import org.apache.commons.collections.SortedBidiMap; @@ -33,12 +32,12 @@ import org.apache.commons.collections.SortedBidiMap; * * @author Stephen Colebourne */ -public class TestUnmodifiableSortedBidiMap extends AbstractTestSortedBidiMap { +public class TestUnmodifiableSortedBidiMap, V extends Comparable> extends AbstractTestSortedBidiMap { public static void main(String[] args) { TestRunner.run(suite()); } - + public static Test suite() { return BulkTest.makeSuite(TestUnmodifiableSortedBidiMap.class); } @@ -48,30 +47,25 @@ public class TestUnmodifiableSortedBidiMap extends AbstractTestSortedBidiMap { } //----------------------------------------------------------------------- - public BidiMap makeEmptyBidiMap() { - return UnmodifiableSortedBidiMap.decorate(new DualTreeBidiMap()); + public SortedBidiMap makeObject() { + return UnmodifiableSortedBidiMap.decorate(new DualTreeBidiMap()); } - public BidiMap makeFullBidiMap() { - SortedBidiMap bidi = new DualTreeBidiMap(); - for (int i = 0; i < entries.length; i++) { - bidi.put(entries[i][0], entries[i][1]); - } - return UnmodifiableSortedBidiMap.decorate(bidi); - } - public Map makeFullMap() { - SortedBidiMap bidi = new DualTreeBidiMap(); + + public SortedBidiMap makeFullMap() { + SortedBidiMap bidi = new DualTreeBidiMap(); addSampleMappings(bidi); return UnmodifiableSortedBidiMap.decorate(bidi); } - - public Map makeConfirmedMap() { - return new TreeMap(); + + public SortedMap makeConfirmedMap() { + return new TreeMap(); } public boolean isSubMapViewsSerializable() { // TreeMap sub map views have a bug in deserialization. return false; } + public String[] ignoredTests() { // Override to prevent infinite recursion of tests. return new String[] {"TestUnmodifiableSortedBidiMap.bulkTestInverseMap.bulkTestInverseMap"}; @@ -81,17 +75,21 @@ public class TestUnmodifiableSortedBidiMap extends AbstractTestSortedBidiMap { public boolean isAllowNullKey() { return false; } + public boolean isAllowNullValue() { return false; } + public boolean isPutAddSupported() { return false; } + public boolean isPutChangeSupported() { return false; } + public boolean isRemoveSupported() { return false; } - + } diff --git a/src/test/org/apache/commons/collections/buffer/TestBlockingBuffer.java b/src/test/org/apache/commons/collections/buffer/TestBlockingBuffer.java index 6dce5fc5a..c5071a600 100644 --- a/src/test/org/apache/commons/collections/buffer/TestBlockingBuffer.java +++ b/src/test/org/apache/commons/collections/buffer/TestBlockingBuffer.java @@ -29,30 +29,31 @@ import java.util.LinkedList; import java.util.Set; /** - * Extension of {@link AbstractTestObject} for exercising the {@link BlockingBuffer} implementation. + * Extension of {@link AbstractTestObject} for exercising the + * {@link BlockingBuffer} implementation. * * @author Janek Bogucki * @author Phil Steitz * @version $Revision$ * @since Commons Collections 3.0 */ -public class TestBlockingBuffer extends AbstractTestObject { +public class TestBlockingBuffer extends AbstractTestObject { - public TestBlockingBuffer( String testName ) { - super( testName ); + public TestBlockingBuffer(String testName) { + super(testName); } public static Test suite() { - return new TestSuite( TestBlockingBuffer.class ); + return new TestSuite(TestBlockingBuffer.class); } - public static void main( String args[] ) { - String[] testCaseName = {TestBlockingBuffer.class.getName()}; - junit.textui.TestRunner.main( testCaseName ); + public static void main(String args[]) { + String[] testCaseName = { TestBlockingBuffer.class.getName() }; + junit.textui.TestRunner.main(testCaseName); } - public Object makeObject() { - return BlockingBuffer.decorate( new MyBuffer() ); + public Buffer makeObject() { + return BlockingBuffer.decorate(new MyBuffer()); } public boolean isEqualsCheckable() { @@ -61,113 +62,122 @@ public class TestBlockingBuffer extends AbstractTestObject { //----------------------------------------------------------------------- + @SuppressWarnings("unchecked") + protected E makeElement() { + return (E) new Object(); + } + /** - * Tests {@link BlockingBuffer#get()} in combination with {@link BlockingBuffer#add(Object)}. + * Tests {@link BlockingBuffer#get()} in combination with + * {@link BlockingBuffer#add(Object)}. */ public void testGetWithAdd() { - Buffer blockingBuffer = BlockingBuffer.decorate( new MyBuffer() ); - Object obj = new Object(); - new DelayedAdd( blockingBuffer, obj ).start(); + Buffer blockingBuffer = makeObject(); + E obj = makeElement(); + new DelayedAdd(blockingBuffer, obj).start(); // verify does not throw BufferUnderflowException; should block until other thread has added to the buffer . - assertSame( obj, blockingBuffer.get() ); + assertSame(obj, blockingBuffer.get()); } public void testGetWithAddTimeout() { - Buffer blockingBuffer = BlockingBuffer.decorate( new MyBuffer(), 500 ); - Object obj = new Object(); - new DelayedAdd( blockingBuffer, obj, 100 ).start(); + Buffer blockingBuffer = BlockingBuffer.decorate(new MyBuffer(), 500); + E obj = makeElement(); + new DelayedAdd(blockingBuffer, obj, 100).start(); // verify does not throw BufferUnderflowException; should block until other thread has added to the buffer . - assertSame( obj, blockingBuffer.get() ); + assertSame(obj, blockingBuffer.get()); } //----------------------------------------------------------------------- /** - * Tests {@link BlockingBuffer#get()} in combination with {@link BlockingBuffer#addAll(java.util.Collection)}. + * Tests {@link BlockingBuffer#get()} in combination with + * {@link BlockingBuffer#addAll(java.util.Collection)}. */ public void testGetWithAddAll() { - Buffer blockingBuffer = BlockingBuffer.decorate( new MyBuffer() ); - Object obj = new Object(); - new DelayedAddAll( blockingBuffer, obj ).start(); + Buffer blockingBuffer = makeObject(); + E obj = makeElement(); + new DelayedAddAll(blockingBuffer, obj).start(); // verify does not throw BufferUnderflowException; should block until other thread has added to the buffer . - assertSame( obj, blockingBuffer.get() ); + assertSame(obj, blockingBuffer.get()); } public void testGetWithAddAllTimeout() { - Buffer blockingBuffer = BlockingBuffer.decorate( new MyBuffer(), 500 ); - Object obj = new Object(); - new DelayedAddAll( blockingBuffer, obj, 100 ).start(); + Buffer blockingBuffer = BlockingBuffer.decorate(new MyBuffer(), 500); + E obj = makeElement(); + new DelayedAddAll(blockingBuffer, obj, 100).start(); // verify does not throw BufferUnderflowException; should block until other thread has added to the buffer . - assertSame( obj, blockingBuffer.get() ); + assertSame(obj, blockingBuffer.get()); } //----------------------------------------------------------------------- /** - * Tests {@link BlockingBuffer#remove()} in combination with {@link BlockingBuffer#add(Object)}. + * Tests {@link BlockingBuffer#remove()} in combination with + * {@link BlockingBuffer#add(Object)}. */ public void testRemoveWithAdd() { - Buffer blockingBuffer = BlockingBuffer.decorate( new MyBuffer() ); - Object obj = new Object(); - new DelayedAdd( blockingBuffer, obj ).start(); + Buffer blockingBuffer = makeObject(); + E obj = makeElement(); + new DelayedAdd(blockingBuffer, obj).start(); // verify does not throw BufferUnderflowException; should block until other thread has added to the buffer . - assertSame( obj, blockingBuffer.remove() ); + assertSame(obj, blockingBuffer.remove()); } public void testRemoveWithAddTimeout() { - Buffer blockingBuffer = BlockingBuffer.decorate( new MyBuffer(), 100 ); - Object obj = new Object(); - new DelayedAdd( blockingBuffer, obj, 500 ).start(); + Buffer blockingBuffer = BlockingBuffer.decorate(new MyBuffer(), 100); + E obj = makeElement(); + new DelayedAdd(blockingBuffer, obj, 500).start(); try { blockingBuffer.remove(); - } - catch( BufferUnderflowException e ) { + } catch (BufferUnderflowException e) { } } + //----------------------------------------------------------------------- /** - * Tests {@link BlockingBuffer#remove()} in combination with {@link BlockingBuffer#addAll(java.util.Collection)}. + * Tests {@link BlockingBuffer#remove()} in combination with + * {@link BlockingBuffer#addAll(java.util.Collection)}. */ public void testRemoveWithAddAll() { - Buffer blockingBuffer = BlockingBuffer.decorate( new MyBuffer() ); - Object obj = new Object(); - new DelayedAddAll( blockingBuffer, obj ).start(); + Buffer blockingBuffer = makeObject(); + E obj = makeElement(); + new DelayedAddAll(blockingBuffer, obj).start(); // verify does not throw BufferUnderflowException; should block until other thread has added to the buffer . - assertSame( obj, blockingBuffer.remove() ); + assertSame(obj, blockingBuffer.remove()); } public void testRemoveWithAddAllTimeout() { - Buffer blockingBuffer = BlockingBuffer.decorate( new MyBuffer(), 100 ); - Object obj = new Object(); - new DelayedAddAll( blockingBuffer, obj, 500 ).start(); + Buffer blockingBuffer = BlockingBuffer.decorate(new MyBuffer(), 100); + E obj = makeElement(); + new DelayedAddAll(blockingBuffer, obj, 500).start(); try { blockingBuffer.remove(); - } - catch( BufferUnderflowException e ) { + } catch (BufferUnderflowException e) { } } + //----------------------------------------------------------------------- /** - * Tests {@link BlockingBuffer#get()} in combination with {@link BlockingBuffer#add(Object)} using multiple read - * threads. - *

- * Two read threads should block on an empty buffer until one object is added then both threads should complete. + * Tests {@link BlockingBuffer#get()} in combination with + * {@link BlockingBuffer#add(Object)} using multiple read threads.

Two + * read threads should block on an empty buffer until one object is added + * then both threads should complete. */ public void testBlockedGetWithAdd() { - Buffer blockingBuffer = BlockingBuffer.decorate( new MyBuffer() ); - Object obj = new Object(); + Buffer blockingBuffer = makeObject(); + E obj = makeElement(); // run methods will get and compare -- must wait for add - Thread thread1 = new ReadThread( blockingBuffer, obj ); - Thread thread2 = new ReadThread( blockingBuffer, obj ); + Thread thread1 = new ReadThread(blockingBuffer, obj); + Thread thread2 = new ReadThread(blockingBuffer, obj); thread1.start(); thread2.start(); @@ -175,32 +185,32 @@ public class TestBlockingBuffer extends AbstractTestObject { delay(); // notifyAll should allow both read threads to complete - blockingBuffer.add( obj ); + blockingBuffer.add(obj); // allow notified threads to complete delay(); // There should not be any threads waiting. - if( thread1.isAlive() || thread2.isAlive() ) { - fail( "Live thread(s) when both should be dead." ); + if (thread1.isAlive() || thread2.isAlive()) { + fail("Live thread(s) when both should be dead."); } } //----------------------------------------------------------------------- /** - * Tests {@link BlockingBuffer#get()} in combination with {@link BlockingBuffer#addAll(java.util.Collection)} using - * multiple read threads. - *

- * Two read threads should block on an empty buffer until a singleton is added then both threads should complete. + * Tests {@link BlockingBuffer#get()} in combination with + * {@link BlockingBuffer#addAll(java.util.Collection)} using multiple read + * threads.

Two read threads should block on an empty buffer until a + * singleton is added then both threads should complete. */ public void testBlockedGetWithAddAll() { - Buffer blockingBuffer = BlockingBuffer.decorate( new MyBuffer() ); - Object obj = new Object(); + Buffer blockingBuffer = makeObject(); + E obj = makeElement(); // run methods will get and compare -- must wait for addAll - Thread thread1 = new ReadThread( blockingBuffer, obj ); - Thread thread2 = new ReadThread( blockingBuffer, obj ); + Thread thread1 = new ReadThread(blockingBuffer, obj); + Thread thread2 = new ReadThread(blockingBuffer, obj); thread1.start(); thread2.start(); @@ -208,14 +218,14 @@ public class TestBlockingBuffer extends AbstractTestObject { delay(); // notifyAll should allow both read threads to complete - blockingBuffer.addAll( Collections.singleton( obj ) ); + blockingBuffer.addAll(Collections.singleton(obj)); // allow notified threads to complete delay(); // There should not be any threads waiting. - if( thread1.isAlive() || thread2.isAlive() ) { - fail( "Live thread(s) when both should be dead." ); + if (thread1.isAlive() || thread2.isAlive()) { + fail("Live thread(s) when both should be dead."); } } @@ -225,12 +235,12 @@ public class TestBlockingBuffer extends AbstractTestObject { * Tests interrupted {@link BlockingBuffer#get()}. */ public void testInterruptedGet() { - Buffer blockingBuffer = BlockingBuffer.decorate( new MyBuffer() ); - Object obj = new Object(); + Buffer blockingBuffer = makeObject(); + E obj = makeElement(); // spawn a read thread to wait on the empty buffer - ArrayList exceptionList = new ArrayList(); - Thread thread = new ReadThread( blockingBuffer, obj, exceptionList ); + ArrayList exceptionList = new ArrayList(); + Thread thread = new ReadThread(blockingBuffer, obj, exceptionList); thread.start(); // Interrupting the thread should cause it to throw BufferUnderflowException @@ -238,10 +248,10 @@ public class TestBlockingBuffer extends AbstractTestObject { // Chill, so thread can throw and add message to exceptionList delay(); - assertTrue( "Thread interrupt should have led to underflow", - exceptionList.contains( "BufferUnderFlow" ) ); - if( thread.isAlive() ) { - fail( "Read thread has hung." ); + assertTrue("Thread interrupt should have led to underflow", exceptionList + .contains("BufferUnderFlow")); + if (thread.isAlive()) { + fail("Read thread has hung."); } } @@ -249,115 +259,116 @@ public class TestBlockingBuffer extends AbstractTestObject { //----------------------------------------------------------------------- /** - * Tests {@link BlockingBuffer#remove()} in combination with {@link BlockingBuffer#add(Object)} using multiple read - * threads. - *

- * Two read threads should block on an empty buffer until one object is added then one thread should complete. The - * remaining thread should complete after the addition of a second object. + * Tests {@link BlockingBuffer#remove()} in combination with + * {@link BlockingBuffer#add(Object)} using multiple read threads.

Two + * read threads should block on an empty buffer until one object is added + * then one thread should complete. The remaining thread should complete + * after the addition of a second object. */ public void testBlockedRemoveWithAdd() { - Buffer blockingBuffer = BlockingBuffer.decorate( new MyBuffer() ); - Object obj = new Object(); + Buffer blockingBuffer = makeObject(); + E obj = makeElement(); // run methods will remove and compare -- must wait for add - Thread thread1 = new ReadThread( blockingBuffer, obj, null, "remove" ); - Thread thread2 = new ReadThread( blockingBuffer, obj, null, "remove" ); + Thread thread1 = new ReadThread(blockingBuffer, obj, null, "remove"); + Thread thread2 = new ReadThread(blockingBuffer, obj, null, "remove"); thread1.start(); thread2.start(); // give hungry read threads ample time to hang delay(); - blockingBuffer.add( obj ); + blockingBuffer.add(obj); // allow notified threads to complete delay(); // There should be one thread waiting. - assertTrue( "There is one thread waiting", thread1.isAlive() ^ thread2.isAlive() ); - blockingBuffer.add( obj ); + assertTrue("There is one thread waiting", thread1.isAlive() ^ thread2.isAlive()); + blockingBuffer.add(obj); // allow notified thread to complete delay(); // There should not be any threads waiting. - if( thread1.isAlive() || thread2.isAlive() ) { - fail( "Live thread(s) when both should be dead." ); + if (thread1.isAlive() || thread2.isAlive()) { + fail("Live thread(s) when both should be dead."); } } //----------------------------------------------------------------------- /** - * Tests {@link BlockingBuffer#remove()} in combination with {@link BlockingBuffer#addAll(java.util.Collection)} - * using multiple read threads. - *

- * Two read threads should block on an empty buffer until a singleton collection is added then one thread should - * complete. The remaining thread should complete after the addition of a second singleton. + * Tests {@link BlockingBuffer#remove()} in combination with + * {@link BlockingBuffer#addAll(java.util.Collection)} using multiple read + * threads.

Two read threads should block on an empty buffer until a + * singleton collection is added then one thread should complete. The + * remaining thread should complete after the addition of a second + * singleton. */ public void testBlockedRemoveWithAddAll1() { - Buffer blockingBuffer = BlockingBuffer.decorate( new MyBuffer() ); - Object obj = new Object(); + Buffer blockingBuffer = makeObject(); + E obj = makeElement(); // run methods will remove and compare -- must wait for addAll - Thread thread1 = new ReadThread( blockingBuffer, obj, null, "remove" ); - Thread thread2 = new ReadThread( blockingBuffer, obj, null, "remove" ); + Thread thread1 = new ReadThread(blockingBuffer, obj, null, "remove"); + Thread thread2 = new ReadThread(blockingBuffer, obj, null, "remove"); thread1.start(); thread2.start(); // give hungry read threads ample time to hang delay(); - blockingBuffer.addAll( Collections.singleton( obj ) ); + blockingBuffer.addAll(Collections.singleton(obj)); // allow notified threads to complete delay(); // There should be one thread waiting. - assertTrue( "There is one thread waiting", thread1.isAlive() ^ thread2.isAlive() ); - blockingBuffer.addAll( Collections.singleton( obj ) ); + assertTrue("There is one thread waiting", thread1.isAlive() ^ thread2.isAlive()); + blockingBuffer.addAll(Collections.singleton(obj)); // allow notified thread to complete delay(); // There should not be any threads waiting. - if( thread1.isAlive() || thread2.isAlive() ) { - fail( "Live thread(s) when both should be dead." ); + if (thread1.isAlive() || thread2.isAlive()) { + fail("Live thread(s) when both should be dead."); } } //----------------------------------------------------------------------- /** - * Tests {@link BlockingBuffer#remove()} in combination with {@link BlockingBuffer#addAll(java.util.Collection)} - * using multiple read threads. - *

- * Two read threads should block on an empty buffer until a collection with two distinct objects is added then both - * threads should complete. Each thread should have read a different object. + * Tests {@link BlockingBuffer#remove()} in combination with + * {@link BlockingBuffer#addAll(java.util.Collection)} using multiple read + * threads.

Two read threads should block on an empty buffer until a + * collection with two distinct objects is added then both threads should + * complete. Each thread should have read a different object. */ public void testBlockedRemoveWithAddAll2() { - Buffer blockingBuffer = BlockingBuffer.decorate( new MyBuffer() ); - Object obj1 = new Object(); - Object obj2 = new Object(); - Set objs = Collections.synchronizedSet( new HashSet() ); - objs.add( obj1 ); - objs.add( obj2 ); + Buffer blockingBuffer = makeObject(); + E obj1 = makeElement(); + E obj2 = makeElement(); + Set objs = Collections.synchronizedSet(new HashSet()); + objs.add(obj1); + objs.add(obj2); // run methods will remove and compare -- must wait for addAll - Thread thread1 = new ReadThread( blockingBuffer, objs, "remove" ); - Thread thread2 = new ReadThread( blockingBuffer, objs, "remove" ); + Thread thread1 = new ReadThread(blockingBuffer, objs, "remove"); + Thread thread2 = new ReadThread(blockingBuffer, objs, "remove"); thread1.start(); thread2.start(); // give hungry read threads ample time to hang delay(); - blockingBuffer.addAll( objs ); + blockingBuffer.addAll(objs); // allow notified threads to complete delay(); - assertEquals( "Both objects were removed", 0, objs.size() ); + assertEquals("Both objects were removed", 0, objs.size()); // There should not be any threads waiting. - if( thread1.isAlive() || thread2.isAlive() ) { - fail( "Live thread(s) when both should be dead." ); + if (thread1.isAlive() || thread2.isAlive()) { + fail("Live thread(s) when both should be dead."); } } @@ -367,12 +378,12 @@ public class TestBlockingBuffer extends AbstractTestObject { * Tests interrupted remove. */ public void testInterruptedRemove() { - Buffer blockingBuffer = BlockingBuffer.decorate( new MyBuffer() ); - Object obj = new Object(); + Buffer blockingBuffer = makeObject(); + E obj = makeElement(); // spawn a read thread to wait on the empty buffer - ArrayList exceptionList = new ArrayList(); - Thread thread = new ReadThread( blockingBuffer, obj, exceptionList, "remove" ); + ArrayList exceptionList = new ArrayList(); + Thread thread = new ReadThread(blockingBuffer, obj, exceptionList, "remove"); thread.start(); // Interrupting the thread should cause it to throw BufferUnderflowException @@ -380,49 +391,47 @@ public class TestBlockingBuffer extends AbstractTestObject { // Chill, so thread can throw and add message to exceptionList delay(); - assertTrue( "Thread interrupt should have led to underflow", - exceptionList.contains( "BufferUnderFlow" ) ); - if( thread.isAlive() ) { - fail( "Read thread has hung." ); + assertTrue("Thread interrupt should have led to underflow", exceptionList + .contains("BufferUnderFlow")); + if (thread.isAlive()) { + fail("Read thread has hung."); } } public void testTimeoutGet() { - final BlockingBuffer buffer = new BlockingBuffer( new MyBuffer() ); + final BlockingBuffer buffer = new BlockingBuffer(new MyBuffer()); try { - buffer.get( 100 ); - fail( "Get should have timed out." ); - } - catch( BufferUnderflowException e ) { + buffer.get(100); + fail("Get should have timed out."); + } catch (BufferUnderflowException e) { } } public void testTimeoutRemove() { - final BlockingBuffer buffer = new BlockingBuffer( new MyBuffer() ); + final BlockingBuffer buffer = new BlockingBuffer(new MyBuffer()); try { - buffer.remove( 100 ); - fail( "Get should have timed out." ); - } - catch( BufferUnderflowException e ) { + buffer.remove(100); + fail("Get should have timed out."); + } catch (BufferUnderflowException e) { } } - protected static class DelayedAdd extends Thread { + protected static class DelayedAdd extends Thread { - Buffer buffer; + Buffer buffer; - Object obj; + E obj; long delay = 1000; - public DelayedAdd( Buffer buffer, Object obj, long delay ) { + public DelayedAdd(Buffer buffer, E obj, long delay) { this.buffer = buffer; this.obj = obj; this.delay = delay; } - DelayedAdd( Buffer buffer, Object obj ) { + DelayedAdd(Buffer buffer, E obj) { super(); this.buffer = buffer; this.obj = obj; @@ -431,29 +440,28 @@ public class TestBlockingBuffer extends AbstractTestObject { public void run() { try { // wait for other thread to block on get() or remove() - Thread.sleep( delay ); + Thread.sleep(delay); + } catch (InterruptedException e) { } - catch( InterruptedException e ) { - } - buffer.add( obj ); + buffer.add(obj); } } - protected static class DelayedAddAll extends Thread { + protected static class DelayedAddAll extends Thread { - Buffer buffer; + Buffer buffer; - Object obj; + E obj; long delay = 100; - public DelayedAddAll( Buffer buffer, Object obj, long delay ) { + public DelayedAddAll(Buffer buffer, E obj, long delay) { this.buffer = buffer; this.obj = obj; this.delay = delay; } - DelayedAddAll( Buffer buffer, Object obj ) { + DelayedAddAll(Buffer buffer, E obj) { super(); this.buffer = buffer; this.obj = obj; @@ -462,40 +470,39 @@ public class TestBlockingBuffer extends AbstractTestObject { public void run() { try { // wait for other thread to block on get() or remove() - Thread.sleep( delay ); + Thread.sleep(delay); + } catch (InterruptedException e) { } - catch( InterruptedException e ) { - } - buffer.addAll( Collections.singleton( obj ) ); + buffer.addAll(Collections.singleton(obj)); } } - protected static class ReadThread extends Thread { + protected static class ReadThread extends Thread { - Buffer buffer; + Buffer buffer; Object obj; - ArrayList exceptionList = null; + ArrayList exceptionList = null; String action = "get"; - Set objs; + Set objs; - ReadThread( Buffer buffer, Object obj ) { + ReadThread(Buffer buffer, Object obj) { super(); this.buffer = buffer; this.obj = obj; } - ReadThread( Buffer buffer, Object obj, ArrayList exceptionList ) { + ReadThread(Buffer buffer, Object obj, ArrayList exceptionList) { super(); this.buffer = buffer; this.obj = obj; this.exceptionList = exceptionList; } - ReadThread( Buffer buffer, Object obj, ArrayList exceptionList, String action ) { + ReadThread(Buffer buffer, Object obj, ArrayList exceptionList, String action) { super(); this.buffer = buffer; this.obj = obj; @@ -503,7 +510,7 @@ public class TestBlockingBuffer extends AbstractTestObject { this.action = action; } - ReadThread( Buffer buffer, Set objs, String action ) { + ReadThread(Buffer buffer, Set objs, String action) { super(); this.buffer = buffer; this.objs = objs; @@ -512,46 +519,43 @@ public class TestBlockingBuffer extends AbstractTestObject { public void run() { try { - if( action == "get" ) { - assertSame( obj, buffer.get() ); - } - else { - if( null != obj ) { - assertSame( obj, buffer.remove() ); - } - else { - assertTrue( objs.remove( buffer.remove() ) ); + if (action == "get") { + assertSame(obj, buffer.get()); + } else { + if (null != obj) { + assertSame(obj, buffer.remove()); + } else { + assertTrue(objs.remove(buffer.remove())); } } - } - catch( BufferUnderflowException ex ) { - exceptionList.add( "BufferUnderFlow" ); + } catch (BufferUnderflowException ex) { + exceptionList.add("BufferUnderFlow"); } } } - protected static class MyBuffer extends LinkedList implements Buffer { + @SuppressWarnings("serial") + protected static class MyBuffer extends LinkedList implements Buffer { - public Object get() { - if( isEmpty() ) { + public E get() { + if (isEmpty()) { throw new BufferUnderflowException(); } - return get( 0 ); + return get(0); } - public Object remove() { - if( isEmpty() ) { + public E remove() { + if (isEmpty()) { throw new BufferUnderflowException(); } - return remove( 0 ); + return remove(0); } } private void delay() { try { Thread.sleep( 200 ); - } - catch( InterruptedException e ) { + } catch (InterruptedException e) { } } @@ -559,15 +563,15 @@ public class TestBlockingBuffer extends AbstractTestObject { return "3.1"; } -// public void testCreate() throws Exception { -// Buffer buffer = BlockingBuffer.decorate(new UnboundedFifoBuffer()); -// writeExternalFormToDisk((java.io.Serializable) buffer, -// "D:/dev/collections/data/test/BlockingBuffer.emptyCollection.version3.1.obj"); -// buffer = BlockingBuffer.decorate(new UnboundedFifoBuffer()); -// buffer.add("A"); -// buffer.add("B"); -// buffer.add("C"); -// writeExternalFormToDisk((java.io.Serializable) buffer, -// "D:/dev/collections/data/test/BlockingBuffer.fullCollection.version3.1.obj"); -// } + // public void testCreate() throws Exception { + // Buffer buffer = BlockingBuffer.decorate(new UnboundedFifoBuffer()); + // writeExternalFormToDisk((java.io.Serializable) buffer, + // "D:/dev/collections/data/test/BlockingBuffer.emptyCollection.version3.1.obj"); + // buffer = BlockingBuffer.decorate(new UnboundedFifoBuffer()); + // buffer.add("A"); + // buffer.add("B"); + // buffer.add("C"); + // writeExternalFormToDisk((java.io.Serializable) buffer, + // "D:/dev/collections/data/test/BlockingBuffer.fullCollection.version3.1.obj"); + // } } diff --git a/src/test/org/apache/commons/collections/buffer/TestBoundedBuffer.java b/src/test/org/apache/commons/collections/buffer/TestBoundedBuffer.java index 0d76ef90f..849a54c1d 100644 --- a/src/test/org/apache/commons/collections/buffer/TestBoundedBuffer.java +++ b/src/test/org/apache/commons/collections/buffer/TestBoundedBuffer.java @@ -28,7 +28,7 @@ import java.util.Arrays; import junit.framework.Test; import junit.framework.TestSuite; -public class TestBoundedBuffer extends AbstractTestObject { +public class TestBoundedBuffer extends AbstractTestObject { public TestBoundedBuffer(String testName) { super(testName); @@ -51,136 +51,142 @@ public class TestBoundedBuffer extends AbstractTestObject { return false; } - public Object makeObject() { - return BoundedBuffer.decorate(new UnboundedFifoBuffer(), 1); + public Buffer makeObject() { + return BoundedBuffer.decorate(new UnboundedFifoBuffer(), 1); } //----------------------------------------------------------------------- + @SuppressWarnings("unchecked") public void testMaxSize() { - final Buffer bounded = BoundedBuffer.decorate(new UnboundedFifoBuffer(), 2, 500); - BoundedCollection bc = (BoundedCollection) bounded; + final Buffer bounded = BoundedBuffer.decorate(new UnboundedFifoBuffer(), 2, 500); + BoundedCollection bc = (BoundedCollection) bounded; assertEquals(2, bc.maxSize()); assertEquals(false, bc.isFull()); - bounded.add("A"); + bounded.add((E) "A"); assertEquals(false, bc.isFull()); - bounded.add("B"); + bounded.add((E) "B"); assertEquals(true, bc.isFull()); bounded.remove(); assertEquals(false, bc.isFull()); try { - BoundedBuffer.decorate(new UnboundedFifoBuffer(), 0); + BoundedBuffer.decorate(new UnboundedFifoBuffer(), 0); fail(); } catch (IllegalArgumentException ex) {} try { - BoundedBuffer.decorate(new UnboundedFifoBuffer(), -1); + BoundedBuffer.decorate(new UnboundedFifoBuffer(), -1); fail(); } catch (IllegalArgumentException ex) {} } + @SuppressWarnings("unchecked") public void testAddToFullBufferNoTimeout() { - final Buffer bounded = BoundedBuffer.decorate(new UnboundedFifoBuffer(), 1); - bounded.add( "Hello" ); + final Buffer bounded = makeObject(); + bounded.add((E) "Hello"); try { - bounded.add("World"); + bounded.add((E) "World"); fail(); } catch (BufferOverflowException e) { } } + @SuppressWarnings("unchecked") public void testAddAllToFullBufferNoTimeout() { - final Buffer bounded = BoundedBuffer.decorate(new UnboundedFifoBuffer(), 1); - bounded.add( "Hello" ); + final Buffer bounded = makeObject(); + bounded.add((E) "Hello"); try { - bounded.addAll(Collections.singleton("World")); + bounded.addAll(Collections.singleton((E) "World")); fail(); } catch (BufferOverflowException e) { } } + @SuppressWarnings("unchecked") public void testAddAllToEmptyBufferExceedMaxSizeNoTimeout() { - final Buffer bounded = BoundedBuffer.decorate(new UnboundedFifoBuffer(), 1); + final Buffer bounded = makeObject(); try { - bounded.addAll(Collections.nCopies(2, "test")); + bounded.addAll(Collections.nCopies(2, (E) "test")); fail(); } catch (BufferOverflowException e) { } } + @SuppressWarnings("unchecked") public void testAddToFullBufferRemoveViaIterator() { - final Buffer bounded = BoundedBuffer.decorate(new UnboundedFifoBuffer(), 1, 500); - bounded.add( "Hello" ); - new DelayedIteratorRemove( bounded, 200 ).start(); - bounded.add( "World" ); - assertEquals( 1, bounded.size() ); - assertEquals( "World", bounded.get() ); + final Buffer bounded = BoundedBuffer.decorate(new UnboundedFifoBuffer(), 1, 500); + bounded.add((E) "Hello"); + new DelayedIteratorRemove(bounded, 200).start(); + bounded.add((E) "World"); + assertEquals(1, bounded.size()); + assertEquals("World", bounded.get()); } + @SuppressWarnings("unchecked") public void testAddAllToFullBufferRemoveViaIterator() { - final Buffer bounded = BoundedBuffer.decorate(new UnboundedFifoBuffer(), 2, 500); - bounded.add( "Hello" ); - bounded.add( "World" ); - new DelayedIteratorRemove( bounded, 200, 2 ).start(); - bounded.addAll( Arrays.asList( new String[] { "Foo", "Bar" } ) ); - assertEquals( 2, bounded.size() ); - assertEquals( "Foo", bounded.remove() ); - assertEquals( "Bar", bounded.remove() ); + final Buffer bounded = BoundedBuffer.decorate(new UnboundedFifoBuffer(), 2, 500); + bounded.add((E) "Hello"); + bounded.add((E) "World"); + new DelayedIteratorRemove(bounded, 200, 2).start(); + bounded.addAll(Arrays.asList((E[]) new String[] { "Foo", "Bar" })); + assertEquals(2, bounded.size()); + assertEquals("Foo", bounded.remove()); + assertEquals("Bar", bounded.remove()); } + @SuppressWarnings("unchecked") public void testAddToFullBufferWithTimeout() { - final Buffer bounded = BoundedBuffer.decorate(new UnboundedFifoBuffer(), 1, 500); - bounded.add( "Hello" ); - new DelayedRemove( bounded, 200 ).start(); - bounded.add( "World" ); - assertEquals( 1, bounded.size() ); - assertEquals( "World", bounded.get() ); + final Buffer bounded = BoundedBuffer.decorate(new UnboundedFifoBuffer(), 1, 500); + bounded.add((E) "Hello"); + new DelayedRemove(bounded, 200).start(); + bounded.add((E) "World"); + assertEquals(1, bounded.size()); + assertEquals("World", bounded.get()); try { - bounded.add( "!" ); + bounded.add((E) "!"); fail(); - } - catch( BufferOverflowException e ) { + } catch (BufferOverflowException e) { } } + @SuppressWarnings("unchecked") public void testAddAllToFullBufferWithTimeout() { - final Buffer bounded = BoundedBuffer.decorate(new UnboundedFifoBuffer(), 2, 500); - bounded.add( "Hello" ); - bounded.add( "World" ); - new DelayedRemove( bounded, 200, 2 ).start(); + final Buffer bounded = BoundedBuffer.decorate(new UnboundedFifoBuffer(), 2, 500); + bounded.add((E) "Hello"); + bounded.add((E) "World"); + new DelayedRemove(bounded, 200, 2).start(); - bounded.addAll( Arrays.asList( new String[] { "Foo", "Bar" } ) ); - assertEquals( 2, bounded.size() ); - assertEquals( "Foo", bounded.get() ); + bounded.addAll(Arrays.asList((E[]) new String[] { "Foo", "Bar" })); + assertEquals(2, bounded.size()); + assertEquals("Foo", bounded.get()); try { - bounded.add( "!" ); + bounded.add((E) "!"); fail(); - } - catch( BufferOverflowException e ) { + } catch (BufferOverflowException e) { } } private class DelayedIteratorRemove extends Thread { - private final Buffer buffer; + private final Buffer buffer; private final long delay; private final int nToRemove; - public DelayedIteratorRemove(Buffer buffer, long delay, int nToRemove) { + public DelayedIteratorRemove(Buffer buffer, long delay, int nToRemove) { this.buffer = buffer; this.delay = delay; this.nToRemove = nToRemove; } - public DelayedIteratorRemove(Buffer buffer, long delay) { + public DelayedIteratorRemove(Buffer buffer, long delay) { this(buffer, delay, 1); } public void run() { try { Thread.sleep(delay); - Iterator iter = buffer.iterator(); + Iterator iter = buffer.iterator(); for (int i = 0; i < nToRemove; ++i) { iter.next(); iter.remove(); @@ -193,19 +199,19 @@ public class TestBoundedBuffer extends AbstractTestObject { private class DelayedRemove extends Thread { - private final Buffer buffer; + private final Buffer buffer; private final long delay; private final int nToRemove; - public DelayedRemove(Buffer buffer, long delay, int nToRemove) { + public DelayedRemove(Buffer buffer, long delay, int nToRemove) { this.buffer = buffer; this.delay = delay; this.nToRemove = nToRemove; } - public DelayedRemove(Buffer buffer, long delay) { + public DelayedRemove(Buffer buffer, long delay) { this(buffer, delay, 1); } @@ -219,4 +225,4 @@ public class TestBoundedBuffer extends AbstractTestObject { } } } -} \ No newline at end of file +} diff --git a/src/test/org/apache/commons/collections/buffer/TestBoundedFifoBuffer.java b/src/test/org/apache/commons/collections/buffer/TestBoundedFifoBuffer.java index 80e47f647..8ea711394 100644 --- a/src/test/org/apache/commons/collections/buffer/TestBoundedFifoBuffer.java +++ b/src/test/org/apache/commons/collections/buffer/TestBoundedFifoBuffer.java @@ -17,8 +17,8 @@ package org.apache.commons.collections.buffer; import java.util.ArrayList; -import java.util.Collection; import java.util.Iterator; +import java.util.List; import junit.framework.Test; @@ -33,7 +33,7 @@ import org.apache.commons.collections.collection.AbstractTestCollection; * * @author Paul Jack */ -public class TestBoundedFifoBuffer extends AbstractTestCollection { +public class TestBoundedFifoBuffer extends AbstractTestCollection { public TestBoundedFifoBuffer(String n) { super(n); @@ -45,18 +45,18 @@ public class TestBoundedFifoBuffer extends AbstractTestCollection { //----------------------------------------------------------------------- /** - * Runs through the regular verifications, but also verifies that + * Runs through the regular verifications, but also verifies that * the buffer contains the same elements in the same sequence as the * list. */ public void verify() { super.verify(); - Iterator iterator1 = collection.iterator(); - Iterator iterator2 = confirmed.iterator(); + Iterator iterator1 = getCollection().iterator(); + Iterator iterator2 = getConfirmed().iterator(); while (iterator2.hasNext()) { assertTrue(iterator1.hasNext()); - Object o1 = iterator1.next(); - Object o2 = iterator2.next(); + E o1 = iterator1.next(); + E o2 = iterator2.next(); assertEquals(o1, o2); } } @@ -78,14 +78,14 @@ public class TestBoundedFifoBuffer extends AbstractTestCollection { return false; } - //----------------------------------------------------------------------- + //----------------------------------------------------------------------- /** * Returns an empty ArrayList. * * @return an empty ArrayList */ - public Collection makeConfirmedCollection() { - return new ArrayList(); + public List makeConfirmedCollection() { + return new ArrayList(); } /** @@ -93,37 +93,37 @@ public class TestBoundedFifoBuffer extends AbstractTestCollection { * * @return a full ArrayList */ - public Collection makeConfirmedFullCollection() { - Collection c = makeConfirmedCollection(); + public List makeConfirmedFullCollection() { + List c = makeConfirmedCollection(); c.addAll(java.util.Arrays.asList(getFullElements())); return c; } /** - * Returns an empty BoundedFifoBuffer that won't overflow. - * + * Returns an empty BoundedFifoBuffer that won't overflow. + * * @return an empty BoundedFifoBuffer */ - public Collection makeCollection() { - return new BoundedFifoBuffer(100); + public BoundedFifoBuffer makeObject() { + return new BoundedFifoBuffer(100); } - //----------------------------------------------------------------------- + //----------------------------------------------------------------------- /** * Tests that the removal operation actually removes the first element. */ public void testBoundedFifoBufferRemove() { resetFull(); - int size = confirmed.size(); + int size = getConfirmed().size(); for (int i = 0; i < size; i++) { - Object o1 = ((BoundedFifoBuffer)collection).remove(); - Object o2 = ((ArrayList)confirmed).remove(0); + E o1 = getCollection().remove(); + E o2 = getConfirmed().remove(0); assertEquals("Removed objects should be equal", o1, o2); verify(); } try { - ((BoundedFifoBuffer)collection).remove(); + getCollection().remove(); fail("Empty buffer should raise Underflow."); } catch (BufferUnderflowException e) { // expected @@ -135,19 +135,19 @@ public class TestBoundedFifoBuffer extends AbstractTestCollection { */ public void testConstructorException1() { try { - new BoundedFifoBuffer(0); + new BoundedFifoBuffer(0); } catch (IllegalArgumentException ex) { return; } fail(); } - + /** * Tests that the constructor correctly throws an exception. */ public void testConstructorException2() { try { - new BoundedFifoBuffer(-20); + new BoundedFifoBuffer(-20); } catch (IllegalArgumentException ex) { return; } @@ -159,7 +159,7 @@ public class TestBoundedFifoBuffer extends AbstractTestCollection { */ public void testConstructorException3() { try { - new BoundedFifoBuffer(null); + new BoundedFifoBuffer(null); } catch (NullPointerException ex) { return; } @@ -169,15 +169,16 @@ public class TestBoundedFifoBuffer extends AbstractTestCollection { public String getCompatibilityVersion() { return "3.1"; } - + // BZ 33071 -- gets start=end=1 before removal of interior element + @SuppressWarnings("unchecked") public void testShift() { - BoundedFifoBuffer fifo = new BoundedFifoBuffer(3); - fifo.add("a"); - fifo.add("b"); - fifo.add("c"); + BoundedFifoBuffer fifo = new BoundedFifoBuffer(3); + fifo.add((E) "a"); + fifo.add((E) "b"); + fifo.add((E) "c"); fifo.remove(); - fifo.add("e"); + fifo.add((E) "e"); fifo.remove("c"); } @@ -188,4 +189,19 @@ public class TestBoundedFifoBuffer extends AbstractTestCollection { // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections/data/test/BoundedFifoBuffer.fullCollection.version3.1.obj"); // } + /** + * {@inheritDoc} + */ + @Override + public BoundedFifoBuffer getCollection() { + return (BoundedFifoBuffer) super.getCollection(); + } + + /** + * {@inheritDoc} + */ + @Override + public List getConfirmed() { + return (List) super.getConfirmed(); + } } diff --git a/src/test/org/apache/commons/collections/buffer/TestBoundedFifoBuffer2.java b/src/test/org/apache/commons/collections/buffer/TestBoundedFifoBuffer2.java index 64eab2586..3e5d55b02 100644 --- a/src/test/org/apache/commons/collections/buffer/TestBoundedFifoBuffer2.java +++ b/src/test/org/apache/commons/collections/buffer/TestBoundedFifoBuffer2.java @@ -21,7 +21,6 @@ import java.util.Collection; import junit.framework.Test; -import org.apache.commons.collections.BoundedCollection; import org.apache.commons.collections.BufferOverflowException; import org.apache.commons.collections.BulkTest; @@ -33,7 +32,7 @@ import org.apache.commons.collections.BulkTest; * * @author Unknown */ -public class TestBoundedFifoBuffer2 extends TestBoundedFifoBuffer { +public class TestBoundedFifoBuffer2 extends TestBoundedFifoBuffer { public TestBoundedFifoBuffer2(String n) { super(n); @@ -50,11 +49,10 @@ public class TestBoundedFifoBuffer2 extends TestBoundedFifoBuffer { * * @return a full BoundedFifoBuffer */ - public Collection makeFullCollection() { - return new BoundedFifoBuffer(Arrays.asList(getFullElements())); + public Collection makeFullCollection() { + return new BoundedFifoBuffer(Arrays.asList(getFullElements())); } - /** * Overridden to skip the add tests. All of them would fail with a * BufferOverflowException. @@ -65,7 +63,6 @@ public class TestBoundedFifoBuffer2 extends TestBoundedFifoBuffer { return false; } - /** * Overridden because the add operations raise BufferOverflowException * instead of UnsupportedOperationException. @@ -73,14 +70,13 @@ public class TestBoundedFifoBuffer2 extends TestBoundedFifoBuffer { public void testUnsupportedAdd() { } - /** * Tests to make sure the add operations raise BufferOverflowException. */ public void testBufferOverflow() { resetFull(); try { - collection.add(getOtherElements()[0]); + getCollection().add(getOtherElements()[0]); fail("add should raise BufferOverflow."); } catch (BufferOverflowException e) { // expected @@ -88,7 +84,7 @@ public class TestBoundedFifoBuffer2 extends TestBoundedFifoBuffer { verify(); try { - collection.addAll(Arrays.asList(getOtherElements())); + getCollection().addAll(Arrays.asList(getOtherElements())); fail("addAll should raise BufferOverflow."); } catch (BufferOverflowException e) { // expected @@ -99,25 +95,27 @@ public class TestBoundedFifoBuffer2 extends TestBoundedFifoBuffer { /** * Tests is full */ + @SuppressWarnings("unchecked") public void testIsFull() { resetFull(); - assertEquals(true, ((BoundedCollection) collection).isFull()); - ((BoundedFifoBuffer) collection).remove(); - assertEquals(false, ((BoundedCollection) collection).isFull()); - ((BoundedFifoBuffer) collection).add("jj"); - assertEquals(true, ((BoundedCollection) collection).isFull()); + assertEquals(true, getCollection().isFull()); + getCollection().remove(); + assertEquals(false, getCollection().isFull()); + getCollection().add((E) "jj"); + assertEquals(true, getCollection().isFull()); } /** * Tests max size */ + @SuppressWarnings("unchecked") public void testMaxSize() { resetFull(); - assertEquals(getFullElements().length, ((BoundedCollection) collection).maxSize()); - ((BoundedFifoBuffer) collection).remove(); - assertEquals(getFullElements().length, ((BoundedCollection) collection).maxSize()); - ((BoundedFifoBuffer) collection).add("jj"); - assertEquals(getFullElements().length, ((BoundedCollection) collection).maxSize()); + assertEquals(getFullElements().length, getCollection().maxSize()); + getCollection().remove(); + assertEquals(getFullElements().length, getCollection().maxSize()); + getCollection().add((E) "jj"); + assertEquals(getFullElements().length, getCollection().maxSize()); } } diff --git a/src/test/org/apache/commons/collections/buffer/TestCircularFifoBuffer.java b/src/test/org/apache/commons/collections/buffer/TestCircularFifoBuffer.java index b2837cf0d..cf1aebd0a 100644 --- a/src/test/org/apache/commons/collections/buffer/TestCircularFifoBuffer.java +++ b/src/test/org/apache/commons/collections/buffer/TestCircularFifoBuffer.java @@ -40,7 +40,7 @@ import org.apache.commons.collections.collection.AbstractTestCollection; * * @author Stephen Colebourne */ -public class TestCircularFifoBuffer extends AbstractTestCollection { +public class TestCircularFifoBuffer extends AbstractTestCollection { public TestCircularFifoBuffer(String n) { super(n); @@ -56,14 +56,14 @@ public class TestCircularFifoBuffer extends AbstractTestCollection { //----------------------------------------------------------------------- /** - * Runs through the regular verifications, but also verifies that + * Runs through the regular verifications, but also verifies that * the buffer contains the same elements in the same sequence as the * list. */ public void verify() { super.verify(); - Iterator iterator1 = collection.iterator(); - Iterator iterator2 = confirmed.iterator(); + Iterator iterator1 = getCollection().iterator(); + Iterator iterator2 = getConfirmed().iterator(); while (iterator2.hasNext()) { assertTrue(iterator1.hasNext()); Object o1 = iterator1.next(); @@ -95,8 +95,8 @@ public class TestCircularFifoBuffer extends AbstractTestCollection { * * @return an empty ArrayList */ - public Collection makeConfirmedCollection() { - return new ArrayList(); + public Collection makeConfirmedCollection() { + return new ArrayList(); } /** @@ -104,43 +104,44 @@ public class TestCircularFifoBuffer extends AbstractTestCollection { * * @return a full ArrayList */ - public Collection makeConfirmedFullCollection() { - Collection c = makeConfirmedCollection(); + public Collection makeConfirmedFullCollection() { + Collection c = makeConfirmedCollection(); c.addAll(java.util.Arrays.asList(getFullElements())); return c; } /** - * Returns an empty BoundedFifoBuffer that won't overflow. - * + * Returns an empty BoundedFifoBuffer that won't overflow. + * * @return an empty BoundedFifoBuffer */ - public Collection makeCollection() { - return new CircularFifoBuffer(100); + public Collection makeObject() { + return new CircularFifoBuffer(100); } //----------------------------------------------------------------------- /** * Tests that the removal operation actually removes the first element. */ + @SuppressWarnings("unchecked") public void testCircularFifoBufferCircular() { - List list = new ArrayList(); - list.add("A"); - list.add("B"); - list.add("C"); - Buffer buf = new CircularFifoBuffer(list); - + List list = new ArrayList(); + list.add((E) "A"); + list.add((E) "B"); + list.add((E) "C"); + Buffer buf = new CircularFifoBuffer(list); + assertEquals(true, buf.contains("A")); assertEquals(true, buf.contains("B")); assertEquals(true, buf.contains("C")); - - buf.add("D"); - + + buf.add((E) "D"); + assertEquals(false, buf.contains("A")); assertEquals(true, buf.contains("B")); assertEquals(true, buf.contains("C")); assertEquals(true, buf.contains("D")); - + assertEquals("B", buf.get()); assertEquals("B", buf.remove()); assertEquals("C", buf.remove()); @@ -152,16 +153,16 @@ public class TestCircularFifoBuffer extends AbstractTestCollection { */ public void testCircularFifoBufferRemove() { resetFull(); - int size = confirmed.size(); + int size = getConfirmed().size(); for (int i = 0; i < size; i++) { - Object o1 = ((CircularFifoBuffer) collection).remove(); - Object o2 = ((ArrayList) confirmed).remove(0); + Object o1 = getCollection().remove(); + Object o2 = getConfirmed().remove(0); assertEquals("Removed objects should be equal", o1, o2); verify(); } try { - ((CircularFifoBuffer) collection).remove(); + getCollection().remove(); fail("Empty buffer should raise Underflow."); } catch (BufferUnderflowException e) { // expected @@ -173,7 +174,7 @@ public class TestCircularFifoBuffer extends AbstractTestCollection { */ public void testConstructorException1() { try { - new CircularFifoBuffer(0); + new CircularFifoBuffer(0); } catch (IllegalArgumentException ex) { return; } @@ -185,220 +186,230 @@ public class TestCircularFifoBuffer extends AbstractTestCollection { */ public void testConstructorException2() { try { - new CircularFifoBuffer(-20); + new CircularFifoBuffer(-20); } catch (IllegalArgumentException ex) { return; } fail(); } - + /** * Tests that the constructor correctly throws an exception. */ public void testConstructorException3() { try { - new CircularFifoBuffer(null); + new CircularFifoBuffer(null); } catch (NullPointerException ex) { return; } fail(); } - + + @SuppressWarnings("unchecked") public void testRemoveError1() throws Exception { // based on bug 33071 - CircularFifoBuffer fifo = new CircularFifoBuffer(5); - fifo.add("1"); - fifo.add("2"); - fifo.add("3"); - fifo.add("4"); - fifo.add("5"); - + CircularFifoBuffer fifo = new CircularFifoBuffer(5); + fifo.add((E) "1"); + fifo.add((E) "2"); + fifo.add((E) "3"); + fifo.add((E) "4"); + fifo.add((E) "5"); + assertEquals("[1, 2, 3, 4, 5]", fifo.toString()); - + fifo.remove("3"); assertEquals("[1, 2, 4, 5]", fifo.toString()); - + fifo.remove("4"); assertEquals("[1, 2, 5]", fifo.toString()); } + @SuppressWarnings("unchecked") public void testRemoveError2() throws Exception { // based on bug 33071 - CircularFifoBuffer fifo = new CircularFifoBuffer(5); - fifo.add("1"); - fifo.add("2"); - fifo.add("3"); - fifo.add("4"); - fifo.add("5"); - fifo.add("6"); - + CircularFifoBuffer fifo = new CircularFifoBuffer(5); + fifo.add((E) "1"); + fifo.add((E) "2"); + fifo.add((E) "3"); + fifo.add((E) "4"); + fifo.add((E) "5"); + fifo.add((E) "6"); + assertEquals(5, fifo.size()); assertEquals("[2, 3, 4, 5, 6]", fifo.toString()); - + fifo.remove("3"); assertEquals("[2, 4, 5, 6]", fifo.toString()); - + fifo.remove("4"); assertEquals("[2, 5, 6]", fifo.toString()); } + @SuppressWarnings("unchecked") public void testRemoveError3() throws Exception { // based on bug 33071 - CircularFifoBuffer fifo = new CircularFifoBuffer(5); - fifo.add("1"); - fifo.add("2"); - fifo.add("3"); - fifo.add("4"); - fifo.add("5"); - + CircularFifoBuffer fifo = new CircularFifoBuffer(5); + fifo.add((E) "1"); + fifo.add((E) "2"); + fifo.add((E) "3"); + fifo.add((E) "4"); + fifo.add((E) "5"); + assertEquals("[1, 2, 3, 4, 5]", fifo.toString()); - + fifo.remove("3"); assertEquals("[1, 2, 4, 5]", fifo.toString()); - - fifo.add("6"); - fifo.add("7"); + + fifo.add((E) "6"); + fifo.add((E) "7"); assertEquals("[2, 4, 5, 6, 7]", fifo.toString()); - + fifo.remove("4"); assertEquals("[2, 5, 6, 7]", fifo.toString()); } + @SuppressWarnings("unchecked") public void testRemoveError4() throws Exception { // based on bug 33071 - CircularFifoBuffer fifo = new CircularFifoBuffer(5); - fifo.add("1"); - fifo.add("2"); - fifo.add("3"); - fifo.add("4"); - fifo.add("5"); // end=0 - fifo.add("6"); // end=1 - fifo.add("7"); // end=2 - + CircularFifoBuffer fifo = new CircularFifoBuffer(5); + fifo.add((E) "1"); + fifo.add((E) "2"); + fifo.add((E) "3"); + fifo.add((E) "4"); + fifo.add((E) "5"); // end=0 + fifo.add((E) "6"); // end=1 + fifo.add((E) "7"); // end=2 + assertEquals("[3, 4, 5, 6, 7]", fifo.toString()); - + fifo.remove("4"); // remove element in middle of array, after start assertEquals("[3, 5, 6, 7]", fifo.toString()); } + @SuppressWarnings("unchecked") public void testRemoveError5() throws Exception { // based on bug 33071 - CircularFifoBuffer fifo = new CircularFifoBuffer(5); - fifo.add("1"); - fifo.add("2"); - fifo.add("3"); - fifo.add("4"); - fifo.add("5"); // end=0 - fifo.add("6"); // end=1 - fifo.add("7"); // end=2 - + CircularFifoBuffer fifo = new CircularFifoBuffer(5); + fifo.add((E) "1"); + fifo.add((E) "2"); + fifo.add((E) "3"); + fifo.add((E) "4"); + fifo.add((E) "5"); // end=0 + fifo.add((E) "6"); // end=1 + fifo.add((E) "7"); // end=2 + assertEquals("[3, 4, 5, 6, 7]", fifo.toString()); - + fifo.remove("5"); // remove element at last pos in array assertEquals("[3, 4, 6, 7]", fifo.toString()); } + @SuppressWarnings("unchecked") public void testRemoveError6() throws Exception { // based on bug 33071 - CircularFifoBuffer fifo = new CircularFifoBuffer(5); - fifo.add("1"); - fifo.add("2"); - fifo.add("3"); - fifo.add("4"); - fifo.add("5"); // end=0 - fifo.add("6"); // end=1 - fifo.add("7"); // end=2 - + CircularFifoBuffer fifo = new CircularFifoBuffer(5); + fifo.add((E) "1"); + fifo.add((E) "2"); + fifo.add((E) "3"); + fifo.add((E) "4"); + fifo.add((E) "5"); // end=0 + fifo.add((E) "6"); // end=1 + fifo.add((E) "7"); // end=2 + assertEquals("[3, 4, 5, 6, 7]", fifo.toString()); - + fifo.remove("6"); // remove element at position zero in array assertEquals("[3, 4, 5, 7]", fifo.toString()); } + @SuppressWarnings("unchecked") public void testRemoveError7() throws Exception { // based on bug 33071 - CircularFifoBuffer fifo = new CircularFifoBuffer(5); - fifo.add("1"); - fifo.add("2"); - fifo.add("3"); - fifo.add("4"); - fifo.add("5"); // end=0 - fifo.add("6"); // end=1 - fifo.add("7"); // end=2 - + CircularFifoBuffer fifo = new CircularFifoBuffer(5); + fifo.add((E) "1"); + fifo.add((E) "2"); + fifo.add((E) "3"); + fifo.add((E) "4"); + fifo.add((E) "5"); // end=0 + fifo.add((E) "6"); // end=1 + fifo.add((E) "7"); // end=2 + assertEquals("[3, 4, 5, 6, 7]", fifo.toString()); - + fifo.remove("7"); // remove element at position one in array assertEquals("[3, 4, 5, 6]", fifo.toString()); } + @SuppressWarnings("unchecked") public void testRemoveError8() throws Exception { // based on bug 33071 - CircularFifoBuffer fifo = new CircularFifoBuffer(5); - fifo.add("1"); - fifo.add("2"); - fifo.add("3"); - fifo.add("4"); - fifo.add("5"); // end=0 - fifo.add("6"); // end=1 - fifo.add("7"); // end=2 - fifo.add("8"); // end=3 - + CircularFifoBuffer fifo = new CircularFifoBuffer(5); + fifo.add((E) "1"); + fifo.add((E) "2"); + fifo.add((E) "3"); + fifo.add((E) "4"); + fifo.add((E) "5"); // end=0 + fifo.add((E) "6"); // end=1 + fifo.add((E) "7"); // end=2 + fifo.add((E) "8"); // end=3 + assertEquals("[4, 5, 6, 7, 8]", fifo.toString()); - + fifo.remove("7"); // remove element at position one in array, need to shift 8 assertEquals("[4, 5, 6, 8]", fifo.toString()); } + @SuppressWarnings("unchecked") public void testRemoveError9() throws Exception { // based on bug 33071 - CircularFifoBuffer fifo = new CircularFifoBuffer(5); - fifo.add("1"); - fifo.add("2"); - fifo.add("3"); - fifo.add("4"); - fifo.add("5"); // end=0 - fifo.add("6"); // end=1 - fifo.add("7"); // end=2 - fifo.add("8"); // end=3 - + CircularFifoBuffer fifo = new CircularFifoBuffer(5); + fifo.add((E) "1"); + fifo.add((E) "2"); + fifo.add((E) "3"); + fifo.add((E) "4"); + fifo.add((E) "5"); // end=0 + fifo.add((E) "6"); // end=1 + fifo.add((E) "7"); // end=2 + fifo.add((E) "8"); // end=3 + assertEquals("[4, 5, 6, 7, 8]", fifo.toString()); - + fifo.remove("8"); // remove element at position two in array assertEquals("[4, 5, 6, 7]", fifo.toString()); } //----------------------------------------------------------------------- + @SuppressWarnings("unchecked") public void testRepeatedSerialization() throws Exception { // bug 31433 - CircularFifoBuffer b = new CircularFifoBuffer(2); - b.add("a"); + CircularFifoBuffer b = new CircularFifoBuffer(2); + b.add((E) "a"); assertEquals(1, b.size()); assertEquals(true, b.contains("a")); - + ByteArrayOutputStream bos = new ByteArrayOutputStream(); new ObjectOutputStream(bos).writeObject(b); - - CircularFifoBuffer b2 = (CircularFifoBuffer) new ObjectInputStream( + + CircularFifoBuffer b2 = (CircularFifoBuffer) new ObjectInputStream( new ByteArrayInputStream(bos.toByteArray())).readObject(); - + assertEquals(1, b2.size()); assertEquals(true, b2.contains("a")); - b2.add("b"); + b2.add((E) "b"); assertEquals(2, b2.size()); assertEquals(true, b2.contains("a")); assertEquals(true, b2.contains("b")); - + bos = new ByteArrayOutputStream(); new ObjectOutputStream(bos).writeObject(b2); - - CircularFifoBuffer b3 = (CircularFifoBuffer) new ObjectInputStream( + + CircularFifoBuffer b3 = (CircularFifoBuffer) new ObjectInputStream( new ByteArrayInputStream(bos.toByteArray())).readObject(); - + assertEquals(2, b3.size()); assertEquals(true, b3.contains("a")); assertEquals(true, b3.contains("b")); - b3.add("c"); + b3.add((E) "c"); assertEquals(2, b3.size()); assertEquals(true, b3.contains("b")); assertEquals(true, b3.contains("c")); @@ -415,4 +426,19 @@ public class TestCircularFifoBuffer extends AbstractTestCollection { // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections/data/test/CircularFifoBuffer.fullCollection.version3.1.obj"); // } + /** + * {@inheritDoc} + */ + @Override + public CircularFifoBuffer getCollection() { + return (CircularFifoBuffer) super.getCollection(); + } + + /** + * {@inheritDoc} + */ + @Override + public List getConfirmed() { + return (List) super.getConfirmed(); + } } diff --git a/src/test/org/apache/commons/collections/buffer/TestPredicatedBuffer.java b/src/test/org/apache/commons/collections/buffer/TestPredicatedBuffer.java index 2c61a3eaa..322d89dc6 100644 --- a/src/test/org/apache/commons/collections/buffer/TestPredicatedBuffer.java +++ b/src/test/org/apache/commons/collections/buffer/TestPredicatedBuffer.java @@ -28,7 +28,7 @@ import org.apache.commons.collections.Predicate; import org.apache.commons.collections.collection.TestPredicatedCollection; /** - * Extension of {@link TestPredicatedCollection} for exercising the + * Extension of {@link TestPredicatedCollection} for exercising the * {@link PredicatedBuffer} implementation. * * @since Commons Collections 3.0 @@ -36,71 +36,73 @@ import org.apache.commons.collections.collection.TestPredicatedCollection; * * @author Phil Steitz */ -public class TestPredicatedBuffer extends TestPredicatedCollection { - +public class TestPredicatedBuffer extends TestPredicatedCollection { + public TestPredicatedBuffer(String testName) { super(testName); } - + public static Test suite() { return new TestSuite(TestPredicatedBuffer.class); } - + public static void main(String args[]) { String[] testCaseName = { TestPredicatedBuffer.class.getName()}; junit.textui.TestRunner.main(testCaseName); } - + //--------------------------------------------------------------- - - protected Buffer decorateBuffer(Buffer buffer, Predicate predicate) { + + protected Buffer decorateCollection(Buffer buffer, Predicate predicate) { return PredicatedBuffer.decorate(buffer, predicate); } - - public Collection makeCollection() { - return decorateBuffer(new ArrayStack(), truePredicate); + + public Buffer makeObject() { + return decorateCollection(new ArrayStack(), truePredicate); } - - public Collection makeConfirmedCollection() { - return new ArrayStack(); + + public Collection makeConfirmedCollection() { + return new ArrayStack(); } - - public Collection makeConfirmedFullCollection() { - ArrayStack list = new ArrayStack(); + + public Collection makeConfirmedFullCollection() { + ArrayStack list = new ArrayStack(); list.addAll(java.util.Arrays.asList(getFullElements())); return list; } - + //------------------------------------------------------------ - - public Buffer makeTestBuffer() { - return decorateBuffer(new ArrayStack(), testPredicate); + + public Buffer makeTestBuffer() { + return decorateCollection(new ArrayStack(), testPredicate); } - + + @SuppressWarnings("unchecked") public void testGet() { - Buffer buffer = makeTestBuffer(); + Buffer buffer = makeTestBuffer(); try { - Object o = buffer.get(); + buffer.get(); fail("Expecting BufferUnderflowException"); } catch (BufferUnderflowException ex) { // expected } - buffer.add("one"); - buffer.add("two"); - buffer.add("three"); + buffer.add((E) "one"); + buffer.add((E) "two"); + buffer.add((E) "three"); assertEquals("Buffer get", "three", buffer.get()); } - + + @SuppressWarnings("unchecked") public void testRemove() { - Buffer buffer = makeTestBuffer(); - buffer.add("one"); + Buffer buffer = makeTestBuffer(); + buffer.add((E) "one"); assertEquals("Buffer get", "one", buffer.remove()); try { buffer.remove(); fail("Expecting BufferUnderflowException"); } catch (BufferUnderflowException ex) { // expected - } + } } public String getCompatibilityVersion() { diff --git a/src/test/org/apache/commons/collections/buffer/TestPriorityBuffer.java b/src/test/org/apache/commons/collections/buffer/TestPriorityBuffer.java index 380506a88..cff46a864 100644 --- a/src/test/org/apache/commons/collections/buffer/TestPriorityBuffer.java +++ b/src/test/org/apache/commons/collections/buffer/TestPriorityBuffer.java @@ -42,7 +42,7 @@ import org.apache.commons.collections.comparators.ReverseComparator; * @author Michael A. Smith * @author Steve Phelps */ -public class TestPriorityBuffer extends AbstractTestCollection { +public class TestPriorityBuffer extends AbstractTestCollection { public static void main(String[] args) { junit.textui.TestRunner.run(suite()); @@ -56,22 +56,23 @@ public class TestPriorityBuffer extends AbstractTestCollection { super(testName); } - //----------------------------------------------------------------------- + //----------------------------------------------------------------------- + @SuppressWarnings("unchecked") public void verify() { super.verify(); - PriorityBuffer heap = (PriorityBuffer) collection; + PriorityBuffer heap = getCollection(); - Comparator c = heap.comparator; + Comparator c = heap.comparator; if (c == null) { - c = ComparatorUtils.naturalComparator(); + c = ComparatorUtils.NATURAL_COMPARATOR; } if (!heap.ascendingOrder) { c = ComparatorUtils.reversedComparator(c); } - Object[] tree = heap.elements; + E[] tree = heap.elements; for (int i = 1; i <= heap.size; i++) { - Object parent = tree[i]; + E parent = tree[i]; if (i * 2 <= heap.size) { assertTrue("Parent is less than or equal to its left child", c.compare(parent, tree[i * 2]) <= 0); } @@ -81,7 +82,7 @@ public class TestPriorityBuffer extends AbstractTestCollection { } } - //----------------------------------------------------------------------- + //----------------------------------------------------------------------- /** * Overridden because BinaryBuffer isn't fail fast. * @return false @@ -90,13 +91,13 @@ public class TestPriorityBuffer extends AbstractTestCollection { return false; } - //----------------------------------------------------------------------- - public Collection makeConfirmedCollection() { - return new ArrayList(); + //----------------------------------------------------------------------- + public Collection makeConfirmedCollection() { + return new ArrayList(); } - public Collection makeConfirmedFullCollection() { - ArrayList list = new ArrayList(); + public Collection makeConfirmedFullCollection() { + ArrayList list = new ArrayList(); list.addAll(Arrays.asList(getFullElements())); return list; } @@ -104,23 +105,25 @@ public class TestPriorityBuffer extends AbstractTestCollection { /** * Return a new, empty {@link Object} to used for testing. */ - public Collection makeCollection() { - return new PriorityBuffer(); + public Buffer makeObject() { + return new PriorityBuffer(); } - //----------------------------------------------------------------------- - public Object[] getFullElements() { - return getFullNonNullStringElements(); + //----------------------------------------------------------------------- + @SuppressWarnings("unchecked") + public E[] getFullElements() { + return (E[]) getFullNonNullStringElements(); } - public Object[] getOtherElements() { - return getOtherNonNullStringElements(); + @SuppressWarnings("unchecked") + public E[] getOtherElements() { + return (E[]) getOtherNonNullStringElements(); } - //----------------------------------------------------------------------- + //----------------------------------------------------------------------- public void testBufferEmpty() { resetEmpty(); - Buffer buffer = (Buffer) collection; + Buffer buffer = getCollection(); assertEquals(0, buffer.size()); assertEquals(true, buffer.isEmpty()); @@ -134,24 +137,24 @@ public class TestPriorityBuffer extends AbstractTestCollection { fail(); } catch (BufferUnderflowException ex) {} } - - public void testBasicOps() { - PriorityBuffer heap = new PriorityBuffer(); - heap.add("a"); - heap.add("c"); - heap.add("e"); - heap.add("b"); - heap.add("d"); - heap.add("n"); - heap.add("m"); - heap.add("l"); - heap.add("k"); - heap.add("j"); - heap.add("i"); - heap.add("h"); - heap.add("g"); - heap.add("f"); + @SuppressWarnings("unchecked") + public void testBasicOps() { + PriorityBuffer heap = new PriorityBuffer(); + heap.add((E) "a"); + heap.add((E) "c"); + heap.add((E) "e"); + heap.add((E) "b"); + heap.add((E) "d"); + heap.add((E) "n"); + heap.add((E) "m"); + heap.add((E) "l"); + heap.add((E) "k"); + heap.add((E) "j"); + heap.add((E) "i"); + heap.add((E) "h"); + heap.add((E) "g"); + heap.add((E) "f"); assertTrue("heap should not be empty after adds", !heap.isEmpty()); @@ -184,8 +187,9 @@ public class TestPriorityBuffer extends AbstractTestCollection { } catch (BufferUnderflowException ex) {} } + @SuppressWarnings("unchecked") public void testBasicComparatorOps() { - PriorityBuffer heap = new PriorityBuffer(new ReverseComparator(new ComparableComparator())); + PriorityBuffer heap = new PriorityBuffer(new ReverseComparator((Comparator) ComparableComparator.INSTANCE)); assertTrue("heap should be empty after create", heap.isEmpty()); @@ -199,20 +203,20 @@ public class TestPriorityBuffer extends AbstractTestCollection { fail("NoSuchElementException should be thrown if remove is called before any elements are added"); } catch (BufferUnderflowException ex) {} - heap.add("a"); - heap.add("c"); - heap.add("e"); - heap.add("b"); - heap.add("d"); - heap.add("n"); - heap.add("m"); - heap.add("l"); - heap.add("k"); - heap.add("j"); - heap.add("i"); - heap.add("h"); - heap.add("g"); - heap.add("f"); + heap.add((E) "a"); + heap.add((E) "c"); + heap.add((E) "e"); + heap.add((E) "b"); + heap.add((E) "d"); + heap.add((E) "n"); + heap.add((E) "m"); + heap.add((E) "l"); + heap.add((E) "k"); + heap.add((E) "j"); + heap.add((E) "i"); + heap.add((E) "h"); + heap.add((E) "g"); + heap.add((E) "f"); assertTrue("heap should not be empty after adds", !heap.isEmpty()); @@ -250,28 +254,28 @@ public class TestPriorityBuffer extends AbstractTestCollection { } /** - * Illustrates bad internal heap state reported in Bugzilla PR #235818. - */ + * Illustrates bad internal heap state reported in Bugzilla PR #235818. + */ + @SuppressWarnings("unchecked") public void testAddRemove() { resetEmpty(); - PriorityBuffer heap = (PriorityBuffer) collection; - heap.add(new Integer(0)); - heap.add(new Integer(2)); - heap.add(new Integer(4)); - heap.add(new Integer(3)); - heap.add(new Integer(8)); - heap.add(new Integer(10)); - heap.add(new Integer(12)); - heap.add(new Integer(3)); - confirmed.addAll(heap); + PriorityBuffer heap = getCollection(); + heap.add(0); + heap.add(2); + heap.add(4); + heap.add(3); + heap.add(8); + heap.add(10); + heap.add(12); + heap.add(3); + getConfirmed().addAll(heap); // System.out.println(heap); - Object obj = new Integer(10); - heap.remove(obj); - confirmed.remove(obj); + heap.remove(10); + getConfirmed().remove(10); // System.out.println(heap); verify(); } - + /** * Generate heaps staring with Integers from 0 - heapSize - 1. * Then perform random add / remove operations, checking @@ -285,29 +289,29 @@ public class TestPriorityBuffer extends AbstractTestCollection { int heapSize = 100; int operations = 20; Random randGenerator = new Random(); - PriorityBuffer h = null; - for(int i=0; i < iterations; i++) { - if (i < iterations / 2) { - h = new PriorityBuffer(true); + PriorityBuffer h = null; + for (int i = 0; i < iterations; i++) { + if (i < iterations / 2) { + h = new PriorityBuffer(true); } else { - h = new PriorityBuffer(false); + h = new PriorityBuffer(false); } - for(int r = 0; r < heapSize; r++) { - h.add( new Integer( randGenerator.nextInt(heapSize)) ); + for (int r = 0; r < heapSize; r++) { + h.add(randGenerator.nextInt(heapSize)); } - for( int r = 0; r < operations; r++ ) { + for (int r = 0; r < operations; r++) { h.remove(new Integer(r)); - h.add(new Integer(randGenerator.nextInt(heapSize))); + h.add(randGenerator.nextInt(heapSize)); } checkOrder(h); } } - + /** * Pops all elements from the heap and verifies that the elements come off * in the correct order. NOTE: this method empties the heap. */ - protected void checkOrder(PriorityBuffer h) { + protected void checkOrder(PriorityBuffer h) { Integer lastNum = null; Integer num = null; while (!h.isEmpty()) { @@ -321,17 +325,17 @@ public class TestPriorityBuffer extends AbstractTestCollection { num = null; } } - + /** * Returns a string showing the contents of the heap formatted as a tree. - * Makes no attempt at padding levels or handling wrapping. + * Makes no attempt at padding levels or handling wrapping. */ - protected String showTree(PriorityBuffer h) { + protected String showTree(PriorityBuffer h) { int count = 1; StringBuffer buffer = new StringBuffer(); for (int offset = 1; count < h.size() + 1; offset *= 2) { for (int i = offset; i < offset * 2; i++) { - if (i < h.elements.length && h.elements[i] != null) + if (i < h.elements.length && h.elements[i] != null) buffer.append(h.elements[i] + " "); count++; } @@ -344,15 +348,16 @@ public class TestPriorityBuffer extends AbstractTestCollection { * Generates 500 randomly initialized heaps of size 100 * and tests that after serializing and restoring them to a byte array * that the following conditions hold: - * - * - the size of the restored heap is the same + * + * - the size of the restored heap is the same * as the size of the orignal heap - * + * * - all elements in the original heap are present in the restored heap - * - * - the heap order of the restored heap is intact as + * + * - the heap order of the restored heap is intact as * verified by checkOrder() */ + @SuppressWarnings("unchecked") public void testSerialization() { int iterations = 500; int heapSize = 100; @@ -360,17 +365,17 @@ public class TestPriorityBuffer extends AbstractTestCollection { Random randGenerator = new Random(); for (int i = 0; i < iterations; i++) { if (i < iterations / 2) { - h = new PriorityBuffer(true); + h = new PriorityBuffer(true); } else { - h = new PriorityBuffer(false); + h = new PriorityBuffer(false); } for (int r = 0; r < heapSize; r++) { h.add(new Integer(randGenerator.nextInt(heapSize))); } assertTrue(h.size() == heapSize); - PriorityBuffer h1 = serializeAndRestore(h); + PriorityBuffer h1 = serializeAndRestore(h); assertTrue(h1.size() == heapSize); - Iterator hit = h.iterator(); + Iterator hit = h.iterator(); while (hit.hasNext()) { Integer n = (Integer) hit.next(); assertTrue(h1.contains(n)); @@ -379,11 +384,11 @@ public class TestPriorityBuffer extends AbstractTestCollection { } } - public PriorityBuffer serializeAndRestore(PriorityBuffer h) { - PriorityBuffer h1 = null; + public PriorityBuffer serializeAndRestore(PriorityBuffer h) { + PriorityBuffer h1 = null; try { byte[] objekt = writeExternalFormToBytes(h); - h1 = (PriorityBuffer) readExternalFormFromBytes(objekt); + h1 = (PriorityBuffer) readExternalFormFromBytes(objekt); } catch (IOException e) { e.printStackTrace(); fail(e.toString()); @@ -405,4 +410,11 @@ public class TestPriorityBuffer extends AbstractTestCollection { // writeExternalFormToDisk((java.io.Serializable) collection, "C:/commons/collections/data/test/PriorityBuffer.fullCollection.version3.2.obj"); // } + /** + * {@inheritDoc} + */ + @Override + public PriorityBuffer getCollection() { + return (PriorityBuffer) super.getCollection(); + } } diff --git a/src/test/org/apache/commons/collections/buffer/TestSynchronizedBuffer.java b/src/test/org/apache/commons/collections/buffer/TestSynchronizedBuffer.java index eba9d40a5..305a78846 100644 --- a/src/test/org/apache/commons/collections/buffer/TestSynchronizedBuffer.java +++ b/src/test/org/apache/commons/collections/buffer/TestSynchronizedBuffer.java @@ -27,7 +27,7 @@ import org.apache.commons.collections.Buffer; import org.apache.commons.collections.collection.AbstractTestCollection; /** - * Extension of {@link AbstractTestCollection} for exercising the + * Extension of {@link AbstractTestCollection} for exercising the * {@link SynchronizedBuffer} implementation. * * @since Commons Collections 3.1 @@ -36,39 +36,38 @@ import org.apache.commons.collections.collection.AbstractTestCollection; * @author Phil Steitz * @author Stephen Colebourne */ -public class TestSynchronizedBuffer extends AbstractTestCollection { - +public class TestSynchronizedBuffer extends AbstractTestCollection { + public TestSynchronizedBuffer(String testName) { super(testName); } - + public static Test suite() { return new TestSuite(TestSynchronizedBuffer.class); } - + public static void main(String args[]) { String[] testCaseName = { TestSynchronizedBuffer.class.getName()}; junit.textui.TestRunner.main(testCaseName); } - //----------------------------------------------------------------------- - public Collection makeCollection() { - return SynchronizedBuffer.decorate(new UnboundedFifoBuffer()); + //----------------------------------------------------------------------- + public Buffer makeObject() { + return SynchronizedBuffer.decorate(new UnboundedFifoBuffer()); } - - public Collection makeFullCollection() { - Buffer buffer = new UnboundedFifoBuffer(); + + public Collection makeFullCollection() { + Buffer buffer = new UnboundedFifoBuffer(); buffer.addAll(Arrays.asList(getFullElements())); return SynchronizedBuffer.decorate(buffer); } - - public Collection makeConfirmedCollection() { - ArrayStack list = new ArrayStack(); - return list; + + public Collection makeConfirmedCollection() { + return new ArrayStack(); } - public Collection makeConfirmedFullCollection() { - ArrayStack list = new ArrayStack(); + public Collection makeConfirmedFullCollection() { + ArrayStack list = new ArrayStack(); list.addAll(Arrays.asList(getFullElements())); return list; } @@ -76,7 +75,7 @@ public class TestSynchronizedBuffer extends AbstractTestCollection { public boolean isNullSupported() { return false; } - + public String getCompatibilityVersion() { return "3.1"; } diff --git a/src/test/org/apache/commons/collections/buffer/TestTransformedBuffer.java b/src/test/org/apache/commons/collections/buffer/TestTransformedBuffer.java index 65a961a03..44f9cad6b 100644 --- a/src/test/org/apache/commons/collections/buffer/TestTransformedBuffer.java +++ b/src/test/org/apache/commons/collections/buffer/TestTransformedBuffer.java @@ -49,9 +49,9 @@ public class TestTransformedBuffer extends TestCase { } public void testTransformedBuffer() { - Buffer buffer = TransformedBuffer.decorate(new ArrayStack(), TestTransformedCollection.STRING_TO_INTEGER_TRANSFORMER); + Buffer buffer = TransformedBuffer.decorate(new ArrayStack(), TestTransformedCollection.STRING_TO_INTEGER_TRANSFORMER); assertEquals(0, buffer.size()); - Object[] els = new Object[] {"1", "3", "5", "7", "2", "4", "6"}; + Object[] els = new Object[] { "1", "3", "5", "7", "2", "4", "6" }; for (int i = 0; i < els.length; i++) { buffer.add(els[i]); assertEquals(i + 1, buffer.size()); diff --git a/src/test/org/apache/commons/collections/buffer/TestUnboundedFifoBuffer.java b/src/test/org/apache/commons/collections/buffer/TestUnboundedFifoBuffer.java index bcfeeea43..f227014b4 100644 --- a/src/test/org/apache/commons/collections/buffer/TestUnboundedFifoBuffer.java +++ b/src/test/org/apache/commons/collections/buffer/TestUnboundedFifoBuffer.java @@ -19,6 +19,7 @@ package org.apache.commons.collections.buffer; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; +import java.util.List; import junit.framework.Test; @@ -32,7 +33,7 @@ import org.apache.commons.collections.collection.AbstractTestCollection; * * @author Unknown */ -public class TestUnboundedFifoBuffer extends AbstractTestCollection { +public class TestUnboundedFifoBuffer extends AbstractTestCollection { public TestUnboundedFifoBuffer(String n) { super(n); @@ -49,8 +50,8 @@ public class TestUnboundedFifoBuffer extends AbstractTestCollection { */ public void verify() { super.verify(); - Iterator iterator1 = collection.iterator(); - Iterator iterator2 = confirmed.iterator(); + Iterator iterator1 = getCollection().iterator(); + Iterator iterator2 = getConfirmed().iterator(); while (iterator2.hasNext()) { assertTrue(iterator1.hasNext()); Object o1 = iterator1.next(); @@ -82,8 +83,8 @@ public class TestUnboundedFifoBuffer extends AbstractTestCollection { * * @return an empty ArrayList */ - public Collection makeConfirmedCollection() { - return new ArrayList(); + public Collection makeConfirmedCollection() { + return new ArrayList(); } /** @@ -91,8 +92,8 @@ public class TestUnboundedFifoBuffer extends AbstractTestCollection { * * @return a full ArrayList */ - public Collection makeConfirmedFullCollection() { - Collection c = makeConfirmedCollection(); + public Collection makeConfirmedFullCollection() { + Collection c = makeConfirmedCollection(); c.addAll(java.util.Arrays.asList(getFullElements())); return c; } @@ -102,8 +103,8 @@ public class TestUnboundedFifoBuffer extends AbstractTestCollection { * * @return an empty UnboundedFifoBuffer */ - public Collection makeCollection() { - return new UnboundedFifoBuffer(5); + public Collection makeObject() { + return new UnboundedFifoBuffer(5); } //----------------------------------------------------------------------- @@ -112,10 +113,10 @@ public class TestUnboundedFifoBuffer extends AbstractTestCollection { */ public void testUnboundedFifoBufferRemove() { resetFull(); - int size = confirmed.size(); + int size = getConfirmed().size(); for (int i = 0; i < size; i++) { - Object o1 = ((UnboundedFifoBuffer)collection).remove(); - Object o2 = ((ArrayList)confirmed).remove(0); + E o1 = getCollection().remove(); + E o2 = getConfirmed().remove(0); assertEquals("Removed objects should be equal", o1, o2); verify(); } @@ -126,7 +127,7 @@ public class TestUnboundedFifoBuffer extends AbstractTestCollection { */ public void testConstructorException1() { try { - new UnboundedFifoBuffer(0); + new UnboundedFifoBuffer(0); } catch (IllegalArgumentException ex) { return; } @@ -138,7 +139,7 @@ public class TestUnboundedFifoBuffer extends AbstractTestCollection { */ public void testConstructorException2() { try { - new UnboundedFifoBuffer(-20); + new UnboundedFifoBuffer(-20); } catch (IllegalArgumentException ex) { return; } @@ -146,43 +147,45 @@ public class TestUnboundedFifoBuffer extends AbstractTestCollection { } //----------------------------------------------------------------------- + @SuppressWarnings("unchecked") public void testInternalStateAdd() { - UnboundedFifoBuffer test = new UnboundedFifoBuffer(2); + UnboundedFifoBuffer test = new UnboundedFifoBuffer(2); assertEquals(3, test.buffer.length); assertEquals(0, test.head); assertEquals(0, test.tail); - test.add("A"); + test.add((E) "A"); assertEquals(3, test.buffer.length); assertEquals(0, test.head); assertEquals(1, test.tail); - test.add("B"); + test.add((E) "B"); assertEquals(3, test.buffer.length); assertEquals(0, test.head); assertEquals(2, test.tail); - test.add("C"); // forces buffer increase + test.add((E) "C"); // forces buffer increase assertEquals(5, test.buffer.length); assertEquals(0, test.head); assertEquals(3, test.tail); - test.add("D"); + test.add((E) "D"); assertEquals(5, test.buffer.length); assertEquals(0, test.head); assertEquals(4, test.tail); } + @SuppressWarnings("unchecked") public void testInternalStateAddWithWrap() { - UnboundedFifoBuffer test = new UnboundedFifoBuffer(3); + UnboundedFifoBuffer test = new UnboundedFifoBuffer(3); assertEquals(4, test.buffer.length); assertEquals(0, test.head); assertEquals(0, test.tail); - test.add("A"); + test.add((E) "A"); assertEquals(4, test.buffer.length); assertEquals(0, test.head); assertEquals(1, test.tail); - test.add("B"); + test.add((E) "B"); assertEquals(4, test.buffer.length); assertEquals(0, test.head); assertEquals(2, test.tail); - test.add("C"); + test.add((E) "C"); assertEquals(4, test.buffer.length); assertEquals(0, test.head); assertEquals(3, test.tail); @@ -194,21 +197,22 @@ public class TestUnboundedFifoBuffer extends AbstractTestCollection { assertEquals(4, test.buffer.length); assertEquals(2, test.head); assertEquals(3, test.tail); - test.add("D"); + test.add((E) "D"); assertEquals(4, test.buffer.length); assertEquals(2, test.head); assertEquals(0, test.tail); - test.add("E"); + test.add((E) "E"); assertEquals(4, test.buffer.length); assertEquals(2, test.head); assertEquals(1, test.tail); } + @SuppressWarnings("unchecked") public void testInternalStateRemove1() { - UnboundedFifoBuffer test = new UnboundedFifoBuffer(4); - test.add("A"); - test.add("B"); - test.add("C"); + UnboundedFifoBuffer test = new UnboundedFifoBuffer(4); + test.add((E) "A"); + test.add((E) "B"); + test.add((E) "C"); assertEquals(5, test.buffer.length); assertEquals(0, test.head); assertEquals(3, test.tail); @@ -218,17 +222,18 @@ public class TestUnboundedFifoBuffer extends AbstractTestCollection { assertEquals(1, test.head); assertEquals(3, test.tail); - test.add("D"); + test.add((E) "D"); assertEquals(5, test.buffer.length); assertEquals(1, test.head); assertEquals(4, test.tail); } + @SuppressWarnings("unchecked") public void testInternalStateRemove2() { - UnboundedFifoBuffer test = new UnboundedFifoBuffer(4); - test.add("A"); - test.add("B"); - test.add("C"); + UnboundedFifoBuffer test = new UnboundedFifoBuffer(4); + test.add((E) "A"); + test.add((E) "B"); + test.add((E) "C"); assertEquals(5, test.buffer.length); assertEquals(0, test.head); assertEquals(3, test.tail); @@ -238,41 +243,43 @@ public class TestUnboundedFifoBuffer extends AbstractTestCollection { assertEquals(0, test.head); assertEquals(2, test.tail); - test.add("D"); + test.add((E) "D"); assertEquals(5, test.buffer.length); assertEquals(0, test.head); assertEquals(3, test.tail); } + @SuppressWarnings("unchecked") public void testInternalStateIteratorRemove1() { - UnboundedFifoBuffer test = new UnboundedFifoBuffer(4); - test.add("A"); - test.add("B"); - test.add("C"); + UnboundedFifoBuffer test = new UnboundedFifoBuffer(4); + test.add((E) "A"); + test.add((E) "B"); + test.add((E) "C"); assertEquals(5, test.buffer.length); assertEquals(0, test.head); assertEquals(3, test.tail); - Iterator it = test.iterator(); + Iterator it = test.iterator(); it.next(); it.remove(); assertEquals(5, test.buffer.length); assertEquals(1, test.head); assertEquals(3, test.tail); - test.add("D"); + test.add((E) "D"); assertEquals(5, test.buffer.length); assertEquals(1, test.head); assertEquals(4, test.tail); } + @SuppressWarnings("unchecked") public void testInternalStateIteratorRemove2() { - UnboundedFifoBuffer test = new UnboundedFifoBuffer(4); - test.add("A"); - test.add("B"); - test.add("C"); + UnboundedFifoBuffer test = new UnboundedFifoBuffer(4); + test.add((E) "A"); + test.add((E) "B"); + test.add((E) "C"); - Iterator it = test.iterator(); + Iterator it = test.iterator(); it.next(); it.next(); it.remove(); @@ -280,24 +287,25 @@ public class TestUnboundedFifoBuffer extends AbstractTestCollection { assertEquals(0, test.head); assertEquals(2, test.tail); - test.add("D"); + test.add((E) "D"); assertEquals(5, test.buffer.length); assertEquals(0, test.head); assertEquals(3, test.tail); } + @SuppressWarnings("unchecked") public void testInternalStateIteratorRemoveWithTailAtEnd1() { - UnboundedFifoBuffer test = new UnboundedFifoBuffer(3); - test.add("A"); - test.add("B"); - test.add("C"); + UnboundedFifoBuffer test = new UnboundedFifoBuffer(3); + test.add((E) "A"); + test.add((E) "B"); + test.add((E) "C"); test.remove("A"); - test.add("D"); + test.add((E) "D"); assertEquals(4, test.buffer.length); assertEquals(1, test.head); assertEquals(0, test.tail); - Iterator it = test.iterator(); + Iterator it = test.iterator(); assertEquals("B", it.next()); it.remove(); assertEquals(4, test.buffer.length); @@ -305,18 +313,19 @@ public class TestUnboundedFifoBuffer extends AbstractTestCollection { assertEquals(0, test.tail); } + @SuppressWarnings("unchecked") public void testInternalStateIteratorRemoveWithTailAtEnd2() { - UnboundedFifoBuffer test = new UnboundedFifoBuffer(3); - test.add("A"); - test.add("B"); - test.add("C"); + UnboundedFifoBuffer test = new UnboundedFifoBuffer(3); + test.add((E) "A"); + test.add((E) "B"); + test.add((E) "C"); test.remove("A"); - test.add("D"); + test.add((E) "D"); assertEquals(4, test.buffer.length); assertEquals(1, test.head); assertEquals(0, test.tail); - Iterator it = test.iterator(); + Iterator it = test.iterator(); assertEquals("B", it.next()); assertEquals("C", it.next()); it.remove(); @@ -325,18 +334,19 @@ public class TestUnboundedFifoBuffer extends AbstractTestCollection { assertEquals(3, test.tail); } + @SuppressWarnings("unchecked") public void testInternalStateIteratorRemoveWithTailAtEnd3() { - UnboundedFifoBuffer test = new UnboundedFifoBuffer(3); - test.add("A"); - test.add("B"); - test.add("C"); + UnboundedFifoBuffer test = new UnboundedFifoBuffer(3); + test.add((E) "A"); + test.add((E) "B"); + test.add((E) "C"); test.remove("A"); - test.add("D"); + test.add((E) "D"); assertEquals(4, test.buffer.length); assertEquals(1, test.head); assertEquals(0, test.tail); - Iterator it = test.iterator(); + Iterator it = test.iterator(); assertEquals("B", it.next()); assertEquals("C", it.next()); assertEquals("D", it.next()); @@ -346,20 +356,21 @@ public class TestUnboundedFifoBuffer extends AbstractTestCollection { assertEquals(3, test.tail); } + @SuppressWarnings("unchecked") public void testInternalStateIteratorRemoveWithWrap1() { - UnboundedFifoBuffer test = new UnboundedFifoBuffer(3); - test.add("A"); - test.add("B"); - test.add("C"); + UnboundedFifoBuffer test = new UnboundedFifoBuffer(3); + test.add((E) "A"); + test.add((E) "B"); + test.add((E) "C"); test.remove("A"); test.remove("B"); - test.add("D"); - test.add("E"); + test.add((E) "D"); + test.add((E) "E"); assertEquals(4, test.buffer.length); assertEquals(2, test.head); assertEquals(1, test.tail); - Iterator it = test.iterator(); + Iterator it = test.iterator(); assertEquals("C", it.next()); it.remove(); assertEquals(4, test.buffer.length); @@ -367,20 +378,21 @@ public class TestUnboundedFifoBuffer extends AbstractTestCollection { assertEquals(1, test.tail); } + @SuppressWarnings("unchecked") public void testInternalStateIteratorRemoveWithWrap2() { - UnboundedFifoBuffer test = new UnboundedFifoBuffer(3); - test.add("A"); - test.add("B"); - test.add("C"); + UnboundedFifoBuffer test = new UnboundedFifoBuffer(3); + test.add((E) "A"); + test.add((E) "B"); + test.add((E) "C"); test.remove("A"); test.remove("B"); - test.add("D"); - test.add("E"); + test.add((E) "D"); + test.add((E) "E"); assertEquals(4, test.buffer.length); assertEquals(2, test.head); assertEquals(1, test.tail); - Iterator it = test.iterator(); + Iterator it = test.iterator(); assertEquals("C", it.next()); assertEquals("D", it.next()); it.remove(); @@ -389,20 +401,21 @@ public class TestUnboundedFifoBuffer extends AbstractTestCollection { assertEquals(0, test.tail); } + @SuppressWarnings("unchecked") public void testInternalStateIteratorRemoveWithWrap3() { - UnboundedFifoBuffer test = new UnboundedFifoBuffer(3); - test.add("A"); - test.add("B"); - test.add("C"); + UnboundedFifoBuffer test = new UnboundedFifoBuffer(3); + test.add((E) "A"); + test.add((E) "B"); + test.add((E) "C"); test.remove("A"); test.remove("B"); - test.add("D"); - test.add("E"); + test.add((E) "D"); + test.add((E) "E"); assertEquals(4, test.buffer.length); assertEquals(2, test.head); assertEquals(1, test.tail); - Iterator it = test.iterator(); + Iterator it = test.iterator(); assertEquals("C", it.next()); assertEquals("D", it.next()); assertEquals("E", it.next()); @@ -435,4 +448,19 @@ public class TestUnboundedFifoBuffer extends AbstractTestCollection { // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections/data/test/UnboundedFifoBuffer.fullCollection.version3.1.obj"); // } + /** + * {@inheritDoc} + */ + @Override + public UnboundedFifoBuffer getCollection() { + return (UnboundedFifoBuffer) super.getCollection(); + } + + /** + * {@inheritDoc} + */ + @Override + public List getConfirmed() { + return (List) super.getConfirmed(); + } } diff --git a/src/test/org/apache/commons/collections/buffer/TestUnmodifiableBuffer.java b/src/test/org/apache/commons/collections/buffer/TestUnmodifiableBuffer.java index 6a9773845..538dc8a72 100644 --- a/src/test/org/apache/commons/collections/buffer/TestUnmodifiableBuffer.java +++ b/src/test/org/apache/commons/collections/buffer/TestUnmodifiableBuffer.java @@ -27,7 +27,7 @@ import org.apache.commons.collections.Buffer; import org.apache.commons.collections.collection.AbstractTestCollection; /** - * Extension of {@link AbstractTestCollection} for exercising the + * Extension of {@link AbstractTestCollection} for exercising the * {@link UnmodifiableBuffer} implementation. * * @since Commons Collections 3.1 @@ -36,39 +36,38 @@ import org.apache.commons.collections.collection.AbstractTestCollection; * @author Phil Steitz * @author Stephen Colebourne */ -public class TestUnmodifiableBuffer extends AbstractTestCollection { - +public class TestUnmodifiableBuffer extends AbstractTestCollection { + public TestUnmodifiableBuffer(String testName) { super(testName); } - + public static Test suite() { return new TestSuite(TestUnmodifiableBuffer.class); } - + public static void main(String args[]) { String[] testCaseName = { TestUnmodifiableBuffer.class.getName()}; junit.textui.TestRunner.main(testCaseName); } - //----------------------------------------------------------------------- - public Collection makeCollection() { - return UnmodifiableBuffer.decorate(new UnboundedFifoBuffer()); + //----------------------------------------------------------------------- + public Collection makeObject() { + return UnmodifiableBuffer.decorate(new UnboundedFifoBuffer()); } - - public Collection makeFullCollection() { - Buffer buffer = new UnboundedFifoBuffer(); + + public Collection makeFullCollection() { + Buffer buffer = new UnboundedFifoBuffer(); buffer.addAll(Arrays.asList(getFullElements())); return UnmodifiableBuffer.decorate(buffer); } - - public Collection makeConfirmedCollection() { - ArrayStack list = new ArrayStack(); - return list; + + public Collection makeConfirmedCollection() { + return new ArrayStack(); } - public Collection makeConfirmedFullCollection() { - ArrayStack list = new ArrayStack(); + public Collection makeConfirmedFullCollection() { + ArrayStack list = new ArrayStack(); list.addAll(Arrays.asList(getFullElements())); return list; } @@ -76,20 +75,19 @@ public class TestUnmodifiableBuffer extends AbstractTestCollection { public boolean isAddSupported() { return false; } - + public boolean isRemoveSupported() { return false; } - + public boolean isNullSupported() { return false; } - + public void testBufferRemove() { resetEmpty(); - Buffer buffer = (Buffer) collection; try { - buffer.remove(); + getCollection().remove(); fail(); } catch (UnsupportedOperationException ex) {} } @@ -105,4 +103,11 @@ public class TestUnmodifiableBuffer extends AbstractTestCollection { // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections/data/test/UnmodifiableBuffer.fullCollection.version3.1.obj"); // } + /** + * {@inheritDoc} + */ + @Override + public Buffer getCollection() { + return (Buffer) super.getCollection(); + } } diff --git a/src/test/org/apache/commons/collections/comparators/TestBooleanComparator.java b/src/test/org/apache/commons/collections/comparators/TestBooleanComparator.java index 99824c132..28eac9282 100644 --- a/src/test/org/apache/commons/collections/comparators/TestBooleanComparator.java +++ b/src/test/org/apache/commons/collections/comparators/TestBooleanComparator.java @@ -30,7 +30,7 @@ import junit.framework.TestSuite; * * @author Rodney Waldhoff */ -public class TestBooleanComparator extends AbstractTestComparator { +public class TestBooleanComparator extends AbstractTestComparator { // conventional // ------------------------------------------------------------------------ @@ -46,21 +46,21 @@ public class TestBooleanComparator extends AbstractTestComparator { // collections testing framework // ------------------------------------------------------------------------ - public Comparator makeComparator() { + public Comparator makeObject() { return new BooleanComparator(); } - public List getComparableObjectsOrdered() { - List list = new ArrayList(); + public List getComparableObjectsOrdered() { + List list = new ArrayList(); list.add(new Boolean(false)); list.add(Boolean.FALSE); list.add(new Boolean(false)); list.add(Boolean.TRUE); list.add(new Boolean(true)); - list.add(Boolean.TRUE); + list.add(true); return list; } - + public String getCompatibilityVersion() { return "3"; } @@ -71,16 +71,16 @@ public class TestBooleanComparator extends AbstractTestComparator { public void testConstructors() { allTests(false,new BooleanComparator()); allTests(false,new BooleanComparator(false)); - allTests(true,new BooleanComparator(true)); + allTests(true,new BooleanComparator(true)); } - + public void testStaticFactoryMethods() { allTests(false,BooleanComparator.getFalseFirstComparator()); allTests(false,BooleanComparator.getBooleanComparator(false)); allTests(true,BooleanComparator.getTrueFirstComparator()); allTests(true,BooleanComparator.getBooleanComparator(true)); } - + public void testEqualsCompatibleInstance() { assertEquals(new BooleanComparator(),new BooleanComparator(false)); assertEquals(new BooleanComparator(false),new BooleanComparator(false)); @@ -94,7 +94,7 @@ public class TestBooleanComparator extends AbstractTestComparator { assertTrue(!(new BooleanComparator().equals(new BooleanComparator(true)))); assertTrue(!(new BooleanComparator(true).equals(new BooleanComparator(false)))); } - + // utilities // ------------------------------------------------------------------------ @@ -109,36 +109,24 @@ public class TestBooleanComparator extends AbstractTestComparator { protected void trueFirstTests(BooleanComparator comp) { assertNotNull(comp); - assertEquals(0,comp.compare(Boolean.TRUE,Boolean.TRUE)); - assertEquals(0,comp.compare(Boolean.FALSE,Boolean.FALSE)); - assertTrue(comp.compare(Boolean.FALSE,Boolean.TRUE) > 0); - assertTrue(comp.compare(Boolean.TRUE,Boolean.FALSE) < 0); - - assertEquals(0,comp.compare((Object)(Boolean.TRUE),(Object)(Boolean.TRUE))); - assertEquals(0,comp.compare((Object)(Boolean.FALSE),(Object)(Boolean.FALSE))); - assertTrue(comp.compare((Object)(Boolean.FALSE),(Object)(Boolean.TRUE)) > 0); - assertTrue(comp.compare((Object)(Boolean.TRUE),(Object)(Boolean.FALSE)) < 0); + assertEquals(0,comp.compare(true, true)); + assertEquals(0,comp.compare(false, false)); + assertTrue(comp.compare(false, true) > 0); + assertTrue(comp.compare(true, false) < 0); } protected void falseFirstTests(BooleanComparator comp) { assertNotNull(comp); - assertEquals(0,comp.compare(Boolean.TRUE,Boolean.TRUE)); - assertEquals(0,comp.compare(Boolean.FALSE,Boolean.FALSE)); - assertTrue(comp.compare(Boolean.FALSE,Boolean.TRUE) < 0); - assertTrue(comp.compare(Boolean.TRUE,Boolean.FALSE) > 0); - - assertEquals(0,comp.compare((Object)(Boolean.TRUE),(Object)(Boolean.TRUE))); - assertEquals(0,comp.compare((Object)(Boolean.FALSE),(Object)(Boolean.FALSE))); - assertTrue(comp.compare((Object)(Boolean.FALSE),(Object)(Boolean.TRUE)) < 0); - assertTrue(comp.compare((Object)(Boolean.TRUE),(Object)(Boolean.FALSE)) > 0); + assertEquals(0,comp.compare(true, true)); + assertEquals(0,comp.compare(false, false)); + assertTrue(comp.compare(false, true) < 0); + assertTrue(comp.compare(true, false) > 0); } protected void orderIndependentTests(BooleanComparator comp) { nullArgumentTests(comp); - nonBooleanArgumentTests(comp); - nullAndNonBooleanArgumentsTests(comp); } - + protected void nullArgumentTests(BooleanComparator comp) { assertNotNull(comp); try { @@ -172,59 +160,5 @@ public class TestBooleanComparator extends AbstractTestComparator { // expected } } - - protected void nonBooleanArgumentTests(BooleanComparator comp) { - assertNotNull(comp); - try { - comp.compare("string","string"); - fail("Expected ClassCastException"); - } catch(ClassCastException e) { - // expected - } - try { - comp.compare(Boolean.TRUE,"string"); - fail("Expected ClassCastException"); - } catch(ClassCastException e) { - // expected - } - try { - comp.compare("string",Boolean.TRUE); - fail("Expected ClassCastException"); - } catch(ClassCastException e) { - // expected - } - try { - comp.compare("string",new Integer(3)); - fail("Expected ClassCastException"); - } catch(ClassCastException e) { - // expected - } - try { - comp.compare(new Integer(3),"string"); - fail("Expected ClassCastException"); - } catch(ClassCastException e) { - // expected - } - } - - protected void nullAndNonBooleanArgumentsTests(BooleanComparator comp) { - assertNotNull(comp); - try { - comp.compare(null,"string"); - fail("Expected ClassCast or NullPointer Exception"); - } catch(ClassCastException e) { - // expected - } catch(NullPointerException e) { - // expected - } - try { - comp.compare("string",null); - fail("Expected ClassCast or NullPointer Exception"); - } catch(ClassCastException e) { - // expected - } catch(NullPointerException e) { - // expected - } - } } diff --git a/src/test/org/apache/commons/collections/comparators/TestComparableComparator.java b/src/test/org/apache/commons/collections/comparators/TestComparableComparator.java index 27e0ad7d3..6b199c574 100644 --- a/src/test/org/apache/commons/collections/comparators/TestComparableComparator.java +++ b/src/test/org/apache/commons/collections/comparators/TestComparableComparator.java @@ -30,7 +30,7 @@ import junit.framework.TestSuite; * * @author Unknown */ -public class TestComparableComparator extends AbstractTestComparator { +public class TestComparableComparator extends AbstractTestComparator { public TestComparableComparator(String testName) { super(testName); @@ -40,17 +40,17 @@ public class TestComparableComparator extends AbstractTestComparator { return new TestSuite(TestComparableComparator.class); } - public Comparator makeComparator() { - return new ComparableComparator(); + public Comparator makeObject() { + return new ComparableComparator(); } - public List getComparableObjectsOrdered() { - List list = new LinkedList(); - list.add(new Integer(1)); - list.add(new Integer(2)); - list.add(new Integer(3)); - list.add(new Integer(4)); - list.add(new Integer(5)); + public List getComparableObjectsOrdered() { + List list = new LinkedList(); + list.add(1); + list.add(2); + list.add(3); + list.add(4); + list.add(5); return list; } diff --git a/src/test/org/apache/commons/collections/comparators/TestComparatorChain.java b/src/test/org/apache/commons/collections/comparators/TestComparatorChain.java index 4e735ddfb..1be2041e0 100644 --- a/src/test/org/apache/commons/collections/comparators/TestComparatorChain.java +++ b/src/test/org/apache/commons/collections/comparators/TestComparatorChain.java @@ -31,7 +31,7 @@ import junit.framework.TestSuite; * * @author Unknown */ -public class TestComparatorChain extends AbstractTestComparator { +public class TestComparatorChain extends AbstractTestComparator { public TestComparatorChain(String testName) { super(testName); @@ -41,97 +41,94 @@ public class TestComparatorChain extends AbstractTestComparator { return new TestSuite(TestComparatorChain.class); } - public Comparator makeComparator() { - ComparatorChain chain = new ComparatorChain(new ColumnComparator(0)); - chain.addComparator(new ColumnComparator(1),true); // reverse the second column - chain.addComparator(new ColumnComparator(2),false); + public Comparator makeObject() { + ComparatorChain chain = new ComparatorChain(new ColumnComparator(0)); + chain.addComparator(new ColumnComparator(1), true); // reverse the second column + chain.addComparator(new ColumnComparator(2), false); return chain; } public void testNoopComparatorChain() { - ComparatorChain chain = new ComparatorChain(); + ComparatorChain chain = new ComparatorChain(); Integer i1 = new Integer(4); Integer i2 = new Integer(6); - chain.addComparator(new ComparableComparator()); + chain.addComparator(new ComparableComparator()); int correctValue = i1.compareTo(i2); - assertTrue("Comparison returns the right order",chain.compare(i1,i2) == correctValue); + assertTrue("Comparison returns the right order", chain.compare(i1, i2) == correctValue); } public void testBadNoopComparatorChain() { - ComparatorChain chain = new ComparatorChain(); + ComparatorChain chain = new ComparatorChain(); Integer i1 = new Integer(4); Integer i2 = new Integer(6); try { chain.compare(i1,i2); fail("An exception should be thrown when a chain contains zero comparators."); } catch (UnsupportedOperationException e) { - } } public void testListComparatorChain() { - List list = new LinkedList(); - list.add(new ComparableComparator()); - ComparatorChain chain = new ComparatorChain(list); + List> list = new LinkedList>(); + list.add(new ComparableComparator()); + ComparatorChain chain = new ComparatorChain(list); Integer i1 = new Integer(4); Integer i2 = new Integer(6); int correctValue = i1.compareTo(i2); - assertTrue("Comparison returns the right order",chain.compare(i1,i2) == correctValue); + assertTrue("Comparison returns the right order", chain.compare(i1, i2) == correctValue); } public void testBadListComparatorChain() { - List list = new LinkedList(); - ComparatorChain chain = new ComparatorChain(list); + List> list = new LinkedList>(); + ComparatorChain chain = new ComparatorChain(list); Integer i1 = new Integer(4); Integer i2 = new Integer(6); try { - chain.compare(i1,i2); + chain.compare(i1, i2); fail("An exception should be thrown when a chain contains zero comparators."); } catch (UnsupportedOperationException e) { - } } - public void testComparatorChainOnMinvaluedCompatator() { // -1 * Integer.MIN_VALUE is less than 0, // test that ComparatorChain handles this edge case correctly - ComparatorChain chain = new ComparatorChain(); - chain.addComparator( - new Comparator() { - public int compare(Object a, Object b) { - int result = ((Comparable)a).compareTo(b); - if(result < 0) { - return Integer.MIN_VALUE; - } else if(result > 0) { - return Integer.MAX_VALUE; - } else { - return 0; - } + ComparatorChain chain = new ComparatorChain(); + chain.addComparator(new Comparator() { + public int compare(Integer a, Integer b) { + int result = a.compareTo(b); + if (result < 0) { + return Integer.MIN_VALUE; } - }, true); + if (result > 0) { + return Integer.MAX_VALUE; + } + return 0; + } + }, true); - assertTrue(chain.compare(new Integer(4), new Integer(5)) > 0); - assertTrue(chain.compare(new Integer(5), new Integer(4)) < 0); - assertTrue(chain.compare(new Integer(4), new Integer(4)) == 0); + assertTrue(chain.compare(new Integer(4), new Integer(5)) > 0); + assertTrue(chain.compare(new Integer(5), new Integer(4)) < 0); + assertTrue(chain.compare(new Integer(4), new Integer(4)) == 0); } - public List getComparableObjectsOrdered() { - List list = new LinkedList(); + public List getComparableObjectsOrdered() { + List list = new LinkedList(); // this is the correct order assuming a // "0th forward, 1st reverse, 2nd forward" sort - list.add(new PseudoRow(1,2,3)); - list.add(new PseudoRow(2,3,5)); - list.add(new PseudoRow(2,2,4)); - list.add(new PseudoRow(2,2,8)); - list.add(new PseudoRow(3,1,0)); - list.add(new PseudoRow(4,4,4)); - list.add(new PseudoRow(4,4,7)); + list.add(new PseudoRow(1, 2, 3)); + list.add(new PseudoRow(2, 3, 5)); + list.add(new PseudoRow(2, 2, 4)); + list.add(new PseudoRow(2, 2, 8)); + list.add(new PseudoRow(3, 1, 0)); + list.add(new PseudoRow(4, 4, 4)); + list.add(new PseudoRow(4, 4, 7)); return list; } + @SuppressWarnings("serial") public static class PseudoRow implements Serializable { public int cols[] = new int[3]; @@ -170,8 +167,8 @@ public class TestComparatorChain extends AbstractTestComparator { if (getColumn(1) != row.getColumn(1)) { return false; - } - + } + if (getColumn(2) != row.getColumn(2)) { return false; } @@ -181,7 +178,8 @@ public class TestComparatorChain extends AbstractTestComparator { } - public static class ColumnComparator implements Comparator,Serializable { + public static class ColumnComparator implements Comparator, Serializable { + private static final long serialVersionUID = -2284880866328872105L; protected int colIndex = 0; @@ -189,32 +187,26 @@ public class TestComparatorChain extends AbstractTestComparator { this.colIndex = colIndex; } - public int compare(Object o1, Object o2) { + public int compare(PseudoRow o1, PseudoRow o2) { - int col1 = ( (PseudoRow) o1).getColumn(colIndex); - int col2 = ( (PseudoRow) o2).getColumn(colIndex); + int col1 = o1.getColumn(colIndex); + int col2 = o2.getColumn(colIndex); if (col1 > col2) { return 1; - } else if (col1 < col2) { + } + if (col1 < col2) { return -1; } - return 0; } - + public int hashCode() { return colIndex; } - + public boolean equals(Object that) { - if(that instanceof ColumnComparator) { - return colIndex == ((ColumnComparator)that).colIndex; - } else { - return false; - } + return that instanceof ColumnComparator && colIndex == ((ColumnComparator) that).colIndex; } - - private static final long serialVersionUID = -2284880866328872105L; } } diff --git a/src/test/org/apache/commons/collections/comparators/TestFixedOrderComparator.java b/src/test/org/apache/commons/collections/comparators/TestFixedOrderComparator.java index b7c9563d3..78533bd7b 100644 --- a/src/test/org/apache/commons/collections/comparators/TestFixedOrderComparator.java +++ b/src/test/org/apache/commons/collections/comparators/TestFixedOrderComparator.java @@ -31,12 +31,11 @@ import junit.framework.TestSuite; * * @version $Revision$ $Date$ * - * @author David Leppik + * @author David Leppik * @author Stephen Colebourne */ public class TestFixedOrderComparator extends TestCase { - /** * Top cities of the world, by population including metro areas. */ @@ -65,7 +64,7 @@ public class TestFixedOrderComparator extends TestCase { return new TestSuite(TestFixedOrderComparator.class); } - public static void main(String args[]) { + public static void main(String args[]) { junit.textui.TestRunner.run(suite()); } @@ -79,11 +78,11 @@ public class TestFixedOrderComparator extends TestCase { // The tests // - /** - * Tests that the constructor plus add method compares items properly. + /** + * Tests that the constructor plus add method compares items properly. */ public void testConstructorPlusAdd() { - FixedOrderComparator comparator = new FixedOrderComparator(); + FixedOrderComparator comparator = new FixedOrderComparator(); for (int i = 0; i < topCities.length; i++) { comparator.add(topCities[i]); } @@ -91,13 +90,13 @@ public class TestFixedOrderComparator extends TestCase { assertComparatorYieldsOrder(keys, comparator); } - /** - * Tests that the array constructor compares items properly. + /** + * Tests that the array constructor compares items properly. */ public void testArrayConstructor() { String[] keys = (String[]) topCities.clone(); String[] topCitiesForTest = (String[]) topCities.clone(); - FixedOrderComparator comparator = new FixedOrderComparator(topCitiesForTest); + FixedOrderComparator comparator = new FixedOrderComparator(topCitiesForTest); assertComparatorYieldsOrder(keys, comparator); // test that changing input after constructor has no effect topCitiesForTest[0] = "Brighton"; @@ -105,12 +104,12 @@ public class TestFixedOrderComparator extends TestCase { } /** - * Tests the list constructor. + * Tests the list constructor. */ public void testListConstructor() { String[] keys = (String[]) topCities.clone(); - List topCitiesForTest = new LinkedList(Arrays.asList(topCities)); - FixedOrderComparator comparator = new FixedOrderComparator(topCitiesForTest); + List topCitiesForTest = new LinkedList(Arrays.asList(topCities)); + FixedOrderComparator comparator = new FixedOrderComparator(topCitiesForTest); assertComparatorYieldsOrder(keys, comparator); // test that changing input after constructor has no effect topCitiesForTest.set(0, "Brighton"); @@ -121,18 +120,18 @@ public class TestFixedOrderComparator extends TestCase { * Tests addAsEqual method. */ public void testAddAsEqual() { - FixedOrderComparator comparator = new FixedOrderComparator(topCities); + FixedOrderComparator comparator = new FixedOrderComparator(topCities); comparator.addAsEqual("New York", "Minneapolis"); assertEquals(0, comparator.compare("New York", "Minneapolis")); assertEquals(-1, comparator.compare("Tokyo", "Minneapolis")); assertEquals(1, comparator.compare("Shanghai", "Minneapolis")); } - /** + /** * Tests whether or not updates are disabled after a comparison is made. */ public void testLock() { - FixedOrderComparator comparator = new FixedOrderComparator(topCities); + FixedOrderComparator comparator = new FixedOrderComparator(topCities); assertEquals(false, comparator.isLocked()); comparator.compare("New York", "Tokyo"); assertEquals(true, comparator.isLocked()); @@ -152,7 +151,7 @@ public class TestFixedOrderComparator extends TestCase { } public void testUnknownObjectBehavior() { - FixedOrderComparator comparator = new FixedOrderComparator(topCities); + FixedOrderComparator comparator = new FixedOrderComparator(topCities); try { comparator.compare("New York", "Minneapolis"); fail("Should have thrown a IllegalArgumentException"); @@ -165,42 +164,43 @@ public class TestFixedOrderComparator extends TestCase { } catch (IllegalArgumentException e) { // success-- ignore } - assertEquals(FixedOrderComparator.UNKNOWN_THROW_EXCEPTION, comparator.getUnknownObjectBehavior()); + assertEquals(FixedOrderComparator.UnknownObjectBehavior.EXCEPTION, comparator.getUnknownObjectBehavior()); - comparator = new FixedOrderComparator(topCities); - comparator.setUnknownObjectBehavior(FixedOrderComparator.UNKNOWN_BEFORE); - assertEquals(FixedOrderComparator.UNKNOWN_BEFORE, comparator.getUnknownObjectBehavior()); - LinkedList keys = new LinkedList(Arrays.asList(topCities)); + comparator = new FixedOrderComparator(topCities); + comparator.setUnknownObjectBehavior(FixedOrderComparator.UnknownObjectBehavior.BEFORE); + assertEquals(FixedOrderComparator.UnknownObjectBehavior.BEFORE, comparator.getUnknownObjectBehavior()); + LinkedList keys = new LinkedList(Arrays.asList(topCities)); keys.addFirst("Minneapolis"); assertComparatorYieldsOrder(keys.toArray(new String[0]), comparator); - + assertEquals(-1, comparator.compare("Minneapolis", "New York")); assertEquals( 1, comparator.compare("New York", "Minneapolis")); assertEquals( 0, comparator.compare("Minneapolis", "St Paul")); - comparator = new FixedOrderComparator(topCities); - comparator.setUnknownObjectBehavior(FixedOrderComparator.UNKNOWN_AFTER); - keys = new LinkedList(Arrays.asList(topCities)); + comparator = new FixedOrderComparator(topCities); + comparator.setUnknownObjectBehavior(FixedOrderComparator.UnknownObjectBehavior.AFTER); + keys = new LinkedList(Arrays.asList(topCities)); keys.add("Minneapolis"); assertComparatorYieldsOrder(keys.toArray(new String[0]), comparator); - + assertEquals( 1, comparator.compare("Minneapolis", "New York")); assertEquals(-1, comparator.compare("New York", "Minneapolis")); assertEquals( 0, comparator.compare("Minneapolis", "St Paul")); - + } - + // // Helper methods // - + /** Shuffles the keys and asserts that the comparator sorts them back to * their original order. */ - private void assertComparatorYieldsOrder(Object[] orderedObjects, - Comparator comparator) { - Object[] keys = (Object[]) orderedObjects.clone(); - + @SuppressWarnings("unused") + private void assertComparatorYieldsOrder(String[] orderedObjects, + Comparator comparator) { + String[] keys = orderedObjects.clone(); + // shuffle until the order changes. It's extremely rare that // this requires more than one shuffle. @@ -209,13 +209,13 @@ public class TestFixedOrderComparator extends TestCase { shuffle: { Random rand = new Random(); for (int i = keys.length-1; i > 0; i--) { - Object swap = keys[i]; + String swap = keys[i]; int j = rand.nextInt(i+1); keys[i] = keys[j]; - keys[j] = swap; + keys[j] = swap; } } - + testShuffle: { for (int i = 0; i < keys.length && !isInNewOrder; i++) { if( !orderedObjects[i].equals(keys[i])) { @@ -224,14 +224,14 @@ public class TestFixedOrderComparator extends TestCase { } } } - + // The real test: sort and make sure they come out right. - + Arrays.sort(keys, comparator); for (int i = 0; i < orderedObjects.length; i++) { assertEquals(orderedObjects[i], keys[i]); } } - + } diff --git a/src/test/org/apache/commons/collections/comparators/TestReverseComparator.java b/src/test/org/apache/commons/collections/comparators/TestReverseComparator.java index a980bcff0..848619246 100644 --- a/src/test/org/apache/commons/collections/comparators/TestReverseComparator.java +++ b/src/test/org/apache/commons/collections/comparators/TestReverseComparator.java @@ -35,7 +35,7 @@ import junit.framework.TestSuite; * * @author Unknown */ -public class TestReverseComparator extends AbstractTestComparator { +public class TestReverseComparator extends AbstractTestComparator { public TestReverseComparator(String testName) { super(testName); @@ -46,21 +46,21 @@ public class TestReverseComparator extends AbstractTestComparator { } /** - * For the purposes of this test, return a + * For the purposes of this test, return a * ReverseComparator that wraps the java.util.Collections.reverseOrder() * Comparator. The resulting comparator should * sort according to natural Order. (Note: we wrap * a Comparator taken from the JDK so that we can * save a "canonical" form in SVN. - * + * * @return Comparator that returns "natural" order */ - public Comparator makeComparator() { - return new ReverseComparator(Collections.reverseOrder()); + public Comparator makeObject() { + return new ReverseComparator(Collections.reverseOrder()); } - public List getComparableObjectsOrdered() { - List list = new LinkedList(); + public List getComparableObjectsOrdered() { + List list = new LinkedList(); list.add(new Integer(1)); list.add(new Integer(2)); list.add(new Integer(3)); @@ -69,11 +69,12 @@ public class TestReverseComparator extends AbstractTestComparator { return list; } - /** + /** * Override this inherited test since Collections.reverseOrder * doesn't adhere to the "soft" Comparator contract, and we've * already "cannonized" the comparator returned by makeComparator. */ + @SuppressWarnings("unchecked") public void testSerializeDeserializeThenCompare() throws Exception { Comparator comp = new ReverseComparator(new ComparableComparator()); @@ -81,7 +82,7 @@ public class TestReverseComparator extends AbstractTestComparator { ObjectOutputStream out = new ObjectOutputStream(buffer); out.writeObject(comp); out.close(); - + ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray())); Object dest = in.readObject(); in.close(); diff --git a/src/test/org/apache/commons/collections/iterators/AbstractTestIterator.java b/src/test/org/apache/commons/collections/iterators/AbstractTestIterator.java index 97cfdcce4..53be5a7d3 100644 --- a/src/test/org/apache/commons/collections/iterators/AbstractTestIterator.java +++ b/src/test/org/apache/commons/collections/iterators/AbstractTestIterator.java @@ -35,7 +35,7 @@ import org.apache.commons.collections.AbstractTestObject; * @author Morgan Delagrange * @author Stephen Colebourne */ -public abstract class AbstractTestIterator extends AbstractTestObject { +public abstract class AbstractTestIterator extends AbstractTestObject { /** * JUnit constructor. @@ -52,23 +52,14 @@ public abstract class AbstractTestIterator extends AbstractTestObject { * * @return an empty iterator */ - public abstract Iterator makeEmptyIterator(); - - /** - * Implement this method to return an iterator over a collection with elements. - * - * @return a full iterator - */ - public abstract Iterator makeFullIterator(); + public abstract Iterator makeEmptyIterator(); /** * Implements the abstract superclass method to return the full iterator. * * @return a full iterator */ - public Object makeObject() { - return makeFullIterator(); - } + public abstract Iterator makeObject(); /** * Whether or not we are testing an iterator that can be empty. @@ -116,7 +107,7 @@ public abstract class AbstractTestIterator extends AbstractTestObject { return; } - Iterator it = makeEmptyIterator(); + Iterator it = makeEmptyIterator(); // hasNext() should return false assertEquals("hasNext() should return false for empty iterators", false, it.hasNext()); @@ -140,7 +131,7 @@ public abstract class AbstractTestIterator extends AbstractTestObject { return; } - Iterator it = makeFullIterator(); + Iterator it = makeObject(); // hasNext() must be true (ensure makeFullIterator is correct!) assertEquals("hasNext() should return true for at least one element", true, it.hasNext()); @@ -172,7 +163,7 @@ public abstract class AbstractTestIterator extends AbstractTestObject { * Test remove behaviour. */ public void testRemove() { - Iterator it = makeFullIterator(); + Iterator it = makeObject(); if (supportsRemove() == false) { // check for UnsupportedOperationException if not supported diff --git a/src/test/org/apache/commons/collections/iterators/AbstractTestListIterator.java b/src/test/org/apache/commons/collections/iterators/AbstractTestListIterator.java index ff0c40121..8ca9e3da4 100644 --- a/src/test/org/apache/commons/collections/iterators/AbstractTestListIterator.java +++ b/src/test/org/apache/commons/collections/iterators/AbstractTestListIterator.java @@ -17,7 +17,6 @@ package org.apache.commons.collections.iterators; import java.util.ArrayList; -import java.util.Iterator; import java.util.ListIterator; import java.util.NoSuchElementException; @@ -35,11 +34,11 @@ import java.util.NoSuchElementException; * @author Rodney Waldhoff * @author Stephen Colebourne */ -public abstract class AbstractTestListIterator extends AbstractTestIterator { +public abstract class AbstractTestListIterator extends AbstractTestIterator { /** * JUnit constructor. - * + * * @param testName the test class name */ public AbstractTestListIterator(String testName) { @@ -48,41 +47,23 @@ public abstract class AbstractTestListIterator extends AbstractTestIterator { //----------------------------------------------------------------------- /** - * Implement this method to return a list iterator over an empty collection. - * + * Implements the abstract superclass method to return the list iterator. + * * @return an empty iterator */ - public abstract ListIterator makeEmptyListIterator(); - - /** - * Implement this method to return a list iterator over a collection with elements. - * - * @return a full iterator - */ - public abstract ListIterator makeFullListIterator(); + public abstract ListIterator makeEmptyIterator(); /** * Implements the abstract superclass method to return the list iterator. - * - * @return an empty iterator - */ - public Iterator makeEmptyIterator() { - return makeEmptyListIterator(); - } - - /** - * Implements the abstract superclass method to return the list iterator. - * + * * @return a full iterator */ - public Iterator makeFullIterator() { - return makeFullListIterator(); - } + public abstract ListIterator makeObject(); /** * Whether or not we are testing an iterator that supports add(). * Default is true. - * + * * @return true if Iterator supports add */ public boolean supportsAdd() { @@ -92,7 +73,7 @@ public abstract class AbstractTestListIterator extends AbstractTestIterator { /** * Whether or not we are testing an iterator that supports set(). * Default is true. - * + * * @return true if Iterator supports set */ public boolean supportsSet() { @@ -103,7 +84,7 @@ public abstract class AbstractTestListIterator extends AbstractTestIterator { * The value to be used in the add and set tests. * Default is null. */ - public Object addSetValue() { + public E addSetValue() { return null; } @@ -116,20 +97,20 @@ public abstract class AbstractTestListIterator extends AbstractTestIterator { return; } - ListIterator it = makeEmptyListIterator(); - + ListIterator it = makeEmptyIterator(); + assertEquals(false, it.hasNext()); assertEquals(0, it.nextIndex()); assertEquals(false, it.hasPrevious()); assertEquals(-1, it.previousIndex()); - + // next() should throw a NoSuchElementException try { it.next(); fail("NoSuchElementException must be thrown from empty ListIterator"); } catch (NoSuchElementException e) { } - + // previous() should throw a NoSuchElementException try { it.previous(); @@ -137,17 +118,17 @@ public abstract class AbstractTestListIterator extends AbstractTestIterator { } catch (NoSuchElementException e) { } } - + /** * Test navigation through the iterator. */ public void testWalkForwardAndBack() { - ArrayList list = new ArrayList(); - ListIterator it = makeFullListIterator(); + ArrayList list = new ArrayList(); + ListIterator it = makeObject(); while (it.hasNext()) { list.add(it.next()); } - + // check state at end assertEquals(false, it.hasNext()); assertEquals(true, it.hasPrevious()); @@ -156,16 +137,16 @@ public abstract class AbstractTestListIterator extends AbstractTestIterator { fail("NoSuchElementException must be thrown from next at end of ListIterator"); } catch (NoSuchElementException e) { } - + // loop back through comparing for (int i = list.size() - 1; i >= 0; i--) { assertEquals(i + 1, it.nextIndex()); assertEquals(i, it.previousIndex()); - + Object obj = list.get(i); assertEquals(obj, it.previous()); } - + // check state at start assertEquals(true, it.hasNext()); assertEquals(false, it.hasPrevious()); @@ -175,14 +156,14 @@ public abstract class AbstractTestListIterator extends AbstractTestIterator { } catch (NoSuchElementException e) { } } - + /** * Test add behaviour. */ public void testAdd() { - ListIterator it = makeFullListIterator(); - - Object addValue = addSetValue(); + ListIterator it = makeObject(); + + E addValue = addSetValue(); if (supportsAdd() == false) { // check for UnsupportedOperationException if not supported try { @@ -190,34 +171,34 @@ public abstract class AbstractTestListIterator extends AbstractTestIterator { } catch (UnsupportedOperationException ex) {} return; } - + // add at start should be OK, added should be previous - it = makeFullListIterator(); + it = makeObject(); it.add(addValue); assertEquals(addValue, it.previous()); // add at start should be OK, added should not be next - it = makeFullListIterator(); + it = makeObject(); it.add(addValue); assertTrue(addValue != it.next()); // add in middle and at end should be OK - it = makeFullListIterator(); + it = makeObject(); while (it.hasNext()) { it.next(); it.add(addValue); // check add OK assertEquals(addValue, it.previous()); it.next(); - } + } } - + /** * Test set behaviour. */ public void testSet() { - ListIterator it = makeFullListIterator(); - + ListIterator it = makeObject(); + if (supportsSet() == false) { // check for UnsupportedOperationException if not supported try { @@ -225,24 +206,24 @@ public abstract class AbstractTestListIterator extends AbstractTestIterator { } catch (UnsupportedOperationException ex) {} return; } - + // should throw IllegalStateException before next() called try { it.set(addSetValue()); fail(); } catch (IllegalStateException ex) {} - + // set after next should be fine it.next(); it.set(addSetValue()); - + // repeated set calls should be fine it.set(addSetValue()); } - + public void testRemoveThenSet() { - ListIterator it = makeFullListIterator(); + ListIterator it = makeObject(); if (supportsRemove() && supportsSet()) { it.next(); it.remove(); @@ -255,7 +236,7 @@ public abstract class AbstractTestListIterator extends AbstractTestIterator { } public void testAddThenSet() { - ListIterator it = makeFullListIterator(); + ListIterator it = makeObject(); // add then set if (supportsAdd() && supportsSet()) { it.next(); @@ -267,13 +248,13 @@ public abstract class AbstractTestListIterator extends AbstractTestIterator { } } } - + /** * Test remove after add behaviour. */ public void testAddThenRemove() { - ListIterator it = makeFullListIterator(); - + ListIterator it = makeObject(); + // add then remove if (supportsAdd() && supportsRemove()) { it.next(); @@ -285,5 +266,5 @@ public abstract class AbstractTestListIterator extends AbstractTestIterator { } } } - + } diff --git a/src/test/org/apache/commons/collections/iterators/AbstractTestMapIterator.java b/src/test/org/apache/commons/collections/iterators/AbstractTestMapIterator.java index 5dc835e5f..445cf7bd1 100644 --- a/src/test/org/apache/commons/collections/iterators/AbstractTestMapIterator.java +++ b/src/test/org/apache/commons/collections/iterators/AbstractTestMapIterator.java @@ -17,7 +17,6 @@ package org.apache.commons.collections.iterators; import java.util.HashSet; -import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; @@ -37,11 +36,11 @@ import org.apache.commons.collections.MapIterator; * * @author Stephen Colebourne */ -public abstract class AbstractTestMapIterator extends AbstractTestIterator { +public abstract class AbstractTestMapIterator extends AbstractTestIterator { /** * JUnit constructor. - * + * * @param testName the test class name */ public AbstractTestMapIterator(String testName) { @@ -51,56 +50,38 @@ public abstract class AbstractTestMapIterator extends AbstractTestIterator { //----------------------------------------------------------------------- /** * Implement this method to return a map iterator over an empty map. - * + * * @return an empty iterator */ - public abstract MapIterator makeEmptyMapIterator(); + public abstract MapIterator makeEmptyIterator(); /** * Implement this method to return a map iterator over a map with elements. - * + * * @return a full iterator */ - public abstract MapIterator makeFullMapIterator(); + public abstract MapIterator makeObject(); /** * Implement this method to return the map which contains the same data as the * iterator. - * + * * @return a full map which can be updated */ - public abstract Map getMap(); - + public abstract Map getMap(); + /** * Implement this method to return the confirmed map which contains the same * data as the iterator. - * + * * @return a full map which can be updated */ - public abstract Map getConfirmedMap(); - - /** - * Implements the abstract superclass method to return the list iterator. - * - * @return an empty iterator - */ - public final Iterator makeEmptyIterator() { - return makeEmptyMapIterator(); - } - - /** - * Implements the abstract superclass method to return the list iterator. - * - * @return a full iterator - */ - public final Iterator makeFullIterator() { - return makeFullMapIterator(); - } + public abstract Map getConfirmedMap(); /** * Whether or not we are testing an iterator that supports setValue(). * Default is true. - * + * * @return true if Iterator supports set */ public boolean supportsSetValue() { @@ -110,19 +91,20 @@ public abstract class AbstractTestMapIterator extends AbstractTestIterator { /** * Whether the get operation on the map structurally modifies the map, * such as with LRUMap. Default is false. - * + * * @return true if the get method structurally modifies the map */ public boolean isGetStructuralModify() { return false; } - + /** * The values to be used in the add and set tests. * Default is two strings. */ - public Object[] addSetValues() { - return new Object[] {"A", "B"}; + @SuppressWarnings("unchecked") + public V[] addSetValues() { + return (V[]) new Object[] { "A", "B" }; } //----------------------------------------------------------------------- @@ -134,28 +116,27 @@ public abstract class AbstractTestMapIterator extends AbstractTestIterator { return; } - MapIterator it = makeEmptyMapIterator(); - Map map = getMap(); + MapIterator it = makeEmptyIterator(); assertEquals(false, it.hasNext()); - + // next() should throw a NoSuchElementException try { it.next(); fail(); } catch (NoSuchElementException ex) {} - + // getKey() should throw an IllegalStateException try { it.getKey(); fail(); } catch (IllegalStateException ex) {} - + // getValue() should throw an IllegalStateException try { it.getValue(); fail(); } catch (IllegalStateException ex) {} - + if (supportsSetValue() == false) { // setValue() should throw an UnsupportedOperationException/IllegalStateException try { @@ -181,21 +162,21 @@ public abstract class AbstractTestMapIterator extends AbstractTestIterator { return; } - MapIterator it = makeFullMapIterator(); - Map map = getMap(); + MapIterator it = makeObject(); + Map map = getMap(); assertEquals(true, it.hasNext()); - + assertEquals(true, it.hasNext()); - Set set = new HashSet(); + Set set = new HashSet(); while (it.hasNext()) { // getKey - Object key = it.next(); + K key = it.next(); assertSame("it.next() should equals getKey()", key, it.getKey()); assertTrue("Key must be in map", map.containsKey(key)); assertTrue("Key must be unique", set.add(key)); - + // getValue - Object value = it.getValue(); + V value = it.getValue(); if (isGetStructuralModify() == false) { assertSame("Value must be mapped to key", map.get(key), value); } @@ -204,22 +185,22 @@ public abstract class AbstractTestMapIterator extends AbstractTestIterator { verify(); } } - + //----------------------------------------------------------------------- public void testMapIteratorSet() { if (supportsFullIterator() == false) { return; } - Object newValue = addSetValues()[0]; - Object newValue2 = (addSetValues().length == 1 ? addSetValues()[0] : addSetValues()[1]); - MapIterator it = makeFullMapIterator(); - Map map = getMap(); - Map confirmed = getConfirmedMap(); + V newValue = addSetValues()[0]; + V newValue2 = (addSetValues().length == 1 ? addSetValues()[0] : addSetValues()[1]); + MapIterator it = makeObject(); + Map map = getMap(); + Map confirmed = getConfirmedMap(); assertEquals(true, it.hasNext()); - Object key = it.next(); - Object value = it.getValue(); - + K key = it.next(); + V value = it.getValue(); + if (supportsSetValue() == false) { try { it.setValue(newValue); @@ -227,24 +208,24 @@ public abstract class AbstractTestMapIterator extends AbstractTestIterator { } catch (UnsupportedOperationException ex) {} return; } - Object old = it.setValue(newValue); + V old = it.setValue(newValue); confirmed.put(key, newValue); assertSame("Key must not change after setValue", key, it.getKey()); assertSame("Value must be changed after setValue", newValue, it.getValue()); assertSame("setValue must return old value", value, old); assertEquals("Map must contain key", true, map.containsKey(key)); // test against confirmed, as map may contain value twice - assertEquals("Map must not contain old value", + assertEquals("Map must not contain old value", confirmed.containsValue(old), map.containsValue(old)); assertEquals("Map must contain new value", true, map.containsValue(newValue)); verify(); - + it.setValue(newValue); // same value - should be OK confirmed.put(key, newValue); assertSame("Key must not change after setValue", key, it.getKey()); assertSame("Value must be changed after setValue", newValue, it.getValue()); verify(); - + it.setValue(newValue2); // new value confirmed.put(key, newValue2); assertSame("Key must not change after setValue", key, it.getKey()); @@ -254,12 +235,12 @@ public abstract class AbstractTestMapIterator extends AbstractTestIterator { //----------------------------------------------------------------------- public void testRemove() { // override - MapIterator it = makeFullMapIterator(); - Map map = getMap(); - Map confirmed = getConfirmedMap(); + MapIterator it = makeObject(); + Map map = getMap(); + Map confirmed = getConfirmedMap(); assertEquals(true, it.hasNext()); - Object key = it.next(); - + K key = it.next(); + if (supportsRemove() == false) { try { it.remove(); @@ -268,12 +249,12 @@ public abstract class AbstractTestMapIterator extends AbstractTestIterator { } return; } - + it.remove(); confirmed.remove(key); assertEquals(false, map.containsKey(key)); verify(); - + try { it.remove(); // second remove fails } catch (IllegalStateException ex) { @@ -286,19 +267,18 @@ public abstract class AbstractTestMapIterator extends AbstractTestIterator { if (supportsSetValue() == false || supportsRemove() == false) { return; } - Object newValue = addSetValues()[0]; - MapIterator it = makeFullMapIterator(); - Map map = getMap(); - Map confirmed = getConfirmedMap(); - + V newValue = addSetValues()[0]; + MapIterator it = makeObject(); + Map confirmed = getConfirmedMap(); + assertEquals(true, it.hasNext()); - Object key = it.next(); - + K key = it.next(); + it.setValue(newValue); it.remove(); confirmed.remove(key); verify(); - + try { it.setValue(newValue); fail(); @@ -311,17 +291,16 @@ public abstract class AbstractTestMapIterator extends AbstractTestIterator { if (supportsRemove() == false) { return; } - MapIterator it = makeFullMapIterator(); - Map map = getMap(); - Map confirmed = getConfirmedMap(); - + MapIterator it = makeObject(); + Map confirmed = getConfirmedMap(); + assertEquals(true, it.hasNext()); - Object key = it.next(); - + K key = it.next(); + it.remove(); confirmed.remove(key); verify(); - + try { it.getKey(); fail(); @@ -334,17 +313,16 @@ public abstract class AbstractTestMapIterator extends AbstractTestIterator { if (supportsRemove() == false) { return; } - MapIterator it = makeFullMapIterator(); - Map map = getMap(); - Map confirmed = getConfirmedMap(); - + MapIterator it = makeObject(); + Map confirmed = getConfirmedMap(); + assertEquals(true, it.hasNext()); - Object key = it.next(); - + K key = it.next(); + it.remove(); confirmed.remove(key); verify(); - + try { it.getValue(); fail(); diff --git a/src/test/org/apache/commons/collections/iterators/AbstractTestOrderedMapIterator.java b/src/test/org/apache/commons/collections/iterators/AbstractTestOrderedMapIterator.java index 2da7d0fb1..a099be52d 100644 --- a/src/test/org/apache/commons/collections/iterators/AbstractTestOrderedMapIterator.java +++ b/src/test/org/apache/commons/collections/iterators/AbstractTestOrderedMapIterator.java @@ -39,11 +39,11 @@ import org.apache.commons.collections.OrderedMapIterator; * * @author Stephen Colebourne */ -public abstract class AbstractTestOrderedMapIterator extends AbstractTestMapIterator { +public abstract class AbstractTestOrderedMapIterator extends AbstractTestMapIterator { /** * JUnit constructor. - * + * * @param testName the test class name */ public AbstractTestOrderedMapIterator(String testName) { @@ -51,14 +51,10 @@ public abstract class AbstractTestOrderedMapIterator extends AbstractTestMapIter } //----------------------------------------------------------------------- - public final OrderedMapIterator makeEmptyOrderedMapIterator() { - return (OrderedMapIterator) makeEmptyMapIterator(); - } + public abstract OrderedMapIterator makeEmptyIterator(); + + public abstract OrderedMapIterator makeObject(); - public final OrderedMapIterator makeFullOrderedMapIterator() { - return (OrderedMapIterator) makeFullMapIterator(); - } - //----------------------------------------------------------------------- /** * Test that the empty list iterator contract is correct. @@ -69,9 +65,8 @@ public abstract class AbstractTestOrderedMapIterator extends AbstractTestMapIter } super.testEmptyMapIterator(); - - OrderedMapIterator it = makeEmptyOrderedMapIterator(); - Map map = getMap(); + + OrderedMapIterator it = makeEmptyIterator(); assertEquals(false, it.hasPrevious()); try { it.previous(); @@ -89,29 +84,29 @@ public abstract class AbstractTestOrderedMapIterator extends AbstractTestMapIter } super.testFullMapIterator(); - - OrderedMapIterator it = makeFullOrderedMapIterator(); - Map map = getMap(); - + + OrderedMapIterator it = makeObject(); + Map map = getMap(); + assertEquals(true, it.hasNext()); assertEquals(false, it.hasPrevious()); - Set set = new HashSet(); + Set set = new HashSet(); while (it.hasNext()) { // getKey - Object key = it.next(); + K key = it.next(); assertSame("it.next() should equals getKey()", key, it.getKey()); assertTrue("Key must be in map", map.containsKey(key)); assertTrue("Key must be unique", set.add(key)); - + // getValue - Object value = it.getValue(); + V value = it.getValue(); if (isGetStructuralModify() == false) { assertSame("Value must be mapped to key", map.get(key), value); } assertTrue("Value must be in map", map.containsValue(value)); assertEquals(true, it.hasPrevious()); - + verify(); } while (it.hasPrevious()) { @@ -120,7 +115,7 @@ public abstract class AbstractTestOrderedMapIterator extends AbstractTestMapIter assertSame("it.previous() should equals getKey()", key, it.getKey()); assertTrue("Key must be in map", map.containsKey(key)); assertTrue("Key must be unique", set.remove(key)); - + // getValue Object value = it.getValue(); if (isGetStructuralModify() == false) { @@ -129,11 +124,11 @@ public abstract class AbstractTestOrderedMapIterator extends AbstractTestMapIter assertTrue("Value must be in map", map.containsValue(value)); assertEquals(true, it.hasNext()); - + verify(); } } - + //----------------------------------------------------------------------- /** * Test that the iterator order matches the keySet order. @@ -143,27 +138,27 @@ public abstract class AbstractTestOrderedMapIterator extends AbstractTestMapIter return; } - OrderedMapIterator it = makeFullOrderedMapIterator(); - Map map = getMap(); - - assertEquals("keySet() not consistent", new ArrayList(map.keySet()), new ArrayList(map.keySet())); - - Iterator it2 = map.keySet().iterator(); + OrderedMapIterator it = makeObject(); + Map map = getMap(); + + assertEquals("keySet() not consistent", new ArrayList(map.keySet()), new ArrayList(map.keySet())); + + Iterator it2 = map.keySet().iterator(); assertEquals(true, it.hasNext()); assertEquals(true, it2.hasNext()); - List list = new ArrayList(); + List list = new ArrayList(); while (it.hasNext()) { - Object key = it.next(); + K key = it.next(); assertEquals(it2.next(), key); list.add(key); } assertEquals(map.size(), list.size()); while (it.hasPrevious()) { - Object key = it.previous(); + K key = it.previous(); assertEquals(list.get(list.size() - 1), key); list.remove(list.size() - 1); } assertEquals(0, list.size()); } - + } diff --git a/src/test/org/apache/commons/collections/iterators/TestArrayIterator.java b/src/test/org/apache/commons/collections/iterators/TestArrayIterator.java index 9373816cb..6a585d177 100644 --- a/src/test/org/apache/commons/collections/iterators/TestArrayIterator.java +++ b/src/test/org/apache/commons/collections/iterators/TestArrayIterator.java @@ -34,7 +34,7 @@ import junit.framework.TestSuite; * @author Morgan Delagrange * @author Stephen Colebourne */ -public class TestArrayIterator extends AbstractTestIterator { +public class TestArrayIterator extends AbstractTestIterator { protected String[] testArray = { "One", "Two", "Three" }; @@ -46,24 +46,23 @@ public class TestArrayIterator extends AbstractTestIterator { super(testName); } - public Iterator makeEmptyIterator() { - return new ArrayIterator(new Object[0]); + public ArrayIterator makeEmptyIterator() { + return new ArrayIterator(new Object[0]); } - public Iterator makeFullIterator() { - return new ArrayIterator(testArray); + public ArrayIterator makeObject() { + return new ArrayIterator(testArray); } public boolean supportsRemove() { return false; } - public void testIterator() { - Iterator iter = (Iterator) makeFullIterator(); + Iterator iter = makeObject(); for (int i = 0; i < testArray.length; i++) { Object testValue = testArray[i]; - Object iterValue = iter.next(); + E iterValue = iter.next(); assertEquals("Iteration value is correct", testValue, iterValue); } @@ -71,7 +70,7 @@ public class TestArrayIterator extends AbstractTestIterator { assertTrue("Iterator should now be empty", !iter.hasNext()); try { - Object testValue = iter.next(); + iter.next(); } catch (Exception e) { assertTrue( "NoSuchElementException must be thrown", @@ -81,14 +80,13 @@ public class TestArrayIterator extends AbstractTestIterator { public void testNullArray() { try { - Iterator iter = new ArrayIterator(null); - + new ArrayIterator(null); fail("Constructor should throw a NullPointerException when constructed with a null array"); } catch (NullPointerException e) { // expected } - ArrayIterator iter = new ArrayIterator(); + ArrayIterator iter = new ArrayIterator(); try { iter.setArray(null); @@ -99,7 +97,7 @@ public class TestArrayIterator extends AbstractTestIterator { } public void testReset() { - ArrayIterator it = (ArrayIterator) makeFullIterator(); + ArrayIterator it = makeObject(); it.next(); it.reset(); assertEquals("One", it.next()); diff --git a/src/test/org/apache/commons/collections/iterators/TestArrayIterator2.java b/src/test/org/apache/commons/collections/iterators/TestArrayIterator2.java index 9d300693c..975c37b50 100644 --- a/src/test/org/apache/commons/collections/iterators/TestArrayIterator2.java +++ b/src/test/org/apache/commons/collections/iterators/TestArrayIterator2.java @@ -30,7 +30,7 @@ import junit.framework.TestSuite; * @author Morgan Delagrange * @author James Strachan */ -public class TestArrayIterator2 extends AbstractTestIterator { +public class TestArrayIterator2 extends AbstractTestIterator { protected int[] testArray = { 2, 4, 6, 8 }; @@ -42,41 +42,32 @@ public class TestArrayIterator2 extends AbstractTestIterator { super(testName); } - public Iterator makeEmptyIterator() { - return new ArrayIterator(new int[0]); + public ArrayIterator makeEmptyIterator() { + return new ArrayIterator(new int[0]); } - public Iterator makeFullIterator() { - return new ArrayIterator(testArray); + public ArrayIterator makeObject() { + return new ArrayIterator(testArray); } - /* - * We use these makeArrayIterator factory methods instead of - * directly calling the constructor so as to allow subclasses - * (e.g. TestArrayListIterator2) to use the existing test code. - * - * @return ArrayIterator - */ - public ArrayIterator makeArrayIterator() { - return (ArrayIterator) makeEmptyIterator(); + public ArrayIterator makeArrayIterator(Object array) { + return new ArrayIterator(array); } - public ArrayIterator makeArrayIterator(Object array) { - return new ArrayIterator(array); + + public ArrayIterator makeArrayIterator(Object array, int index) { + return new ArrayIterator(array, index); } - public ArrayIterator makeArrayIterator(Object array, int index) { - return new ArrayIterator(array, index); - } - public ArrayIterator makeArrayIterator(Object array, int start, int end) { - return new ArrayIterator(array, start, end); + + public ArrayIterator makeArrayIterator(Object array, int start, int end) { + return new ArrayIterator(array, start, end); } public boolean supportsRemove() { return false; } - public void testIterator() { - Iterator iter = (Iterator) makeFullIterator(); + Iterator iter = makeObject(); for (int i = 0; i < testArray.length; i++) { Integer testValue = new Integer(testArray[i]); Number iterValue = (Number) iter.next(); @@ -87,7 +78,7 @@ public class TestArrayIterator2 extends AbstractTestIterator { assertTrue("Iterator should now be empty", !iter.hasNext()); try { - Object testValue = iter.next(); + iter.next(); } catch (Exception e) { assertTrue( "NoSuchElementException must be thrown", @@ -96,9 +87,9 @@ public class TestArrayIterator2 extends AbstractTestIterator { } // proves that an ArrayIterator set with the constructor has the same number of elements - // as an ArrayIterator set with setArray(Object) + // as an ArrayIterator set with setArray(Object) public void testSetArray() { - Iterator iter1 = makeArrayIterator(testArray); + Iterator iter1 = makeArrayIterator(testArray); int count1 = 0; while (iter1.hasNext()) { ++count1; @@ -107,7 +98,7 @@ public class TestArrayIterator2 extends AbstractTestIterator { assertEquals("the count should be right using the constructor", count1, testArray.length); - ArrayIterator iter2 = makeArrayIterator(); + ArrayIterator iter2 = makeObject(); iter2.setArray(testArray); int count2 = 0; while (iter2.hasNext()) { @@ -119,7 +110,7 @@ public class TestArrayIterator2 extends AbstractTestIterator { } public void testIndexedArray() { - Iterator iter = makeArrayIterator(testArray, 2); + Iterator iter = makeArrayIterator(testArray, 2); int count = 0; while (iter.hasNext()) { ++count; diff --git a/src/test/org/apache/commons/collections/iterators/TestArrayListIterator.java b/src/test/org/apache/commons/collections/iterators/TestArrayListIterator.java index bb9cb16c8..621ae5a71 100644 --- a/src/test/org/apache/commons/collections/iterators/TestArrayListIterator.java +++ b/src/test/org/apache/commons/collections/iterators/TestArrayListIterator.java @@ -17,7 +17,6 @@ package org.apache.commons.collections.iterators; import java.util.Arrays; -import java.util.Iterator; import java.util.ListIterator; import java.util.NoSuchElementException; @@ -30,7 +29,7 @@ import junit.framework.TestSuite; * @version $Revision$ $Date$ * @author Neil O'Toole */ -public class TestArrayListIterator extends TestArrayIterator { +public class TestArrayListIterator extends TestArrayIterator { public TestArrayListIterator(String testName) { super(testName); @@ -40,16 +39,16 @@ public class TestArrayListIterator extends TestArrayIterator { return new TestSuite(TestArrayListIterator.class); } - public Iterator makeEmptyIterator() { - return new ArrayListIterator(new Object[0]); + public ArrayListIterator makeEmptyIterator() { + return new ArrayListIterator(new Object[0]); } - public Iterator makeFullIterator() { - return new ArrayListIterator(testArray); + public ArrayListIterator makeObject() { + return new ArrayListIterator(testArray); } - public ListIterator makeArrayListIterator(Object array) { - return new ArrayListIterator(array); + public ArrayListIterator makeArrayListIterator(Object array) { + return new ArrayListIterator(array); } public boolean supportsRemove() { @@ -61,7 +60,7 @@ public class TestArrayListIterator extends TestArrayIterator { * previous(). */ public void testListIterator() { - ListIterator iter = (ListIterator) makeFullIterator(); + ListIterator iter = makeObject(); // TestArrayIterator#testIterator() has already tested the iterator forward, // now we need to test it in reverse @@ -81,7 +80,7 @@ public class TestArrayListIterator extends TestArrayIterator { assertTrue("Iterator should now be empty", !iter.hasPrevious()); try { - Object testValue = iter.previous(); + iter.previous(); } catch (Exception e) { assertTrue( "NoSuchElementException must be thrown", @@ -93,17 +92,18 @@ public class TestArrayListIterator extends TestArrayIterator { /** * Tests the {@link java.util.ListIterator#set} operation. */ + @SuppressWarnings("unchecked") public void testListIteratorSet() { String[] testData = new String[] { "a", "b", "c" }; String[] result = new String[] { "0", "1", "2" }; - ListIterator iter = (ListIterator) makeArrayListIterator(testData); + ListIterator iter = makeArrayListIterator(testData); int x = 0; while (iter.hasNext()) { iter.next(); - iter.set(Integer.toString(x)); + iter.set((E) Integer.toString(x)); x++; } @@ -113,7 +113,7 @@ public class TestArrayListIterator extends TestArrayIterator { iter = makeArrayListIterator(testArray); try { - iter.set("should fail"); + iter.set((E) "should fail"); fail("ListIterator#set should fail if next() or previous() have not yet been called."); } catch (IllegalStateException e) { // expected diff --git a/src/test/org/apache/commons/collections/iterators/TestArrayListIterator2.java b/src/test/org/apache/commons/collections/iterators/TestArrayListIterator2.java index f3e5251b5..83d9b96cf 100644 --- a/src/test/org/apache/commons/collections/iterators/TestArrayListIterator2.java +++ b/src/test/org/apache/commons/collections/iterators/TestArrayListIterator2.java @@ -16,8 +16,6 @@ */ package org.apache.commons.collections.iterators; -import java.util.Iterator; - import junit.framework.Test; import junit.framework.TestSuite; @@ -27,7 +25,7 @@ import junit.framework.TestSuite; * @version $Revision$ $Date$ * @author Neil O'Toole */ -public class TestArrayListIterator2 extends TestArrayIterator2 { +public class TestArrayListIterator2 extends TestArrayIterator2 { public TestArrayListIterator2(String testName) { super(testName); @@ -37,28 +35,24 @@ public class TestArrayListIterator2 extends TestArrayIterator2 { return new TestSuite(TestArrayListIterator2.class); } - public Iterator makeEmptyIterator() { - return new ArrayListIterator(new int[0]); + public ArrayListIterator makeEmptyIterator() { + return new ArrayListIterator(new int[0]); } - public Iterator makeFullIterator() { - return new ArrayListIterator(testArray); + public ArrayListIterator makeObject() { + return new ArrayListIterator(testArray); } - public ArrayIterator makeArrayIterator() { - return (ArrayIterator) makeEmptyIterator(); + public ArrayListIterator makeArrayListIterator(Object array) { + return new ArrayListIterator(array); } - public ArrayIterator makeArrayIterator(Object array) { - return new ArrayListIterator(array); + public ArrayListIterator makeArrayListIterator(Object array, int index) { + return new ArrayListIterator(array, index); } - public ArrayIterator makeArrayIterator(Object array, int index) { - return new ArrayListIterator(array, index); - } - - public ArrayIterator makeArrayIterator(Object array, int start, int end) { - return new ArrayListIterator(array, start, end); + public ArrayListIterator makeArrayListIterator(Object array, int start, int end) { + return new ArrayListIterator(array, start, end); } } diff --git a/src/test/org/apache/commons/collections/iterators/TestCollatingIterator.java b/src/test/org/apache/commons/collections/iterators/TestCollatingIterator.java index 40feaa5e9..11be9cfc2 100644 --- a/src/test/org/apache/commons/collections/iterators/TestCollatingIterator.java +++ b/src/test/org/apache/commons/collections/iterators/TestCollatingIterator.java @@ -18,7 +18,6 @@ package org.apache.commons.collections.iterators; import java.util.ArrayList; import java.util.Comparator; -import java.util.Iterator; import junit.framework.Test; import junit.framework.TestSuite; @@ -31,56 +30,56 @@ import org.apache.commons.collections.comparators.ComparableComparator; * @version $Revision$ $Date$ * @author Rodney Waldhoff */ -public class TestCollatingIterator extends AbstractTestIterator { +public class TestCollatingIterator extends AbstractTestIterator { //------------------------------------------------------------ Conventional - + public TestCollatingIterator(String testName) { super(testName); } - + public static Test suite() { return new TestSuite(TestCollatingIterator.class); } //--------------------------------------------------------------- Lifecycle - private Comparator comparator = null; - private ArrayList evens = null; - private ArrayList odds = null; - private ArrayList fib = null; + private Comparator comparator = null; + private ArrayList evens = null; + private ArrayList odds = null; + private ArrayList fib = null; public void setUp() throws Exception { super.setUp(); - comparator = new ComparableComparator(); - evens = new ArrayList(); - odds = new ArrayList(); - for(int i=0;i<20;i++) { - if(0 == i%2) { - evens.add(new Integer(i)); + comparator = new ComparableComparator(); + evens = new ArrayList(); + odds = new ArrayList(); + for (int i = 0; i < 20; i++) { + if (0 == i % 2) { + evens.add(i); } else { - odds.add(new Integer(i)); + odds.add(i); } } - fib = new ArrayList(); - fib.add(new Integer(1)); - fib.add(new Integer(1)); - fib.add(new Integer(2)); - fib.add(new Integer(3)); - fib.add(new Integer(5)); - fib.add(new Integer(8)); - fib.add(new Integer(13)); - fib.add(new Integer(21)); - } - - //---------------------------------------------------- TestIterator Methods - - public Iterator makeEmptyIterator() { - return new CollatingIterator(comparator); + fib = new ArrayList(); + fib.add(1); + fib.add(1); + fib.add(2); + fib.add(3); + fib.add(5); + fib.add(8); + fib.add(13); + fib.add(21); } - public Iterator makeFullIterator() { - CollatingIterator iter = new CollatingIterator(comparator); + //---------------------------------------------------- TestIterator Methods + + public CollatingIterator makeEmptyIterator() { + return new CollatingIterator(comparator); + } + + public CollatingIterator makeObject() { + CollatingIterator iter = new CollatingIterator(comparator); iter.addIterator(evens.iterator()); iter.addIterator(odds.iterator()); iter.addIterator(fib.iterator()); @@ -90,38 +89,38 @@ public class TestCollatingIterator extends AbstractTestIterator { //------------------------------------------------------------------- Tests public void testGetSetComparator() { - CollatingIterator iter = new CollatingIterator(); + CollatingIterator iter = new CollatingIterator(); assertNull(iter.getComparator()); iter.setComparator(comparator); - assertSame(comparator,iter.getComparator()); + assertSame(comparator, iter.getComparator()); iter.setComparator(null); assertNull(iter.getComparator()); } public void testIterateEven() { - CollatingIterator iter = new CollatingIterator(comparator); + CollatingIterator iter = new CollatingIterator(comparator); iter.addIterator(evens.iterator()); - for(int i=0;i iter = new CollatingIterator(comparator, evens.iterator(), odds.iterator()); + for (int i = 0; i < 20; i++) { assertTrue(iter.hasNext()); - assertEquals(new Integer(i),iter.next()); + assertEquals(new Integer(i), iter.next()); assertEquals(i % 2,iter.getIteratorIndex()); } assertTrue(!iter.hasNext()); } public void testIterateOddEven() { - CollatingIterator iter = new CollatingIterator(comparator,odds.iterator(),evens.iterator()); - for(int i=0;i<20;i++) { + CollatingIterator iter = new CollatingIterator(comparator, odds.iterator(), evens.iterator()); + for (int i = 0; i < 20; i++) { assertTrue(iter.hasNext()); assertEquals(new Integer(i),iter.next()); assertEquals((i % 2) == 0 ? 1 : 0,iter.getIteratorIndex()); @@ -130,27 +129,26 @@ public class TestCollatingIterator extends AbstractTestIterator { } public void testIterateEvenEven() { - CollatingIterator iter = new CollatingIterator(comparator); + CollatingIterator iter = new CollatingIterator(comparator); iter.addIterator(evens.iterator()); iter.addIterator(evens.iterator()); - for(int i=0;i iter = new CollatingIterator(comparator); iter.addIterator(fib.iterator()); iter.addIterator(evens.iterator()); iter.addIterator(odds.iterator()); - + assertEquals(new Integer(0),iter.next()); // even 0 assertEquals(1,iter.getIteratorIndex()); assertEquals(new Integer(1),iter.next()); // fib 1 @@ -212,12 +210,13 @@ public class TestCollatingIterator extends AbstractTestIterator { } public void testRemoveFromSingle() { - CollatingIterator iter = new CollatingIterator(comparator); + CollatingIterator iter = new CollatingIterator(comparator); iter.addIterator(evens.iterator()); int expectedSize = evens.size(); - while(iter.hasNext()) { - Integer val = (Integer)(iter.next()); - if(val.intValue() % 4 == 0) { + while (iter.hasNext()) { + Object o = iter.next(); + Integer val = (Integer) o; + if (val.intValue() % 4 == 0) { expectedSize--; iter.remove(); } @@ -226,19 +225,20 @@ public class TestCollatingIterator extends AbstractTestIterator { } public void testRemoveFromDouble() { - CollatingIterator iter = new CollatingIterator(comparator); + CollatingIterator iter = new CollatingIterator(comparator); iter.addIterator(evens.iterator()); iter.addIterator(odds.iterator()); int expectedSize = evens.size() + odds.size(); - while(iter.hasNext()) { - Integer val = (Integer)(iter.next()); - if(val.intValue() % 4 == 0 || val.intValue() % 3 == 0 ) { + while (iter.hasNext()) { + Object o = iter.next(); + Integer val = (Integer) o; + if (val.intValue() % 4 == 0 || val.intValue() % 3 == 0) { expectedSize--; iter.remove(); } } - assertEquals(expectedSize,(evens.size() + odds.size())); - } + assertEquals(expectedSize, (evens.size() + odds.size())); + } } diff --git a/src/test/org/apache/commons/collections/iterators/TestFilterListIterator.java b/src/test/org/apache/commons/collections/iterators/TestFilterListIterator.java index 467e57245..a350856be 100644 --- a/src/test/org/apache/commons/collections/iterators/TestFilterListIterator.java +++ b/src/test/org/apache/commons/collections/iterators/TestFilterListIterator.java @@ -48,69 +48,69 @@ public class TestFilterListIterator extends TestCase { junit.textui.TestRunner.main(testCaseName); } - private ArrayList list = null; - private ArrayList odds = null; - private ArrayList evens = null; - private ArrayList threes = null; - private ArrayList fours = null; - private ArrayList sixes = null; - private Predicate truePred = null; - private Predicate falsePred = null; - private Predicate evenPred = null; - private Predicate oddPred = null; - private Predicate threePred = null; - private Predicate fourPred = null; + private ArrayList list = null; + private ArrayList odds = null; + private ArrayList evens = null; + private ArrayList threes = null; + private ArrayList fours = null; + private ArrayList sixes = null; + private Predicate truePred = null; + private Predicate falsePred = null; + private Predicate evenPred = null; + private Predicate oddPred = null; + private Predicate threePred = null; + private Predicate fourPred = null; private Random random = new Random(); public void setUp() { - list = new ArrayList(); - odds = new ArrayList(); - evens = new ArrayList(); - threes = new ArrayList(); - fours = new ArrayList(); - sixes = new ArrayList(); - for(int i=0;i<20;i++) { + list = new ArrayList(); + odds = new ArrayList(); + evens = new ArrayList(); + threes = new ArrayList(); + fours = new ArrayList(); + sixes = new ArrayList(); + for (int i = 0; i < 20; i++) { list.add(new Integer(i)); - if(i%2 == 0) { evens.add(new Integer(i)); } - if(i%2 == 1) { odds.add(new Integer(i)); } - if(i%3 == 0) { threes.add(new Integer(i)); } - if(i%4 == 0) { fours.add(new Integer(i)); } - if(i%6 == 0) { sixes.add(new Integer(i)); } + if (i % 2 == 0) { evens.add(new Integer(i)); } + if (i % 2 == 1) { odds.add(new Integer(i)); } + if (i % 3 == 0) { threes.add(new Integer(i)); } + if (i % 4 == 0) { fours.add(new Integer(i)); } + if (i % 6 == 0) { sixes.add(new Integer(i)); } } - truePred = new Predicate() { - public boolean evaluate(Object x) { + truePred = new Predicate() { + public boolean evaluate(Integer x) { return true; } }; - falsePred = new Predicate() { - public boolean evaluate(Object x) { + falsePred = new Predicate() { + public boolean evaluate(Integer x) { return true; } }; - evenPred = new Predicate() { - public boolean evaluate(Object x) { - return (((Integer)x).intValue()%2 == 0); + evenPred = new Predicate() { + public boolean evaluate(Integer x) { + return x % 2 == 0; } }; - oddPred = new Predicate() { - public boolean evaluate(Object x) { - return (((Integer)x).intValue()%2 == 1); + oddPred = new Predicate() { + public boolean evaluate(Integer x) { + return x % 2 == 1; } }; - threePred = new Predicate() { - public boolean evaluate(Object x) { - return (((Integer)x).intValue()%3 == 0); + threePred = new Predicate() { + public boolean evaluate(Integer x) { + return x % 3 == 0; } }; - fourPred = new Predicate() { - public boolean evaluate(Object x) { - return (((Integer)x).intValue()%4 == 0); + fourPred = new Predicate() { + public boolean evaluate(Integer x) { + return x % 4 == 0; } }; @@ -138,208 +138,207 @@ public class TestFilterListIterator extends TestCase { public void testManual() { // do this one "by hand" as a sanity check - FilterListIterator filtered = new FilterListIterator(list.listIterator(),threePred); + FilterListIterator filtered = new FilterListIterator(list.listIterator(), threePred); - assertEquals(new Integer(0),filtered.next()); - assertEquals(new Integer(3),filtered.next()); - assertEquals(new Integer(6),filtered.next()); - assertEquals(new Integer(9),filtered.next()); - assertEquals(new Integer(12),filtered.next()); - assertEquals(new Integer(15),filtered.next()); - assertEquals(new Integer(18),filtered.next()); + assertEquals(new Integer(0), filtered.next()); + assertEquals(new Integer(3), filtered.next()); + assertEquals(new Integer(6), filtered.next()); + assertEquals(new Integer(9), filtered.next()); + assertEquals(new Integer(12), filtered.next()); + assertEquals(new Integer(15), filtered.next()); + assertEquals(new Integer(18), filtered.next()); - assertEquals(new Integer(18),filtered.previous()); - assertEquals(new Integer(15),filtered.previous()); - assertEquals(new Integer(12),filtered.previous()); - assertEquals(new Integer(9),filtered.previous()); - assertEquals(new Integer(6),filtered.previous()); - assertEquals(new Integer(3),filtered.previous()); - assertEquals(new Integer(0),filtered.previous()); + assertEquals(new Integer(18), filtered.previous()); + assertEquals(new Integer(15), filtered.previous()); + assertEquals(new Integer(12), filtered.previous()); + assertEquals(new Integer(9), filtered.previous()); + assertEquals(new Integer(6), filtered.previous()); + assertEquals(new Integer(3), filtered.previous()); + assertEquals(new Integer(0), filtered.previous()); assertTrue(!filtered.hasPrevious()); - assertEquals(new Integer(0),filtered.next()); - assertEquals(new Integer(3),filtered.next()); - assertEquals(new Integer(6),filtered.next()); - assertEquals(new Integer(9),filtered.next()); - assertEquals(new Integer(12),filtered.next()); - assertEquals(new Integer(15),filtered.next()); - assertEquals(new Integer(18),filtered.next()); + assertEquals(new Integer(0), filtered.next()); + assertEquals(new Integer(3), filtered.next()); + assertEquals(new Integer(6), filtered.next()); + assertEquals(new Integer(9), filtered.next()); + assertEquals(new Integer(12), filtered.next()); + assertEquals(new Integer(15), filtered.next()); + assertEquals(new Integer(18), filtered.next()); assertTrue(!filtered.hasNext()); - assertEquals(new Integer(18),filtered.previous()); - assertEquals(new Integer(15),filtered.previous()); - assertEquals(new Integer(12),filtered.previous()); - assertEquals(new Integer(9),filtered.previous()); - assertEquals(new Integer(6),filtered.previous()); - assertEquals(new Integer(3),filtered.previous()); - assertEquals(new Integer(0),filtered.previous()); + assertEquals(new Integer(18), filtered.previous()); + assertEquals(new Integer(15), filtered.previous()); + assertEquals(new Integer(12), filtered.previous()); + assertEquals(new Integer(9), filtered.previous()); + assertEquals(new Integer(6), filtered.previous()); + assertEquals(new Integer(3), filtered.previous()); + assertEquals(new Integer(0), filtered.previous()); - assertEquals(new Integer(0),filtered.next()); - assertEquals(new Integer(0),filtered.previous()); - assertEquals(new Integer(0),filtered.next()); - - assertEquals(new Integer(3),filtered.next()); - assertEquals(new Integer(6),filtered.next()); - assertEquals(new Integer(6),filtered.previous()); - assertEquals(new Integer(3),filtered.previous()); - assertEquals(new Integer(3),filtered.next()); - assertEquals(new Integer(6),filtered.next()); + assertEquals(new Integer(0), filtered.next()); + assertEquals(new Integer(0), filtered.previous()); + assertEquals(new Integer(0), filtered.next()); - assertEquals(new Integer(9),filtered.next()); - assertEquals(new Integer(12),filtered.next()); - assertEquals(new Integer(15),filtered.next()); - assertEquals(new Integer(15),filtered.previous()); - assertEquals(new Integer(12),filtered.previous()); - assertEquals(new Integer(9),filtered.previous()); + assertEquals(new Integer(3), filtered.next()); + assertEquals(new Integer(6), filtered.next()); + assertEquals(new Integer(6), filtered.previous()); + assertEquals(new Integer(3), filtered.previous()); + assertEquals(new Integer(3), filtered.next()); + assertEquals(new Integer(6), filtered.next()); + assertEquals(new Integer(9), filtered.next()); + assertEquals(new Integer(12), filtered.next()); + assertEquals(new Integer(15), filtered.next()); + assertEquals(new Integer(15), filtered.previous()); + assertEquals(new Integer(12), filtered.previous()); + assertEquals(new Integer(9), filtered.previous()); } public void testTruePredicate() { - FilterListIterator filtered = new FilterListIterator(list.listIterator(),truePred); - walkLists(list,filtered); + FilterListIterator filtered = new FilterListIterator(list.listIterator(), truePred); + walkLists(list, filtered); } public void testFalsePredicate() { - FilterListIterator filtered = new FilterListIterator(list.listIterator(),falsePred); - walkLists(new ArrayList(),filtered); + FilterListIterator filtered = new FilterListIterator(list.listIterator(), falsePred); + walkLists(new ArrayList(), filtered); } public void testEvens() { - FilterListIterator filtered = new FilterListIterator(list.listIterator(),evenPred); - walkLists(evens,filtered); + FilterListIterator filtered = new FilterListIterator(list.listIterator(), evenPred); + walkLists(evens, filtered); } public void testOdds() { - FilterListIterator filtered = new FilterListIterator(list.listIterator(),oddPred); - walkLists(odds,filtered); + FilterListIterator filtered = new FilterListIterator(list.listIterator(), oddPred); + walkLists(odds, filtered); } public void testThrees() { - FilterListIterator filtered = new FilterListIterator(list.listIterator(),threePred); - walkLists(threes,filtered); + FilterListIterator filtered = new FilterListIterator(list.listIterator(), threePred); + walkLists(threes, filtered); } public void testFours() { - FilterListIterator filtered = new FilterListIterator(list.listIterator(),fourPred); - walkLists(fours,filtered); + FilterListIterator filtered = new FilterListIterator(list.listIterator(), fourPred); + walkLists(fours, filtered); } public void testNestedSixes() { - FilterListIterator filtered = new FilterListIterator( - new FilterListIterator(list.listIterator(),threePred), + FilterListIterator filtered = new FilterListIterator( + new FilterListIterator(list.listIterator(), threePred), evenPred ); - walkLists(sixes,filtered); + walkLists(sixes, filtered); } public void testNestedSixes2() { - FilterListIterator filtered = new FilterListIterator( - new FilterListIterator(list.listIterator(),evenPred), + FilterListIterator filtered = new FilterListIterator( + new FilterListIterator(list.listIterator(), evenPred), threePred ); - walkLists(sixes,filtered); + walkLists(sixes, filtered); } public void testNestedSixes3() { - FilterListIterator filtered = new FilterListIterator( - new FilterListIterator(list.listIterator(),threePred), + FilterListIterator filtered = new FilterListIterator( + new FilterListIterator(list.listIterator(), threePred), evenPred ); - walkLists(sixes,new FilterListIterator(filtered,truePred)); + walkLists(sixes, new FilterListIterator(filtered, truePred)); } public void testNextChangesPrevious() { { - FilterListIterator filtered = new FilterListIterator(list.listIterator(),threePred); - nextNextPrevious(threes.listIterator(),filtered); + FilterListIterator filtered = new FilterListIterator(list.listIterator(), threePred); + nextNextPrevious(threes.listIterator(), filtered); } { - FilterListIterator filtered = new FilterListIterator(list.listIterator(),truePred); - nextNextPrevious(list.listIterator(),filtered); + FilterListIterator filtered = new FilterListIterator(list.listIterator(), truePred); + nextNextPrevious(list.listIterator(), filtered); } } public void testPreviousChangesNext() { { - FilterListIterator filtered = new FilterListIterator(list.listIterator(),threePred); - ListIterator expected = threes.listIterator(); + FilterListIterator filtered = new FilterListIterator(list.listIterator(), threePred); + ListIterator expected = threes.listIterator(); walkForward(expected,filtered); previousPreviousNext(expected,filtered); } { - FilterListIterator filtered = new FilterListIterator(list.listIterator(),truePred); - ListIterator expected = list.listIterator(); - walkForward(expected,filtered); - previousPreviousNext(expected,filtered); + FilterListIterator filtered = new FilterListIterator(list.listIterator(), truePred); + ListIterator expected = list.listIterator(); + walkForward(expected, filtered); + previousPreviousNext(expected, filtered); } } public void testFailingHasNextBug() { - FilterListIterator filtered = new FilterListIterator(list.listIterator(),fourPred); - ListIterator expected = fours.listIterator(); - while(expected.hasNext()) { + FilterListIterator filtered = new FilterListIterator(list.listIterator(), fourPred); + ListIterator expected = fours.listIterator(); + while (expected.hasNext()) { expected.next(); filtered.next(); } assertTrue(filtered.hasPrevious()); assertTrue(!filtered.hasNext()); - assertEquals(expected.previous(),filtered.previous()); + assertEquals(expected.previous(), filtered.previous()); } // Utilities - private void walkForward(ListIterator expected, ListIterator testing) { - while(expected.hasNext()) { - assertEquals(expected.nextIndex(),testing.nextIndex()); - assertEquals(expected.previousIndex(),testing.previousIndex()); + private void walkForward(ListIterator expected, ListIterator testing) { + while (expected.hasNext()) { + assertEquals(expected.nextIndex(), testing.nextIndex()); + assertEquals(expected.previousIndex(), testing.previousIndex()); assertTrue(testing.hasNext()); - assertEquals(expected.next(),testing.next()); + assertEquals(expected.next(), testing.next()); } } - private void walkBackward(ListIterator expected, ListIterator testing) { - while(expected.hasPrevious()) { - assertEquals(expected.nextIndex(),testing.nextIndex()); - assertEquals(expected.previousIndex(),testing.previousIndex()); + private void walkBackward(ListIterator expected, ListIterator testing) { + while (expected.hasPrevious()) { + assertEquals(expected.nextIndex(), testing.nextIndex()); + assertEquals(expected.previousIndex(), testing.previousIndex()); assertTrue(testing.hasPrevious()); - assertEquals(expected.previous(),testing.previous()); + assertEquals(expected.previous(), testing.previous()); } } - private void nextNextPrevious(ListIterator expected, ListIterator testing) { + private void nextNextPrevious(ListIterator expected, ListIterator testing) { // calls to next() should change the value returned by previous() // even after previous() has been set by a call to hasPrevious() - assertEquals(expected.next(),testing.next()); - assertEquals(expected.hasPrevious(),testing.hasPrevious()); + assertEquals(expected.next(), testing.next()); + assertEquals(expected.hasPrevious(), testing.hasPrevious()); Object expecteda = expected.next(); Object testinga = testing.next(); - assertEquals(expecteda,testinga); + assertEquals(expecteda, testinga); Object expectedb = expected.previous(); Object testingb = testing.previous(); - assertEquals(expecteda,expectedb); - assertEquals(testinga,testingb); + assertEquals(expecteda, expectedb); + assertEquals(testinga, testingb); } - private void previousPreviousNext(ListIterator expected, ListIterator testing) { + private void previousPreviousNext(ListIterator expected, ListIterator testing) { // calls to previous() should change the value returned by next() // even after next() has been set by a call to hasNext() - assertEquals(expected.previous(),testing.previous()); - assertEquals(expected.hasNext(),testing.hasNext()); + assertEquals(expected.previous(), testing.previous()); + assertEquals(expected.hasNext(), testing.hasNext()); Object expecteda = expected.previous(); Object testinga = testing.previous(); - assertEquals(expecteda,testinga); + assertEquals(expecteda, testinga); Object expectedb = expected.next(); Object testingb = testing.next(); - assertEquals(expecteda,testingb); - assertEquals(expecteda,expectedb); - assertEquals(testinga,testingb); + assertEquals(expecteda, testingb); + assertEquals(expecteda, expectedb); + assertEquals(testinga, testingb); } - private void walkLists(List list, ListIterator testing) { - ListIterator expected = list.listIterator(); + private void walkLists(List list, ListIterator testing) { + ListIterator expected = list.listIterator(); // walk all the way forward walkForward(expected,testing); @@ -348,74 +347,73 @@ public class TestFilterListIterator extends TestCase { walkBackward(expected,testing); // forward,back,forward - while(expected.hasNext()) { - assertEquals(expected.nextIndex(),testing.nextIndex()); - assertEquals(expected.previousIndex(),testing.previousIndex()); + while (expected.hasNext()) { + assertEquals(expected.nextIndex(), testing.nextIndex()); + assertEquals(expected.previousIndex(), testing.previousIndex()); assertTrue(testing.hasNext()); - assertEquals(expected.next(),testing.next()); + assertEquals(expected.next(), testing.next()); assertTrue(testing.hasPrevious()); - assertEquals(expected.previous(),testing.previous()); + assertEquals(expected.previous(), testing.previous()); assertTrue(testing.hasNext()); - assertEquals(expected.next(),testing.next()); + assertEquals(expected.next(), testing.next()); } - // walk all the way back - walkBackward(expected,testing); + walkBackward(expected, testing); - for(int i=0;i { protected String[] testArray = { "One", "Two", "Three", "Four", "Five", "Six" }; - protected List list1 = null; - protected List list2 = null; - protected List list3 = null; + protected List list1 = null; + protected List list2 = null; + protected List list3 = null; public static Test suite() { return new TestSuite(TestIteratorChain.class); @@ -55,24 +55,24 @@ public class TestIteratorChain extends AbstractTestIterator { } public void setUp() { - list1 = new ArrayList(); + list1 = new ArrayList(); list1.add("One"); list1.add("Two"); list1.add("Three"); - list2 = new ArrayList(); + list2 = new ArrayList(); list2.add("Four"); - list3 = new ArrayList(); + list3 = new ArrayList(); list3.add("Five"); list3.add("Six"); } - public Iterator makeEmptyIterator() { - ArrayList list = new ArrayList(); - return new IteratorChain(list.iterator()); + public IteratorChain makeEmptyIterator() { + ArrayList list = new ArrayList(); + return new IteratorChain(list.iterator()); } - public Iterator makeFullIterator() { - IteratorChain chain = new IteratorChain(); + public IteratorChain makeObject() { + IteratorChain chain = new IteratorChain(); chain.addIterator(list1.iterator()); chain.addIterator(list2.iterator()); @@ -81,18 +81,18 @@ public class TestIteratorChain extends AbstractTestIterator { } public void testIterator() { - Iterator iter = (Iterator) makeFullIterator(); - for ( int i = 0; i < testArray.length; i++ ) { + Iterator iter = makeObject(); + for (int i = 0; i < testArray.length; i++) { Object testValue = testArray[i]; Object iterValue = iter.next(); assertEquals( "Iteration value is correct", testValue, iterValue ); } - assertTrue("Iterator should now be empty", ! iter.hasNext() ); + assertTrue("Iterator should now be empty", !iter.hasNext()); try { - Object testValue = iter.next(); + iter.next(); } catch (Exception e) { assertTrue("NoSuchElementException must be thrown", e.getClass().equals((new NoSuchElementException()).getClass())); @@ -101,38 +101,34 @@ public class TestIteratorChain extends AbstractTestIterator { public void testRemoveFromFilteredIterator() { - final Predicate myPredicate = new Predicate() { - public boolean evaluate( Object object ) { - Integer i = (Integer) object; - if (i.compareTo(new Integer(4)) < 0) - return true; - return false; + final Predicate myPredicate = new Predicate() { + public boolean evaluate(Integer i) { + return i.compareTo(new Integer(4)) < 0; } }; - List list1 = new ArrayList(); - List list2 = new ArrayList(); + List list1 = new ArrayList(); + List list2 = new ArrayList(); list1.add(new Integer(1)); list1.add(new Integer(2)); list2.add(new Integer(3)); list2.add(new Integer(4)); // will be ignored by the predicate - Iterator it1 = IteratorUtils.filteredIterator(list1.iterator(), myPredicate ); - Iterator it2 = IteratorUtils.filteredIterator(list2.iterator(), myPredicate ); + Iterator it1 = IteratorUtils.filteredIterator(list1.iterator(), myPredicate); + Iterator it2 = IteratorUtils.filteredIterator(list2.iterator(), myPredicate); - Iterator it = IteratorUtils.chainedIterator(it1, it2); + Iterator it = IteratorUtils.chainedIterator(it1, it2); while (it.hasNext()) { it.next(); it.remove(); } - assertEquals( 0, list1.size() ); - assertEquals( 1, list2.size() ); - + assertEquals(0, list1.size()); + assertEquals(1, list2.size()); } public void testRemove() { - Iterator iter = (Iterator) makeFullIterator(); + Iterator iter = makeObject(); try { iter.remove(); @@ -141,13 +137,13 @@ public class TestIteratorChain extends AbstractTestIterator { } - for ( int i = 0; i < testArray.length; i++ ) { - Object testValue = testArray[i]; - Object iterValue = iter.next(); + for (int i = 0; i < testArray.length; i++) { + String testValue = testArray[i]; + String iterValue = iter.next(); - assertEquals( "Iteration value is correct", testValue, iterValue ); + assertEquals("Iteration value is correct", testValue, iterValue); - if (! iterValue.equals("Four")) { + if (!iterValue.equals("Four")) { iter.remove(); } } @@ -158,12 +154,12 @@ public class TestIteratorChain extends AbstractTestIterator { } public void testFirstIteratorIsEmptyBug() { - List empty = new ArrayList(); - List notEmpty = new ArrayList(); + List empty = new ArrayList(); + List notEmpty = new ArrayList(); notEmpty.add("A"); notEmpty.add("B"); notEmpty.add("C"); - IteratorChain chain = new IteratorChain(); + IteratorChain chain = new IteratorChain(); chain.addIterator(empty.iterator()); chain.addIterator(notEmpty.iterator()); assertTrue("should have next",chain.hasNext()); @@ -176,7 +172,7 @@ public class TestIteratorChain extends AbstractTestIterator { } public void testEmptyChain() { - IteratorChain chain = new IteratorChain(); + IteratorChain chain = new IteratorChain(); assertEquals(false, chain.hasNext()); try { chain.next(); diff --git a/src/test/org/apache/commons/collections/iterators/TestLoopingIterator.java b/src/test/org/apache/commons/collections/iterators/TestLoopingIterator.java index 36f9f43bf..655e1cd48 100644 --- a/src/test/org/apache/commons/collections/iterators/TestLoopingIterator.java +++ b/src/test/org/apache/commons/collections/iterators/TestLoopingIterator.java @@ -48,7 +48,7 @@ public class TestLoopingIterator extends TestCase { */ public void testConstructorEx() throws Exception { try { - new LoopingIterator(null); + new LoopingIterator(null); fail(); } catch (NullPointerException ex) { } @@ -59,8 +59,8 @@ public class TestLoopingIterator extends TestCase { * @throws Exception If something unexpected occurs. */ public void testLooping0() throws Exception { - List list = new ArrayList(); - LoopingIterator loop = new LoopingIterator(list); + List list = new ArrayList(); + LoopingIterator loop = new LoopingIterator(list); assertTrue("hasNext should return false", loop.hasNext() == false); try { @@ -75,8 +75,8 @@ public class TestLoopingIterator extends TestCase { * @throws Exception If something unexpected occurs. */ public void testLooping1() throws Exception { - List list = new ArrayList(Arrays.asList(new String[] { "a" })); - LoopingIterator loop = new LoopingIterator(list); + List list = Arrays.asList(new String[] { "a" }); + LoopingIterator loop = new LoopingIterator(list); assertTrue("1st hasNext should return true", loop.hasNext()); assertEquals("a", loop.next()); @@ -94,8 +94,8 @@ public class TestLoopingIterator extends TestCase { * @throws Exception If something unexpected occurs. */ public void testLooping2() throws Exception { - List list = new ArrayList(Arrays.asList(new String[] { "a", "b" })); - LoopingIterator loop = new LoopingIterator(list); + List list = Arrays.asList(new String[] { "a", "b" }); + LoopingIterator loop = new LoopingIterator(list); assertTrue("1st hasNext should return true", loop.hasNext()); assertEquals("a", loop.next()); @@ -113,8 +113,8 @@ public class TestLoopingIterator extends TestCase { * @throws Exception If something unexpected occurs. */ public void testLooping3() throws Exception { - List list = new ArrayList(Arrays.asList(new String[] { "a", "b", "c" })); - LoopingIterator loop = new LoopingIterator(list); + List list = Arrays.asList(new String[] { "a", "b", "c" }); + LoopingIterator loop = new LoopingIterator(list); assertTrue("1st hasNext should return true", loop.hasNext()); assertEquals("a", loop.next()); @@ -135,8 +135,8 @@ public class TestLoopingIterator extends TestCase { * @throws Exception If something unexpected occurs. */ public void testRemoving1() throws Exception { - List list = new ArrayList(Arrays.asList(new String[] { "a", "b", "c" })); - LoopingIterator loop = new LoopingIterator(list); + List list = new ArrayList(Arrays.asList(new String[] { "a", "b", "c" })); + LoopingIterator loop = new LoopingIterator(list); assertEquals("list should have 3 elements.", 3, list.size()); assertTrue("1st hasNext should return true", loop.hasNext()); @@ -167,8 +167,8 @@ public class TestLoopingIterator extends TestCase { * @throws Exception If something unexpected occurs. */ public void testReset() throws Exception { - List list = new ArrayList(Arrays.asList(new String[] { "a", "b", "c" })); - LoopingIterator loop = new LoopingIterator(list); + List list = Arrays.asList(new String[] { "a", "b", "c" }); + LoopingIterator loop = new LoopingIterator(list); assertEquals("a", loop.next()); assertEquals("b", loop.next()); @@ -189,8 +189,8 @@ public class TestLoopingIterator extends TestCase { * @throws Exception If something unexpected occurs. */ public void testSize() throws Exception { - List list = new ArrayList(Arrays.asList(new String[] { "a", "b", "c" })); - LoopingIterator loop = new LoopingIterator(list); + List list = new ArrayList(Arrays.asList(new String[] { "a", "b", "c" })); + LoopingIterator loop = new LoopingIterator(list); assertEquals(3, loop.size()); loop.next(); diff --git a/src/test/org/apache/commons/collections/iterators/TestLoopingListIterator.java b/src/test/org/apache/commons/collections/iterators/TestLoopingListIterator.java index 811f6c176..954d519de 100644 --- a/src/test/org/apache/commons/collections/iterators/TestLoopingListIterator.java +++ b/src/test/org/apache/commons/collections/iterators/TestLoopingListIterator.java @@ -47,7 +47,7 @@ public class TestLoopingListIterator extends TestCase { */ public void testConstructorEx() throws Exception { try { - new LoopingListIterator(null); + new LoopingListIterator(null); fail(); } catch (NullPointerException ex) { } @@ -57,8 +57,8 @@ public class TestLoopingListIterator extends TestCase { * Tests whether an empty looping list iterator works. */ public void testLooping0() throws Exception { - List list = new ArrayList(); - LoopingListIterator loop = new LoopingListIterator(list); + List list = new ArrayList(); + LoopingListIterator loop = new LoopingListIterator(list); assertFalse(loop.hasNext()); assertFalse(loop.hasPrevious()); @@ -80,8 +80,8 @@ public class TestLoopingListIterator extends TestCase { * one element. */ public void testLooping1() throws Exception { - List list = new ArrayList(Arrays.asList(new String[] { "a" })); - LoopingListIterator loop = new LoopingListIterator(list); // + List list = Arrays.asList(new String[] { "a" }); + LoopingListIterator loop = new LoopingListIterator(list); // assertTrue(loop.hasNext()); assertEquals("a", loop.next()); // @@ -107,8 +107,8 @@ public class TestLoopingListIterator extends TestCase { * elements. */ public void testLooping2() throws Exception { - List list = new ArrayList(Arrays.asList(new String[] { "a", "b" })); - LoopingListIterator loop = new LoopingListIterator(list); // b + List list = Arrays.asList(new String[] { "a", "b" }); + LoopingListIterator loop = new LoopingListIterator(list); // b assertTrue(loop.hasNext()); assertEquals("a", loop.next()); // a @@ -137,8 +137,8 @@ public class TestLoopingListIterator extends TestCase { * the begin/end boundary of the list. */ public void testJoggingNotOverBoundary() { - List list = new ArrayList(Arrays.asList(new String[] { "a", "b" })); - LoopingListIterator loop = new LoopingListIterator(list); // b + List list = Arrays.asList(new String[] { "a", "b" }); + LoopingListIterator loop = new LoopingListIterator(list); // b // Try jogging back and forth between the elements, but not // over the begin/end boundary. @@ -157,8 +157,8 @@ public class TestLoopingListIterator extends TestCase { * begin/end boundary of the list. */ public void testJoggingOverBoundary() { - List list = new ArrayList(Arrays.asList(new String[] { "a", "b" })); - LoopingListIterator loop = new LoopingListIterator(list); // b + List list = Arrays.asList(new String[] { "a", "b" }); + LoopingListIterator loop = new LoopingListIterator(list); // b // Try jogging back and forth between the elements, but not // over the begin/end boundary. @@ -175,8 +175,8 @@ public class TestLoopingListIterator extends TestCase { * Tests removing an element from a wrapped ArrayList. */ public void testRemovingElementsAndIteratingForward() { - List list = new ArrayList(Arrays.asList(new String[] { "a", "b", "c" })); - LoopingListIterator loop = new LoopingListIterator(list); // b c + List list = new ArrayList(Arrays.asList(new String[] { "a", "b", "c" })); + LoopingListIterator loop = new LoopingListIterator(list); // b c assertTrue(loop.hasNext()); assertEquals("a", loop.next()); // a c @@ -205,8 +205,8 @@ public class TestLoopingListIterator extends TestCase { * Tests removing an element from a wrapped ArrayList. */ public void testRemovingElementsAndIteratingBackwards() { - List list = new ArrayList(Arrays.asList(new String[] { "a", "b", "c" })); - LoopingListIterator loop = new LoopingListIterator(list); // b c + List list = new ArrayList(Arrays.asList(new String[] { "a", "b", "c" })); + LoopingListIterator loop = new LoopingListIterator(list); // b c assertTrue(loop.hasPrevious()); assertEquals("c", loop.previous()); // a b @@ -235,8 +235,8 @@ public class TestLoopingListIterator extends TestCase { * Tests the reset method. */ public void testReset() { - List list = new ArrayList(Arrays.asList(new String[] { "a", "b", "c" })); - LoopingListIterator loop = new LoopingListIterator(list); // b c + List list = Arrays.asList(new String[] { "a", "b", "c" }); + LoopingListIterator loop = new LoopingListIterator(list); // b c assertEquals("a", loop.next()); // a c assertEquals("b", loop.next()); // a b @@ -262,8 +262,8 @@ public class TestLoopingListIterator extends TestCase { * Tests the add method. */ public void testAdd() { - List list = new ArrayList(Arrays.asList(new String[] { "b", "e", "f" })); - LoopingListIterator loop = new LoopingListIterator(list); // e f + List list = new ArrayList(Arrays.asList(new String[] { "b", "e", "f" })); + LoopingListIterator loop = new LoopingListIterator(list); // e f loop.add("a"); // b e f assertEquals("b", loop.next()); // a e f @@ -287,8 +287,8 @@ public class TestLoopingListIterator extends TestCase { assertEquals("f", loop.next()); // b c d e f assertEquals("a", loop.next()); // a c d e f - list = new ArrayList(Arrays.asList(new String[] { "b", "e", "f" })); - loop = new LoopingListIterator(list); // e f + list = new ArrayList(Arrays.asList(new String[] { "b", "e", "f" })); + loop = new LoopingListIterator(list); // e f loop.add("a"); // a e f assertEquals("a", loop.previous()); // a b e @@ -316,8 +316,8 @@ public class TestLoopingListIterator extends TestCase { * Tests nextIndex and previousIndex. */ public void testNextAndPreviousIndex() { - List list = new ArrayList(Arrays.asList(new String[] { "a", "b", "c" })); - LoopingListIterator loop = new LoopingListIterator(list); // b c + List list = Arrays.asList(new String[] { "a", "b", "c" }); + LoopingListIterator loop = new LoopingListIterator(list); // b c assertEquals(0, loop.nextIndex()); assertEquals(2, loop.previousIndex()); @@ -347,8 +347,8 @@ public class TestLoopingListIterator extends TestCase { * Tests using the set method to change elements. */ public void testSet() { - List list = new ArrayList(Arrays.asList(new String[] { "q", "r", "z" })); - LoopingListIterator loop = new LoopingListIterator(list); // r z + List list = Arrays.asList(new String[] { "q", "r", "z" }); + LoopingListIterator loop = new LoopingListIterator(list); // r z assertEquals("z", loop.previous()); // q r loop.set("c"); // q r diff --git a/src/test/org/apache/commons/collections/iterators/TestObjectArrayIterator.java b/src/test/org/apache/commons/collections/iterators/TestObjectArrayIterator.java index a9f0f31b3..797cea854 100644 --- a/src/test/org/apache/commons/collections/iterators/TestObjectArrayIterator.java +++ b/src/test/org/apache/commons/collections/iterators/TestObjectArrayIterator.java @@ -32,7 +32,7 @@ import junit.framework.TestSuite; * @author Morgan Delagrange * @author Stephen Colebourne */ -public class TestObjectArrayIterator extends AbstractTestIterator { +public class TestObjectArrayIterator extends AbstractTestIterator { protected String[] testArray = { "One", "Two", "Three" }; @@ -44,28 +44,30 @@ public class TestObjectArrayIterator extends AbstractTestIterator { super(testName); } - public Iterator makeEmptyIterator() { - return new ObjectArrayIterator(new Object[0]); + @SuppressWarnings("unchecked") + public ObjectArrayIterator makeEmptyIterator() { + return new ObjectArrayIterator((E[]) new Object[0]); } - public Iterator makeFullIterator() { - return new ObjectArrayIterator(testArray); + @SuppressWarnings("unchecked") + public ObjectArrayIterator makeObject() { + return new ObjectArrayIterator((E[]) testArray); } - public ObjectArrayIterator makeArrayIterator() { - return new ObjectArrayIterator(); + public ObjectArrayIterator makeArrayIterator() { + return new ObjectArrayIterator(); } - public ObjectArrayIterator makeArrayIterator(Object[] array) { - return new ObjectArrayIterator(array); + public ObjectArrayIterator makeArrayIterator(E[] array) { + return new ObjectArrayIterator(array); } - public ObjectArrayIterator makeArrayIterator(Object[] array, int index) { - return new ObjectArrayIterator(array, index); + public ObjectArrayIterator makeArrayIterator(E[] array, int index) { + return new ObjectArrayIterator(array, index); } - public ObjectArrayIterator makeArrayIterator(Object[] array, int start, int end) { - return new ObjectArrayIterator(array, start, end); + public ObjectArrayIterator makeArrayIterator(E[] array, int start, int end) { + return new ObjectArrayIterator(array, start, end); } public boolean supportsRemove() { @@ -73,10 +75,10 @@ public class TestObjectArrayIterator extends AbstractTestIterator { } public void testIterator() { - Iterator iter = (Iterator) makeFullIterator(); + Iterator iter = makeObject(); for (int i = 0; i < testArray.length; i++) { Object testValue = testArray[i]; - Object iterValue = iter.next(); + E iterValue = iter.next(); assertEquals("Iteration value is correct", testValue, iterValue); } @@ -84,7 +86,7 @@ public class TestObjectArrayIterator extends AbstractTestIterator { assertTrue("Iterator should now be empty", !iter.hasNext()); try { - Object testValue = iter.next(); + iter.next(); } catch (Exception e) { assertTrue( "NoSuchElementException must be thrown", @@ -94,14 +96,14 @@ public class TestObjectArrayIterator extends AbstractTestIterator { public void testNullArray() { try { - Iterator iter = makeArrayIterator(null); + makeArrayIterator(null); fail("Constructor should throw a NullPointerException when constructed with a null array"); } catch (NullPointerException e) { // expected } - ObjectArrayIterator iter = makeArrayIterator(); + ObjectArrayIterator iter = makeArrayIterator(); try { iter.setArray(null); @@ -111,18 +113,20 @@ public class TestObjectArrayIterator extends AbstractTestIterator { } } + @SuppressWarnings("unchecked") public void testDoubleSet() { - ObjectArrayIterator it = makeArrayIterator(); - it.setArray(new String[0]); + ObjectArrayIterator it = makeArrayIterator(); + it.setArray((E[]) new String[0]); try { - it.setArray(new String[0]); + it.setArray((E[]) new String[0]); fail(); } catch (IllegalStateException ex) { } } + @SuppressWarnings("unchecked") public void testReset() { - ObjectArrayIterator it = makeArrayIterator(testArray); + ObjectArrayIterator it = makeArrayIterator((E[]) testArray); it.next(); it.reset(); assertEquals("One", it.next()); diff --git a/src/test/org/apache/commons/collections/iterators/TestObjectArrayListIterator.java b/src/test/org/apache/commons/collections/iterators/TestObjectArrayListIterator.java index e6c1f3623..ccd29ff12 100644 --- a/src/test/org/apache/commons/collections/iterators/TestObjectArrayListIterator.java +++ b/src/test/org/apache/commons/collections/iterators/TestObjectArrayListIterator.java @@ -17,7 +17,6 @@ package org.apache.commons.collections.iterators; import java.util.Arrays; -import java.util.Iterator; import java.util.ListIterator; import java.util.NoSuchElementException; @@ -31,7 +30,7 @@ import junit.framework.TestSuite; * * @author Neil O'Toole */ -public class TestObjectArrayListIterator extends TestObjectArrayIterator { +public class TestObjectArrayListIterator extends TestObjectArrayIterator { public TestObjectArrayListIterator(String testName) { super(testName); @@ -41,16 +40,18 @@ public class TestObjectArrayListIterator extends TestObjectArrayIterator { return new TestSuite(TestObjectArrayListIterator.class); } - public Iterator makeEmptyIterator() { - return new ObjectArrayListIterator(new Object[0]); + @SuppressWarnings("unchecked") + public ObjectArrayListIterator makeEmptyIterator() { + return new ObjectArrayListIterator((E[]) new Object[0]); } - public Iterator makeFullIterator() { - return new ObjectArrayListIterator(testArray); + @SuppressWarnings("unchecked") + public ObjectArrayListIterator makeObject() { + return new ObjectArrayListIterator((E[]) testArray); } - public ListIterator makeArrayListIterator(Object[] array) { - return new ObjectArrayListIterator(array); + public ObjectArrayListIterator makeArrayListIterator(E[] array) { + return new ObjectArrayListIterator(array); } /** @@ -58,7 +59,7 @@ public class TestObjectArrayListIterator extends TestObjectArrayIterator { * previous(). */ public void testListIterator() { - ListIterator iter = (ListIterator) makeFullIterator(); + ListIterator iter = makeObject(); // TestArrayIterator#testIterator() has already tested the iterator forward, // now we need to test it in reverse @@ -78,7 +79,7 @@ public class TestObjectArrayListIterator extends TestObjectArrayIterator { assertTrue("Iterator should now be empty", !iter.hasPrevious()); try { - Object testValue = iter.previous(); + iter.previous(); } catch (Exception e) { assertTrue( "NoSuchElementException must be thrown", @@ -90,27 +91,28 @@ public class TestObjectArrayListIterator extends TestObjectArrayIterator { /** * Tests the {@link java.util.ListIterator#set} operation. */ + @SuppressWarnings("unchecked") public void testListIteratorSet() { String[] testData = new String[] { "a", "b", "c" }; String[] result = new String[] { "0", "1", "2" }; - ListIterator iter = (ListIterator) makeArrayListIterator(testData); + ListIterator iter = makeArrayListIterator((E[]) testData); int x = 0; while (iter.hasNext()) { iter.next(); - iter.set(Integer.toString(x)); + iter.set((E) Integer.toString(x)); x++; } assertTrue("The two arrays should have the same value, i.e. {0,1,2}", Arrays.equals(testData, result)); // a call to set() before a call to next() or previous() should throw an IllegalStateException - iter = makeArrayListIterator(testArray); + iter = makeArrayListIterator((E[]) testArray); try { - iter.set("should fail"); + iter.set((E) "should fail"); fail("ListIterator#set should fail if next() or previous() have not yet been called."); } catch (IllegalStateException e) { // expected diff --git a/src/test/org/apache/commons/collections/iterators/TestObjectArrayListIterator2.java b/src/test/org/apache/commons/collections/iterators/TestObjectArrayListIterator2.java index 410d67516..9ef2d3105 100644 --- a/src/test/org/apache/commons/collections/iterators/TestObjectArrayListIterator2.java +++ b/src/test/org/apache/commons/collections/iterators/TestObjectArrayListIterator2.java @@ -16,8 +16,6 @@ */ package org.apache.commons.collections.iterators; -import java.util.ListIterator; - import junit.framework.Test; import junit.framework.TestSuite; @@ -28,10 +26,10 @@ import junit.framework.TestSuite; * * @author Stephen Colebourne */ -public class TestObjectArrayListIterator2 extends AbstractTestListIterator { +public class TestObjectArrayListIterator2 extends AbstractTestListIterator { protected String[] testArray = { "One", "Two", "Three" }; - + public TestObjectArrayListIterator2(String testName) { super(testName); } @@ -40,22 +38,24 @@ public class TestObjectArrayListIterator2 extends AbstractTestListIterator { return new TestSuite(TestObjectArrayListIterator2.class); } - public ListIterator makeEmptyListIterator() { - return new ObjectArrayListIterator(new Object[0]); + @SuppressWarnings("unchecked") + public ObjectArrayListIterator makeEmptyIterator() { + return new ObjectArrayListIterator((E[]) new Object[0]); } - public ListIterator makeFullListIterator() { - return new ObjectArrayListIterator(testArray); + @SuppressWarnings("unchecked") + public ObjectArrayListIterator makeObject() { + return new ObjectArrayListIterator((E[]) testArray); } - public ListIterator makeArrayListIterator(Object[] array) { - return new ObjectArrayListIterator(array); + public ObjectArrayListIterator makeArrayListIterator(E[] array) { + return new ObjectArrayListIterator(array); } public boolean supportsAdd() { return false; } - + public boolean supportsRemove() { return false; } diff --git a/src/test/org/apache/commons/collections/iterators/TestObjectGraphIterator.java b/src/test/org/apache/commons/collections/iterators/TestObjectGraphIterator.java index 60c38a323..1aaab9b60 100644 --- a/src/test/org/apache/commons/collections/iterators/TestObjectGraphIterator.java +++ b/src/test/org/apache/commons/collections/iterators/TestObjectGraphIterator.java @@ -35,14 +35,14 @@ import org.apache.commons.collections.Transformer; * * @author Stephen Colebourne */ -public class TestObjectGraphIterator extends AbstractTestIterator { +public class TestObjectGraphIterator extends AbstractTestIterator { protected String[] testArray = { "One", "Two", "Three", "Four", "Five", "Six" }; - protected List list1 = null; - protected List list2 = null; - protected List list3 = null; - protected List iteratorList = null; + protected List list1 = null; + protected List list2 = null; + protected List list3 = null; + protected List> iteratorList = null; public TestObjectGraphIterator(String testName) { super(testName); @@ -57,34 +57,34 @@ public class TestObjectGraphIterator extends AbstractTestIterator { } public void setUp() { - list1 = new ArrayList(); + list1 = new ArrayList(); list1.add("One"); list1.add("Two"); list1.add("Three"); - list2 = new ArrayList(); + list2 = new ArrayList(); list2.add("Four"); - list3 = new ArrayList(); + list3 = new ArrayList(); list3.add("Five"); list3.add("Six"); - iteratorList = new ArrayList(); + iteratorList = new ArrayList>(); iteratorList.add(list1.iterator()); iteratorList.add(list2.iterator()); iteratorList.add(list3.iterator()); } //----------------------------------------------------------------------- - public Iterator makeEmptyIterator() { - ArrayList list = new ArrayList(); - return new ObjectGraphIterator(list.iterator(), null); + public ObjectGraphIterator makeEmptyIterator() { + ArrayList list = new ArrayList(); + return new ObjectGraphIterator(list.iterator()); } - public Iterator makeFullIterator() { - return new ObjectGraphIterator(iteratorList.iterator(), null); + public ObjectGraphIterator makeObject() { + return new ObjectGraphIterator(iteratorList.iterator()); } //----------------------------------------------------------------------- public void testIteratorConstructor_null1() { - Iterator it = new ObjectGraphIterator(null); + Iterator it = new ObjectGraphIterator(null); assertEquals(false, it.hasNext()); try { @@ -100,7 +100,7 @@ public class TestObjectGraphIterator extends AbstractTestIterator { } public void testIteratorConstructor_null_next() { - Iterator it = new ObjectGraphIterator(null); + Iterator it = new ObjectGraphIterator(null); try { it.next(); fail(); @@ -109,7 +109,7 @@ public class TestObjectGraphIterator extends AbstractTestIterator { } public void testIteratorConstructor_null_remove() { - Iterator it = new ObjectGraphIterator(null); + Iterator it = new ObjectGraphIterator(null); try { it.remove(); fail(); @@ -119,8 +119,8 @@ public class TestObjectGraphIterator extends AbstractTestIterator { //----------------------------------------------------------------------- public void testIteratorConstructorIteration_Empty() { - List iteratorList = new ArrayList(); - Iterator it = new ObjectGraphIterator(iteratorList.iterator()); + List> iteratorList = new ArrayList>(); + Iterator it = new ObjectGraphIterator(iteratorList.iterator()); assertEquals(false, it.hasNext()); try { @@ -136,11 +136,11 @@ public class TestObjectGraphIterator extends AbstractTestIterator { } public void testIteratorConstructorIteration_Simple() { - List iteratorList = new ArrayList(); + List> iteratorList = new ArrayList>(); iteratorList.add(list1.iterator()); iteratorList.add(list2.iterator()); iteratorList.add(list3.iterator()); - Iterator it = new ObjectGraphIterator(iteratorList.iterator()); + Iterator it = new ObjectGraphIterator(iteratorList.iterator()); for (int i = 0; i < 6; i++) { assertEquals(true, it.hasNext()); @@ -155,11 +155,11 @@ public class TestObjectGraphIterator extends AbstractTestIterator { } public void testIteratorConstructorIteration_SimpleNoHasNext() { - List iteratorList = new ArrayList(); + List> iteratorList = new ArrayList>(); iteratorList.add(list1.iterator()); iteratorList.add(list2.iterator()); iteratorList.add(list3.iterator()); - Iterator it = new ObjectGraphIterator(iteratorList.iterator()); + Iterator it = new ObjectGraphIterator(iteratorList.iterator()); for (int i = 0; i < 6; i++) { assertEquals(testArray[i], it.next()); @@ -172,15 +172,15 @@ public class TestObjectGraphIterator extends AbstractTestIterator { } public void testIteratorConstructorIteration_WithEmptyIterators() { - List iteratorList = new ArrayList(); - iteratorList.add(IteratorUtils.EMPTY_ITERATOR); + List> iteratorList = new ArrayList>(); + iteratorList.add(IteratorUtils.emptyIterator()); iteratorList.add(list1.iterator()); - iteratorList.add(IteratorUtils.EMPTY_ITERATOR); + iteratorList.add(IteratorUtils.emptyIterator()); iteratorList.add(list2.iterator()); - iteratorList.add(IteratorUtils.EMPTY_ITERATOR); + iteratorList.add(IteratorUtils.emptyIterator()); iteratorList.add(list3.iterator()); - iteratorList.add(IteratorUtils.EMPTY_ITERATOR); - Iterator it = new ObjectGraphIterator(iteratorList.iterator()); + iteratorList.add(IteratorUtils.emptyIterator()); + Iterator it = new ObjectGraphIterator(iteratorList.iterator()); for (int i = 0; i < 6; i++) { assertEquals(true, it.hasNext()); @@ -195,11 +195,11 @@ public class TestObjectGraphIterator extends AbstractTestIterator { } public void testIteratorConstructorRemove() { - List iteratorList = new ArrayList(); + List> iteratorList = new ArrayList>(); iteratorList.add(list1.iterator()); iteratorList.add(list2.iterator()); iteratorList.add(list3.iterator()); - Iterator it = new ObjectGraphIterator(iteratorList.iterator()); + Iterator it = new ObjectGraphIterator(iteratorList.iterator()); for (int i = 0; i < 6; i++) { assertEquals(testArray[i], it.next()); @@ -213,11 +213,11 @@ public class TestObjectGraphIterator extends AbstractTestIterator { //----------------------------------------------------------------------- public void testIteration_IteratorOfIterators() { - List iteratorList = new ArrayList(); + List> iteratorList = new ArrayList>(); iteratorList.add(list1.iterator()); iteratorList.add(list2.iterator()); iteratorList.add(list3.iterator()); - Iterator it = new ObjectGraphIterator(iteratorList.iterator(), null); + Iterator it = new ObjectGraphIterator(iteratorList.iterator(), null); for (int i = 0; i < 6; i++) { assertEquals(true, it.hasNext()); @@ -227,15 +227,15 @@ public class TestObjectGraphIterator extends AbstractTestIterator { } public void testIteration_IteratorOfIteratorsWithEmptyIterators() { - List iteratorList = new ArrayList(); - iteratorList.add(IteratorUtils.EMPTY_ITERATOR); + List> iteratorList = new ArrayList>(); + iteratorList.add(IteratorUtils.emptyIterator()); iteratorList.add(list1.iterator()); - iteratorList.add(IteratorUtils.EMPTY_ITERATOR); + iteratorList.add(IteratorUtils.emptyIterator()); iteratorList.add(list2.iterator()); - iteratorList.add(IteratorUtils.EMPTY_ITERATOR); + iteratorList.add(IteratorUtils.emptyIterator()); iteratorList.add(list3.iterator()); - iteratorList.add(IteratorUtils.EMPTY_ITERATOR); - Iterator it = new ObjectGraphIterator(iteratorList.iterator(), null); + iteratorList.add(IteratorUtils.emptyIterator()); + Iterator it = new ObjectGraphIterator(iteratorList.iterator(), null); for (int i = 0; i < 6; i++) { assertEquals(true, it.hasNext()); @@ -246,7 +246,7 @@ public class TestObjectGraphIterator extends AbstractTestIterator { //----------------------------------------------------------------------- public void testIteration_RootNull() { - Iterator it = new ObjectGraphIterator(null, null); + Iterator it = new ObjectGraphIterator(null, null); assertEquals(false, it.hasNext()); try { @@ -263,7 +263,7 @@ public class TestObjectGraphIterator extends AbstractTestIterator { public void testIteration_RootNoTransformer() { Forest forest = new Forest(); - Iterator it = new ObjectGraphIterator(forest, null); + Iterator it = new ObjectGraphIterator(forest, null); assertEquals(true, it.hasNext()); assertSame(forest, it.next()); @@ -278,7 +278,7 @@ public class TestObjectGraphIterator extends AbstractTestIterator { public void testIteration_Transformed1() { Forest forest = new Forest(); Leaf l1 = forest.addTree().addBranch().addLeaf(); - Iterator it = new ObjectGraphIterator(forest, new LeafFinder()); + Iterator it = new ObjectGraphIterator(forest, new LeafFinder()); assertEquals(true, it.hasNext()); assertSame(l1, it.next()); @@ -298,7 +298,7 @@ public class TestObjectGraphIterator extends AbstractTestIterator { Branch b1 = forest.getTree(0).addBranch(); Branch b2 = forest.getTree(0).addBranch(); Branch b3 = forest.getTree(2).addBranch(); - Branch b4 = forest.getTree(2).addBranch(); + /* Branch b4 = */ forest.getTree(2).addBranch(); Branch b5 = forest.getTree(2).addBranch(); Leaf l1 = b1.addLeaf(); Leaf l2 = b1.addLeaf(); @@ -306,7 +306,7 @@ public class TestObjectGraphIterator extends AbstractTestIterator { Leaf l4 = b3.addLeaf(); Leaf l5 = b5.addLeaf(); - Iterator it = new ObjectGraphIterator(forest, new LeafFinder()); + Iterator it = new ObjectGraphIterator(forest, new LeafFinder()); assertEquals(true, it.hasNext()); assertSame(l1, it.next()); @@ -335,14 +335,14 @@ public class TestObjectGraphIterator extends AbstractTestIterator { Branch b2 = forest.getTree(1).addBranch(); Branch b3 = forest.getTree(2).addBranch(); Branch b4 = forest.getTree(2).addBranch(); - Branch b5 = forest.getTree(2).addBranch(); + /* Branch b5 = */ forest.getTree(2).addBranch(); Leaf l1 = b1.addLeaf(); Leaf l2 = b1.addLeaf(); Leaf l3 = b2.addLeaf(); Leaf l4 = b3.addLeaf(); Leaf l5 = b4.addLeaf(); - Iterator it = new ObjectGraphIterator(forest, new LeafFinder()); + Iterator it = new ObjectGraphIterator(forest, new LeafFinder()); assertEquals(true, it.hasNext()); assertSame(l1, it.next()); @@ -363,7 +363,7 @@ public class TestObjectGraphIterator extends AbstractTestIterator { } //----------------------------------------------------------------------- - static class LeafFinder implements Transformer { + static class LeafFinder implements Transformer { public Object transform(Object input) { if (input instanceof Forest) { return ((Forest) input).treeIterator(); @@ -383,7 +383,7 @@ public class TestObjectGraphIterator extends AbstractTestIterator { //----------------------------------------------------------------------- static class Forest { - List trees = new ArrayList(); + List trees = new ArrayList(); Tree addTree() { trees.add(new Tree()); @@ -394,13 +394,13 @@ public class TestObjectGraphIterator extends AbstractTestIterator { return (Tree) trees.get(index); } - Iterator treeIterator() { + Iterator treeIterator() { return trees.iterator(); } } static class Tree { - List branches = new ArrayList(); + List branches = new ArrayList(); Branch addBranch() { branches.add(new Branch()); @@ -411,13 +411,13 @@ public class TestObjectGraphIterator extends AbstractTestIterator { return (Branch) branches.get(index); } - Iterator branchIterator() { + Iterator branchIterator() { return branches.iterator(); } } static class Branch { - List leaves = new ArrayList(); + List leaves = new ArrayList(); Leaf addLeaf() { leaves.add(new Leaf()); @@ -428,7 +428,7 @@ public class TestObjectGraphIterator extends AbstractTestIterator { return (Leaf) leaves.get(index); } - Iterator leafIterator() { + Iterator leafIterator() { return leaves.iterator(); } } diff --git a/src/test/org/apache/commons/collections/iterators/TestReverseListIterator.java b/src/test/org/apache/commons/collections/iterators/TestReverseListIterator.java index 66ade090e..86203c533 100644 --- a/src/test/org/apache/commons/collections/iterators/TestReverseListIterator.java +++ b/src/test/org/apache/commons/collections/iterators/TestReverseListIterator.java @@ -33,7 +33,7 @@ import org.apache.commons.collections.ResettableListIterator; * * @version $Revision: $ $Date$ */ -public class TestReverseListIterator extends AbstractTestListIterator { +public class TestReverseListIterator extends AbstractTestListIterator { protected String[] testArray = { "One", "Two", "Three", "Four" }; @@ -50,33 +50,33 @@ public class TestReverseListIterator extends AbstractTestListIterator { super(testName); } - public ListIterator makeEmptyListIterator() { - List list = new ArrayList(); - return new ReverseListIterator(list); + public ListIterator makeEmptyIterator() { + return new ReverseListIterator(new ArrayList()); } - public ListIterator makeFullListIterator() { - List list = new ArrayList(Arrays.asList(testArray)); - return new ReverseListIterator(list); + @SuppressWarnings("unchecked") + public ReverseListIterator makeObject() { + List list = new ArrayList(Arrays.asList((E[]) testArray)); + return new ReverseListIterator(list); } // overrides //----------------------------------------------------------------------- public void testEmptyListIteratorIsIndeedEmpty() { - ListIterator it = makeEmptyListIterator(); - + ListIterator it = makeEmptyIterator(); + assertEquals(false, it.hasNext()); assertEquals(-1, it.nextIndex()); // reversed index assertEquals(false, it.hasPrevious()); assertEquals(0, it.previousIndex()); // reversed index - + // next() should throw a NoSuchElementException try { it.next(); fail("NoSuchElementException must be thrown from empty ListIterator"); } catch (NoSuchElementException e) { } - + // previous() should throw a NoSuchElementException try { it.previous(); @@ -86,16 +86,16 @@ public class TestReverseListIterator extends AbstractTestListIterator { } public void testWalkForwardAndBack() { - ArrayList list = new ArrayList(); - ListIterator it = makeFullListIterator(); + ArrayList list = new ArrayList(); + ListIterator it = makeObject(); while (it.hasNext()) { list.add(it.next()); } - + // check state at end assertEquals(false, it.hasNext()); assertEquals(true, it.hasPrevious()); - + // this had to be commented out, as there is a bug in the JDK before JDK1.5 // where calling previous at the start of an iterator would push the cursor // back to an invalid negative value @@ -104,16 +104,16 @@ public class TestReverseListIterator extends AbstractTestListIterator { // fail("NoSuchElementException must be thrown from next at end of ListIterator"); // } catch (NoSuchElementException e) { // } - + // loop back through comparing for (int i = list.size() - 1; i >= 0; i--) { assertEquals("" + i, list.size() - i - 2, it.nextIndex()); // reversed index assertEquals(list.size() - i - 1, it.previousIndex()); // reversed index - + Object obj = list.get(i); assertEquals(obj, it.previous()); } - + // check state at start assertEquals(true, it.hasNext()); assertEquals(false, it.hasPrevious()); @@ -126,7 +126,7 @@ public class TestReverseListIterator extends AbstractTestListIterator { //----------------------------------------------------------------------- public void testReverse() { - ListIterator it = makeFullListIterator(); + ListIterator it = makeObject(); assertEquals(true, it.hasNext()); assertEquals(3, it.nextIndex()); assertEquals(false, it.hasPrevious()); @@ -158,7 +158,7 @@ public class TestReverseListIterator extends AbstractTestListIterator { } public void testReset() { - ResettableListIterator it = (ResettableListIterator) makeFullListIterator(); + ResettableListIterator it = makeObject(); assertEquals("Four", it.next()); it.reset(); assertEquals("Four", it.next()); diff --git a/src/test/org/apache/commons/collections/iterators/TestSingletonIterator.java b/src/test/org/apache/commons/collections/iterators/TestSingletonIterator.java index 8ddca3adb..7c22098ae 100644 --- a/src/test/org/apache/commons/collections/iterators/TestSingletonIterator.java +++ b/src/test/org/apache/commons/collections/iterators/TestSingletonIterator.java @@ -32,32 +32,33 @@ import org.apache.commons.collections.ResettableIterator; * * @author James Strachan */ -public class TestSingletonIterator extends AbstractTestIterator { +public class TestSingletonIterator extends AbstractTestIterator { private static final Object testValue = "foo"; - + public static Test suite() { return new TestSuite(TestSingletonIterator.class); } - + public TestSingletonIterator(String testName) { super(testName); } - + /** - * Returns a SingletonIterator from which + * Returns a SingletonIterator from which * the element has already been removed. */ - public Iterator makeEmptyIterator() { - SingletonIterator iter = (SingletonIterator)makeFullIterator(); + public SingletonIterator makeEmptyIterator() { + SingletonIterator iter = makeObject(); iter.next(); - iter.remove(); + iter.remove(); iter.reset(); return iter; } - public Iterator makeFullIterator() { - return new SingletonIterator( testValue ); + @SuppressWarnings("unchecked") + public SingletonIterator makeObject() { + return new SingletonIterator((E) testValue); } public boolean supportsRemove() { @@ -69,10 +70,10 @@ public class TestSingletonIterator extends AbstractTestIterator { } public void testIterator() { - Iterator iter = (Iterator) makeObject(); + Iterator iter = makeObject(); assertTrue("Iterator has a first item", iter.hasNext()); - Object iterValue = iter.next(); + E iterValue = iter.next(); assertEquals("Iteration value is correct", testValue, iterValue); assertTrue("Iterator should now be empty", !iter.hasNext()); @@ -85,33 +86,34 @@ public class TestSingletonIterator extends AbstractTestIterator { e.getClass().equals((new NoSuchElementException()).getClass())); } } - + + @SuppressWarnings("unchecked") public void testSingletonIteratorRemove() { - ResettableIterator iter = new SingletonIterator("xyzzy"); + ResettableIterator iter = new SingletonIterator((E) "xyzzy"); assertTrue(iter.hasNext()); assertEquals("xyzzy",iter.next()); iter.remove(); iter.reset(); assertTrue(! iter.hasNext()); } - + public void testReset() { - ResettableIterator it = (ResettableIterator) makeObject(); - + ResettableIterator it = makeObject(); + assertEquals(true, it.hasNext()); assertEquals(testValue, it.next()); assertEquals(false, it.hasNext()); it.reset(); - + assertEquals(true, it.hasNext()); assertEquals(testValue, it.next()); assertEquals(false, it.hasNext()); - + it.reset(); it.reset(); - + assertEquals(true, it.hasNext()); } - + } diff --git a/src/test/org/apache/commons/collections/iterators/TestSingletonIterator2.java b/src/test/org/apache/commons/collections/iterators/TestSingletonIterator2.java index 3de1016f2..f5cbf6ea7 100644 --- a/src/test/org/apache/commons/collections/iterators/TestSingletonIterator2.java +++ b/src/test/org/apache/commons/collections/iterators/TestSingletonIterator2.java @@ -32,7 +32,7 @@ import org.apache.commons.collections.ResettableIterator; * * @author James Strachan */ -public class TestSingletonIterator2 extends AbstractTestIterator { +public class TestSingletonIterator2 extends AbstractTestIterator { private static final Object testValue = "foo"; @@ -45,16 +45,18 @@ public class TestSingletonIterator2 extends AbstractTestIterator { } //----------------------------------------------------------------------- - public Iterator makeEmptyIterator() { - SingletonIterator iter = new SingletonIterator(testValue); + @SuppressWarnings("unchecked") + public SingletonIterator makeEmptyIterator() { + SingletonIterator iter = new SingletonIterator((E) testValue); iter.next(); iter.remove(); iter.reset(); return iter; } - public Iterator makeFullIterator() { - return new SingletonIterator(testValue, false); + @SuppressWarnings("unchecked") + public SingletonIterator makeObject() { + return new SingletonIterator((E) testValue, false); } public boolean supportsRemove() { @@ -67,10 +69,10 @@ public class TestSingletonIterator2 extends AbstractTestIterator { //----------------------------------------------------------------------- public void testIterator() { - Iterator iter = (Iterator) makeObject(); + Iterator iter = makeObject(); assertTrue("Iterator has a first item", iter.hasNext()); - Object iterValue = iter.next(); + E iterValue = iter.next(); assertEquals("Iteration value is correct", testValue, iterValue); assertTrue("Iterator should now be empty", !iter.hasNext()); @@ -85,7 +87,7 @@ public class TestSingletonIterator2 extends AbstractTestIterator { } public void testReset() { - ResettableIterator it = (ResettableIterator) makeObject(); + ResettableIterator it = makeObject(); assertEquals(true, it.hasNext()); assertEquals(testValue, it.next()); diff --git a/src/test/org/apache/commons/collections/iterators/TestUniqueFilterIterator.java b/src/test/org/apache/commons/collections/iterators/TestUniqueFilterIterator.java index 11614b26d..efe6d3056 100644 --- a/src/test/org/apache/commons/collections/iterators/TestUniqueFilterIterator.java +++ b/src/test/org/apache/commons/collections/iterators/TestUniqueFilterIterator.java @@ -34,13 +34,13 @@ import junit.framework.TestSuite; * @author Morgan Delagrange * @author Stephen Colebourne */ -public class TestUniqueFilterIterator extends AbstractTestIterator { +public class TestUniqueFilterIterator extends AbstractTestIterator { protected String[] testArray = { "One", "Two", "Three", "Four", "Five", "Six" }; - protected List list1 = null; + protected List list1 = null; public static Test suite() { return new TestSuite(TestUniqueFilterIterator.class); @@ -50,36 +50,36 @@ public class TestUniqueFilterIterator extends AbstractTestIterator { super(testName); } + @SuppressWarnings("unchecked") public void setUp() { - list1 = new ArrayList(); - list1.add("One"); - list1.add("Two"); - list1.add("Three"); - list1.add("Two"); - list1.add("One"); - list1.add("Four"); - list1.add("Five"); - list1.add("Five"); - list1.add("Six"); - list1.add("Five"); + list1 = new ArrayList(); + list1.add((E) "One"); + list1.add((E) "Two"); + list1.add((E) "Three"); + list1.add((E) "Two"); + list1.add((E) "One"); + list1.add((E) "Four"); + list1.add((E) "Five"); + list1.add((E) "Five"); + list1.add((E) "Six"); + list1.add((E) "Five"); } - public Iterator makeEmptyIterator() { - ArrayList list = new ArrayList(); - return new UniqueFilterIterator(list.iterator()); + public UniqueFilterIterator makeEmptyIterator() { + ArrayList list = new ArrayList(); + return new UniqueFilterIterator(list.iterator()); } - public Iterator makeFullIterator() { - Iterator i = list1.iterator(); - - return new UniqueFilterIterator(i); + public UniqueFilterIterator makeObject() { + Iterator i = list1.iterator(); + return new UniqueFilterIterator(i); } public void testIterator() { - Iterator iter = (Iterator) makeFullIterator(); - for ( int i = 0; i < testArray.length; i++ ) { + Iterator iter = makeObject(); + for (int i = 0; i < testArray.length; i++) { Object testValue = testArray[i]; - Object iterValue = iter.next(); + E iterValue = iter.next(); assertEquals( "Iteration value is correct", testValue, iterValue ); } @@ -87,7 +87,7 @@ public class TestUniqueFilterIterator extends AbstractTestIterator { assertTrue("Iterator should now be empty", ! iter.hasNext() ); try { - Object testValue = iter.next(); + iter.next(); } catch (Exception e) { assertTrue("NoSuchElementException must be thrown", e.getClass().equals((new NoSuchElementException()).getClass())); diff --git a/src/test/org/apache/commons/collections/iterators/TestUnmodifiableIterator.java b/src/test/org/apache/commons/collections/iterators/TestUnmodifiableIterator.java index a2ec3196a..05eac1645 100644 --- a/src/test/org/apache/commons/collections/iterators/TestUnmodifiableIterator.java +++ b/src/test/org/apache/commons/collections/iterators/TestUnmodifiableIterator.java @@ -34,10 +34,10 @@ import org.apache.commons.collections.Unmodifiable; * * @author Stephen Colebourne */ -public class TestUnmodifiableIterator extends AbstractTestIterator { +public class TestUnmodifiableIterator extends AbstractTestIterator { protected String[] testArray = { "One", "Two", "Three" }; - protected List testList = new ArrayList(Arrays.asList(testArray)); + protected List testList; public static Test suite() { return new TestSuite(TestUnmodifiableIterator.class); @@ -47,11 +47,21 @@ public class TestUnmodifiableIterator extends AbstractTestIterator { super(testName); } - public Iterator makeEmptyIterator() { - return UnmodifiableIterator.decorate(Collections.EMPTY_LIST.iterator()); + /** + * {@inheritDoc} + */ + @SuppressWarnings("unchecked") + @Override + protected void setUp() throws Exception { + super.setUp(); + testList = new ArrayList(Arrays.asList((E[]) testArray)); } - public Iterator makeFullIterator() { + public Iterator makeEmptyIterator() { + return UnmodifiableIterator.decorate(Collections.emptyList().iterator()); + } + + public Iterator makeObject() { return UnmodifiableIterator.decorate(testList.iterator()); } @@ -63,14 +73,14 @@ public class TestUnmodifiableIterator extends AbstractTestIterator { public void testIterator() { assertTrue(makeEmptyIterator() instanceof Unmodifiable); } - + public void testDecorateFactory() { - Iterator it = makeFullIterator(); + Iterator it = makeObject(); assertSame(it, UnmodifiableIterator.decorate(it)); - + it = testList.iterator(); assertTrue(it != UnmodifiableIterator.decorate(it)); - + try { UnmodifiableIterator.decorate(null); fail(); diff --git a/src/test/org/apache/commons/collections/iterators/TestUnmodifiableListIterator.java b/src/test/org/apache/commons/collections/iterators/TestUnmodifiableListIterator.java index 2b91e25fa..e7275e209 100644 --- a/src/test/org/apache/commons/collections/iterators/TestUnmodifiableListIterator.java +++ b/src/test/org/apache/commons/collections/iterators/TestUnmodifiableListIterator.java @@ -34,10 +34,10 @@ import org.apache.commons.collections.Unmodifiable; * * @author Stephen Colebourne */ -public class TestUnmodifiableListIterator extends AbstractTestListIterator { +public class TestUnmodifiableListIterator extends AbstractTestListIterator { protected String[] testArray = { "One", "Two", "Three" }; - protected List testList = new ArrayList(Arrays.asList(testArray)); + protected List testList; public static Test suite() { return new TestSuite(TestUnmodifiableListIterator.class); @@ -47,11 +47,21 @@ public class TestUnmodifiableListIterator extends AbstractTestListIterator { super(testName); } - public ListIterator makeEmptyListIterator() { - return UnmodifiableListIterator.decorate(Collections.EMPTY_LIST.listIterator()); + /** + * {@inheritDoc} + */ + @SuppressWarnings("unchecked") + @Override + protected void setUp() throws Exception { + super.setUp(); + testList = new ArrayList(Arrays.asList((E[]) testArray)); } - public ListIterator makeFullListIterator() { + public ListIterator makeEmptyIterator() { + return UnmodifiableListIterator.decorate(Collections.emptyList().listIterator()); + } + + public ListIterator makeObject() { return UnmodifiableListIterator.decorate(testList.listIterator()); } @@ -69,16 +79,16 @@ public class TestUnmodifiableListIterator extends AbstractTestListIterator { //----------------------------------------------------------------------- public void testListIterator() { - assertTrue(makeEmptyListIterator() instanceof Unmodifiable); + assertTrue(makeEmptyIterator() instanceof Unmodifiable); } - + public void testDecorateFactory() { - ListIterator it = makeFullListIterator(); + ListIterator it = makeObject(); assertSame(it, UnmodifiableListIterator.decorate(it)); - + it = testList.listIterator(); assertTrue(it != UnmodifiableListIterator.decorate(it)); - + try { UnmodifiableListIterator.decorate(null); fail(); diff --git a/src/test/org/apache/commons/collections/iterators/TestUnmodifiableMapIterator.java b/src/test/org/apache/commons/collections/iterators/TestUnmodifiableMapIterator.java index 1ef37b0d6..050095515 100644 --- a/src/test/org/apache/commons/collections/iterators/TestUnmodifiableMapIterator.java +++ b/src/test/org/apache/commons/collections/iterators/TestUnmodifiableMapIterator.java @@ -22,7 +22,7 @@ import java.util.Map; import junit.framework.Test; import junit.framework.TestSuite; -import org.apache.commons.collections.BidiMap; +import org.apache.commons.collections.IterableMap; import org.apache.commons.collections.MapIterator; import org.apache.commons.collections.Unmodifiable; import org.apache.commons.collections.bidimap.DualHashBidiMap; @@ -34,7 +34,7 @@ import org.apache.commons.collections.bidimap.DualHashBidiMap; * * @author Stephen Colebourne */ -public class TestUnmodifiableMapIterator extends AbstractTestMapIterator { +public class TestUnmodifiableMapIterator extends AbstractTestMapIterator { public static Test suite() { return new TestSuite(TestUnmodifiableMapIterator.class); @@ -44,27 +44,29 @@ public class TestUnmodifiableMapIterator extends AbstractTestMapIterator { super(testName); } - public MapIterator makeEmptyMapIterator() { - return UnmodifiableMapIterator.decorate(new DualHashBidiMap().mapIterator()); + public MapIterator makeEmptyIterator() { + return UnmodifiableMapIterator.decorate(new DualHashBidiMap().mapIterator()); } - public MapIterator makeFullMapIterator() { - return UnmodifiableMapIterator.decorate(((BidiMap) getMap()).mapIterator()); + public MapIterator makeObject() { + return UnmodifiableMapIterator.decorate(getMap().mapIterator()); } - - public Map getMap() { - Map testMap = new DualHashBidiMap(); - testMap.put("A", "a"); - testMap.put("B", "b"); - testMap.put("C", "c"); + + @SuppressWarnings("unchecked") + public IterableMap getMap() { + IterableMap testMap = new DualHashBidiMap(); + testMap.put((K) "A", (V) "a"); + testMap.put((K) "B", (V)"b"); + testMap.put((K) "C", (V) "c"); return testMap; } - public Map getConfirmedMap() { - Map testMap = new HashMap(); - testMap.put("A", "a"); - testMap.put("B", "b"); - testMap.put("C", "c"); + @SuppressWarnings("unchecked") + public Map getConfirmedMap() { + Map testMap = new HashMap(); + testMap.put((K) "A", (V) "a"); + testMap.put((K) "B", (V)"b"); + testMap.put((K) "C", (V) "c"); return testMap; } @@ -75,19 +77,19 @@ public class TestUnmodifiableMapIterator extends AbstractTestMapIterator { public boolean supportsSetValue() { return false; } - + //----------------------------------------------------------------------- public void testMapIterator() { - assertTrue(makeEmptyMapIterator() instanceof Unmodifiable); + assertTrue(makeEmptyIterator() instanceof Unmodifiable); } - + public void testDecorateFactory() { - MapIterator it = makeFullMapIterator(); + MapIterator it = makeObject(); assertSame(it, UnmodifiableMapIterator.decorate(it)); - - it = ((BidiMap) getMap()).mapIterator() ; + + it = getMap().mapIterator() ; assertTrue(it != UnmodifiableMapIterator.decorate(it)); - + try { UnmodifiableMapIterator.decorate(null); fail(); diff --git a/src/test/org/apache/commons/collections/iterators/TestUnmodifiableOrderedMapIterator.java b/src/test/org/apache/commons/collections/iterators/TestUnmodifiableOrderedMapIterator.java index ef6993b89..9dcb26d36 100644 --- a/src/test/org/apache/commons/collections/iterators/TestUnmodifiableOrderedMapIterator.java +++ b/src/test/org/apache/commons/collections/iterators/TestUnmodifiableOrderedMapIterator.java @@ -23,7 +23,6 @@ import java.util.TreeMap; import junit.framework.Test; import junit.framework.TestSuite; -import org.apache.commons.collections.MapIterator; import org.apache.commons.collections.OrderedMap; import org.apache.commons.collections.OrderedMapIterator; import org.apache.commons.collections.Unmodifiable; @@ -36,7 +35,7 @@ import org.apache.commons.collections.map.ListOrderedMap; * * @author Stephen Colebourne */ -public class TestUnmodifiableOrderedMapIterator extends AbstractTestOrderedMapIterator { +public class TestUnmodifiableOrderedMapIterator extends AbstractTestOrderedMapIterator { public static Test suite() { return new TestSuite(TestUnmodifiableOrderedMapIterator.class); @@ -46,29 +45,30 @@ public class TestUnmodifiableOrderedMapIterator extends AbstractTestOrderedMapIt super(testName); } - public MapIterator makeEmptyMapIterator() { + public OrderedMapIterator makeEmptyIterator() { return UnmodifiableOrderedMapIterator.decorate( - ListOrderedMap.decorate(new HashMap()).orderedMapIterator()); + ListOrderedMap.decorate(new HashMap()).mapIterator()); } - public MapIterator makeFullMapIterator() { - return UnmodifiableOrderedMapIterator.decorate( - ((OrderedMap) getMap()).orderedMapIterator()); + public OrderedMapIterator makeObject() { + return UnmodifiableOrderedMapIterator.decorate(getMap().mapIterator()); } - - public Map getMap() { - Map testMap = ListOrderedMap.decorate(new HashMap()); - testMap.put("A", "a"); - testMap.put("B", "b"); - testMap.put("C", "c"); + + @SuppressWarnings("unchecked") + public OrderedMap getMap() { + OrderedMap testMap = ListOrderedMap.decorate(new HashMap()); + testMap.put((K) "A", (V) "a"); + testMap.put((K) "B", (V) "b"); + testMap.put((K) "C", (V) "c"); return testMap; } - public Map getConfirmedMap() { - Map testMap = new TreeMap(); - testMap.put("A", "a"); - testMap.put("B", "b"); - testMap.put("C", "c"); + @SuppressWarnings("unchecked") + public Map getConfirmedMap() { + Map testMap = new TreeMap(); + testMap.put((K) "A", (V) "a"); + testMap.put((K) "B", (V) "b"); + testMap.put((K) "C", (V) "c"); return testMap; } @@ -79,19 +79,19 @@ public class TestUnmodifiableOrderedMapIterator extends AbstractTestOrderedMapIt public boolean supportsSetValue() { return false; } - + //----------------------------------------------------------------------- public void testOrderedMapIterator() { - assertTrue(makeEmptyOrderedMapIterator() instanceof Unmodifiable); + assertTrue(makeEmptyIterator() instanceof Unmodifiable); } - + public void testDecorateFactory() { - OrderedMapIterator it = makeFullOrderedMapIterator(); + OrderedMapIterator it = makeObject(); assertSame(it, UnmodifiableOrderedMapIterator.decorate(it)); - - it = ((OrderedMap) getMap()).orderedMapIterator() ; + + it = getMap().mapIterator() ; assertTrue(it != UnmodifiableOrderedMapIterator.decorate(it)); - + try { UnmodifiableOrderedMapIterator.decorate(null); fail(); diff --git a/src/test/org/apache/commons/collections/keyvalue/AbstractTestMapEntry.java b/src/test/org/apache/commons/collections/keyvalue/AbstractTestMapEntry.java index 278fcf77a..227077dae 100644 --- a/src/test/org/apache/commons/collections/keyvalue/AbstractTestMapEntry.java +++ b/src/test/org/apache/commons/collections/keyvalue/AbstractTestMapEntry.java @@ -33,7 +33,7 @@ import junit.framework.TestCase; * * @author Neil O'Toole */ -public abstract class AbstractTestMapEntry extends TestCase { +public abstract class AbstractTestMapEntry extends TestCase { protected final String key = "name"; protected final String value = "duke"; @@ -53,7 +53,7 @@ public abstract class AbstractTestMapEntry extends TestCase { * This implementation simply calls {@link #makeMapEntry(Object, Object)} * with null for key and value. Subclasses can override this method if desired. */ - public Map.Entry makeMapEntry() { + public Map.Entry makeMapEntry() { return makeMapEntry(null, null); } @@ -62,32 +62,33 @@ public abstract class AbstractTestMapEntry extends TestCase { * Subclasses should override this method to return a Map.Entry * of the type being tested. */ - public abstract Map.Entry makeMapEntry(Object key, Object value); + public abstract Map.Entry makeMapEntry(K key, V value); /** * Makes a Map.Entry of a type that's known to work correctly. */ - public Map.Entry makeKnownMapEntry() { + public Map.Entry makeKnownMapEntry() { return makeKnownMapEntry(null, null); } /** * Makes a Map.Entry of a type that's known to work correctly. */ - public Map.Entry makeKnownMapEntry(Object key, Object value) { - Map map = new HashMap(1); + public Map.Entry makeKnownMapEntry(K key, V value) { + Map map = new HashMap(1); map.put(key, value); - Map.Entry entry = (Map.Entry) map.entrySet().iterator().next(); + Map.Entry entry = map.entrySet().iterator().next(); return entry; } //----------------------------------------------------------------------- + @SuppressWarnings("unchecked") public void testAccessorsAndMutators() { - Map.Entry entry = makeMapEntry(key, value); + Map.Entry entry = makeMapEntry((K) key, (V) value); assertTrue(entry.getKey() == key); - entry.setValue(value); + entry.setValue((V) value); assertTrue(entry.getValue() == value); // check that null doesn't do anything funny @@ -105,15 +106,16 @@ public abstract class AbstractTestMapEntry extends TestCase { * */ + @SuppressWarnings("unchecked") public void testSelfReferenceHandling() { // test that #setValue does not permit // the MapEntry to contain itself (and thus cause infinite recursion // in #hashCode and #toString) - Map.Entry entry = makeMapEntry(); + Map.Entry entry = makeMapEntry(); try { - entry.setValue(entry); + entry.setValue((V) entry); fail("Should throw an IllegalArgumentException"); } catch (IllegalArgumentException iae) { // expected to happen... @@ -129,10 +131,11 @@ public abstract class AbstractTestMapEntry extends TestCase { */ public abstract void testConstructors(); + @SuppressWarnings("unchecked") public void testEqualsAndHashCode() { // 1. test with object data - Map.Entry e1 = makeMapEntry(key, value); - Map.Entry e2 = makeKnownMapEntry(key, value); + Map.Entry e1 = makeMapEntry((K) key, (V) value); + Map.Entry e2 = makeKnownMapEntry((K) key, (V) value); assertTrue(e1.equals(e1)); assertTrue(e2.equals(e1)); @@ -149,8 +152,9 @@ public abstract class AbstractTestMapEntry extends TestCase { assertTrue(e1.hashCode() == e2.hashCode()); } + @SuppressWarnings("unchecked") public void testToString() { - Map.Entry entry = makeMapEntry(key, value); + Map.Entry entry = makeMapEntry((K) key, (V) value); assertTrue(entry.toString().equals(entry.getKey() + "=" + entry.getValue())); // test with nulls diff --git a/src/test/org/apache/commons/collections/keyvalue/TestDefaultKeyValue.java b/src/test/org/apache/commons/collections/keyvalue/TestDefaultKeyValue.java index efba6fd46..71156137f 100644 --- a/src/test/org/apache/commons/collections/keyvalue/TestDefaultKeyValue.java +++ b/src/test/org/apache/commons/collections/keyvalue/TestDefaultKeyValue.java @@ -31,7 +31,7 @@ import junit.framework.TestSuite; * * @author Neil O'Toole */ -public class TestDefaultKeyValue extends TestCase { +public class TestDefaultKeyValue extends TestCase { private final String key = "name"; private final String value = "duke"; @@ -60,8 +60,8 @@ public class TestDefaultKeyValue extends TestCase { * Subclasses should override this method to return a DefaultKeyValue * of the type being tested. */ - protected DefaultKeyValue makeDefaultKeyValue() { - return new DefaultKeyValue(null, null); + protected DefaultKeyValue makeDefaultKeyValue() { + return new DefaultKeyValue(null, null); } /** @@ -69,18 +69,19 @@ public class TestDefaultKeyValue extends TestCase { * Subclasses should override this method to return a DefaultKeyValue * of the type being tested. */ - protected DefaultKeyValue makeDefaultKeyValue(Object key, Object value) { - return new DefaultKeyValue(key, value); + protected DefaultKeyValue makeDefaultKeyValue(K key, V value) { + return new DefaultKeyValue(key, value); } //----------------------------------------------------------------------- + @SuppressWarnings("unchecked") public void testAccessorsAndMutators() { - DefaultKeyValue kv = makeDefaultKeyValue(); + DefaultKeyValue kv = makeDefaultKeyValue(); - kv.setKey(key); + kv.setKey((K) key); assertTrue(kv.getKey() == key); - kv.setValue(value); + kv.setValue((V) value); assertTrue(kv.getValue() == value); // check that null doesn't do anything funny @@ -92,15 +93,16 @@ public class TestDefaultKeyValue extends TestCase { } + @SuppressWarnings("unchecked") public void testSelfReferenceHandling() { // test that #setKey and #setValue do not permit // the KVP to contain itself (and thus cause infinite recursion // in #hashCode and #toString) - DefaultKeyValue kv = makeDefaultKeyValue(); + DefaultKeyValue kv = makeDefaultKeyValue(); try { - kv.setKey(kv); + kv.setKey((K) kv); fail("Should throw an IllegalArgumentException"); } catch (IllegalArgumentException iae) { // expected to happen... @@ -110,7 +112,7 @@ public class TestDefaultKeyValue extends TestCase { } try { - kv.setValue(kv); + kv.setValue((V) kv); fail("Should throw an IllegalArgumentException"); } catch (IllegalArgumentException iae) { // expected to happen... @@ -123,17 +125,18 @@ public class TestDefaultKeyValue extends TestCase { /** * Subclasses should override this method to test their own constructors. */ + @SuppressWarnings("unchecked") public void testConstructors() { // 1. test default constructor - DefaultKeyValue kv = new DefaultKeyValue(); + DefaultKeyValue kv = new DefaultKeyValue(); assertTrue(kv.getKey() == null && kv.getValue() == null); // 2. test key-value constructor - kv = new DefaultKeyValue(key, value); + kv = new DefaultKeyValue((K) key, (V) value); assertTrue(kv.getKey() == key && kv.getValue() == value); // 3. test copy constructor - DefaultKeyValue kv2 = new DefaultKeyValue(kv); + DefaultKeyValue kv2 = new DefaultKeyValue(kv); assertTrue(kv2.getKey() == key && kv2.getValue() == value); // test that the KVPs are independent @@ -143,11 +146,11 @@ public class TestDefaultKeyValue extends TestCase { assertTrue(kv2.getKey() == key && kv2.getValue() == value); // 4. test Map.Entry constructor - Map map = new HashMap(); - map.put(key, value); - Map.Entry entry = (Map.Entry) map.entrySet().iterator().next(); + Map map = new HashMap(); + map.put((K) key, (V) value); + Map.Entry entry = map.entrySet().iterator().next(); - kv = new DefaultKeyValue(entry); + kv = new DefaultKeyValue(entry); assertTrue(kv.getKey() == key && kv.getValue() == value); // test that the KVP is independent of the Map.Entry @@ -156,10 +159,11 @@ public class TestDefaultKeyValue extends TestCase { } + @SuppressWarnings("unchecked") public void testEqualsAndHashCode() { // 1. test with object data - DefaultKeyValue kv = makeDefaultKeyValue(key, value); - DefaultKeyValue kv2 = makeDefaultKeyValue(key, value); + DefaultKeyValue kv = makeDefaultKeyValue((K) key, (V) value); + DefaultKeyValue kv2 = makeDefaultKeyValue((K) key, (V) value); assertTrue(kv.equals(kv)); assertTrue(kv.equals(kv2)); @@ -174,8 +178,9 @@ public class TestDefaultKeyValue extends TestCase { assertTrue(kv.hashCode() == kv2.hashCode()); } + @SuppressWarnings("unchecked") public void testToString() { - DefaultKeyValue kv = makeDefaultKeyValue(key, value); + DefaultKeyValue kv = makeDefaultKeyValue((K) key, (V) value); assertTrue(kv.toString().equals(kv.getKey() + "=" + kv.getValue())); // test with nulls @@ -183,12 +188,13 @@ public class TestDefaultKeyValue extends TestCase { assertTrue(kv.toString().equals(kv.getKey() + "=" + kv.getValue())); } + @SuppressWarnings("unchecked") public void testToMapEntry() { - DefaultKeyValue kv = makeDefaultKeyValue(key, value); + DefaultKeyValue kv = makeDefaultKeyValue((K) key, (V) value); - Map map = new HashMap(); + Map map = new HashMap(); map.put(kv.getKey(), kv.getValue()); - Map.Entry entry = (Map.Entry) map.entrySet().iterator().next(); + Map.Entry entry = map.entrySet().iterator().next(); assertTrue(entry.equals(kv.toMapEntry())); assertTrue(entry.hashCode() == kv.hashCode()); diff --git a/src/test/org/apache/commons/collections/keyvalue/TestDefaultMapEntry.java b/src/test/org/apache/commons/collections/keyvalue/TestDefaultMapEntry.java index 6c9ac6704..fa3e4b6f2 100644 --- a/src/test/org/apache/commons/collections/keyvalue/TestDefaultMapEntry.java +++ b/src/test/org/apache/commons/collections/keyvalue/TestDefaultMapEntry.java @@ -31,11 +31,10 @@ import org.apache.commons.collections.KeyValue; * * @author Neil O'Toole */ -public class TestDefaultMapEntry extends AbstractTestMapEntry { +public class TestDefaultMapEntry extends AbstractTestMapEntry { public TestDefaultMapEntry(String testName) { super(testName); - } public static void main(String[] args) { @@ -52,8 +51,8 @@ public class TestDefaultMapEntry extends AbstractTestMapEntry { * Subclasses should override this method to return a Map.Entry * of the type being tested. */ - public Map.Entry makeMapEntry() { - return new DefaultMapEntry(null, null); + public Map.Entry makeMapEntry() { + return new DefaultMapEntry(null, null); } /** @@ -61,8 +60,8 @@ public class TestDefaultMapEntry extends AbstractTestMapEntry { * Subclasses should override this method to return a Map.Entry * of the type being tested. */ - public Map.Entry makeMapEntry(Object key, Object value) { - return new DefaultMapEntry(key, value); + public Map.Entry makeMapEntry(K key, V value) { + return new DefaultMapEntry(key, value); } //----------------------------------------------------------------------- @@ -70,19 +69,20 @@ public class TestDefaultMapEntry extends AbstractTestMapEntry { * Subclasses should override this method. * */ + @SuppressWarnings("unchecked") public void testConstructors() { // 1. test key-value constructor - Map.Entry entry = new DefaultMapEntry(key, value); + Map.Entry entry = new DefaultMapEntry((K) key, (V) value); assertSame(key, entry.getKey()); assertSame(value, entry.getValue()); // 2. test pair constructor - KeyValue pair = new DefaultKeyValue(key, value); + KeyValue pair = new DefaultKeyValue((K) key, (V) value); assertSame(key, pair.getKey()); assertSame(value, pair.getValue()); // 3. test copy constructor - Map.Entry entry2 = new DefaultMapEntry(entry); + Map.Entry entry2 = new DefaultMapEntry(entry); assertSame(key, entry2.getKey()); assertSame(value, entry2.getValue()); @@ -91,11 +91,12 @@ public class TestDefaultMapEntry extends AbstractTestMapEntry { assertSame(value, entry2.getValue()); } + @SuppressWarnings("unchecked") public void testSelfReferenceHandling() { - Map.Entry entry = makeMapEntry(); + Map.Entry entry = makeMapEntry(); try { - entry.setValue(entry); + entry.setValue((V) entry); assertSame(entry, entry.getValue()); } catch (Exception e) { diff --git a/src/test/org/apache/commons/collections/keyvalue/TestTiedMapEntry.java b/src/test/org/apache/commons/collections/keyvalue/TestTiedMapEntry.java index b53dadcaf..d3b812acc 100644 --- a/src/test/org/apache/commons/collections/keyvalue/TestTiedMapEntry.java +++ b/src/test/org/apache/commons/collections/keyvalue/TestTiedMapEntry.java @@ -30,11 +30,10 @@ import junit.framework.TestSuite; * * @author Stephen Colebourne */ -public class TestTiedMapEntry extends AbstractTestMapEntry { +public class TestTiedMapEntry extends AbstractTestMapEntry { public TestTiedMapEntry(String testName) { super(testName); - } public static void main(String[] args) { @@ -49,10 +48,10 @@ public class TestTiedMapEntry extends AbstractTestMapEntry { /** * Gets the instance to test */ - public Map.Entry makeMapEntry(Object key, Object value) { - Map map = new HashMap(); + public Map.Entry makeMapEntry(K key, V value) { + Map map = new HashMap(); map.put(key, value); - return new TiedMapEntry(map, key); + return new TiedMapEntry(map, key); } //----------------------------------------------------------------------- @@ -66,29 +65,30 @@ public class TestTiedMapEntry extends AbstractTestMapEntry { /** * Tests the constructors. */ + @SuppressWarnings("unchecked") public void testSetValue() { - Map map = new HashMap(); - map.put("A", "a"); - map.put("B", "b"); - map.put("C", "c"); - Map.Entry entry = new TiedMapEntry(map, "A"); + Map map = new HashMap(); + map.put((K) "A", (V) "a"); + map.put((K) "B", (V) "b"); + map.put((K) "C", (V) "c"); + Map.Entry entry = new TiedMapEntry(map, (K) "A"); assertSame("A", entry.getKey()); assertSame("a", entry.getValue()); - assertSame("a", entry.setValue("x")); + assertSame("a", entry.setValue((V) "x")); assertSame("A", entry.getKey()); assertSame("x", entry.getValue()); - - entry = new TiedMapEntry(map, "B"); + + entry = new TiedMapEntry(map, (K) "B"); assertSame("B", entry.getKey()); assertSame("b", entry.getValue()); - assertSame("b", entry.setValue("y")); + assertSame("b", entry.setValue((V) "y")); assertSame("B", entry.getKey()); assertSame("y", entry.getValue()); - - entry = new TiedMapEntry(map, "C"); + + entry = new TiedMapEntry(map, (K) "C"); assertSame("C", entry.getKey()); assertSame("c", entry.getValue()); - assertSame("c", entry.setValue("z")); + assertSame("c", entry.setValue((V) "z")); assertSame("C", entry.getKey()); assertSame("z", entry.getValue()); } diff --git a/src/test/org/apache/commons/collections/keyvalue/TestUnmodifiableMapEntry.java b/src/test/org/apache/commons/collections/keyvalue/TestUnmodifiableMapEntry.java index 99939672a..9c3398f0d 100644 --- a/src/test/org/apache/commons/collections/keyvalue/TestUnmodifiableMapEntry.java +++ b/src/test/org/apache/commons/collections/keyvalue/TestUnmodifiableMapEntry.java @@ -32,11 +32,10 @@ import org.apache.commons.collections.Unmodifiable; * * @author Neil O'Toole */ -public class TestUnmodifiableMapEntry extends AbstractTestMapEntry { +public class TestUnmodifiableMapEntry extends AbstractTestMapEntry { public TestUnmodifiableMapEntry(String testName) { super(testName); - } public static void main(String[] args) { @@ -53,8 +52,8 @@ public class TestUnmodifiableMapEntry extends AbstractTestMapEntry { * Subclasses should override this method to return a Map.Entry * of the type being tested. */ - public Map.Entry makeMapEntry() { - return new UnmodifiableMapEntry(null, null); + public Map.Entry makeMapEntry() { + return new UnmodifiableMapEntry(null, null); } /** @@ -62,8 +61,8 @@ public class TestUnmodifiableMapEntry extends AbstractTestMapEntry { * Subclasses should override this method to return a Map.Entry * of the type being tested. */ - public Map.Entry makeMapEntry(Object key, Object value) { - return new UnmodifiableMapEntry(key, value); + public Map.Entry makeMapEntry(K key, V value) { + return new UnmodifiableMapEntry(key, value); } //----------------------------------------------------------------------- @@ -71,28 +70,30 @@ public class TestUnmodifiableMapEntry extends AbstractTestMapEntry { * Subclasses should override this method. * */ + @SuppressWarnings("unchecked") public void testConstructors() { // 1. test key-value constructor - Map.Entry entry = new UnmodifiableMapEntry(key, value); + Map.Entry entry = new UnmodifiableMapEntry((K) key, (V) value); assertSame(key, entry.getKey()); assertSame(value, entry.getValue()); // 2. test pair constructor - KeyValue pair = new DefaultKeyValue(key, value); - entry = new UnmodifiableMapEntry(pair); + KeyValue pair = new DefaultKeyValue((K) key, (V) value); + entry = new UnmodifiableMapEntry(pair); assertSame(key, entry.getKey()); assertSame(value, entry.getValue()); // 3. test copy constructor - Map.Entry entry2 = new UnmodifiableMapEntry(entry); + Map.Entry entry2 = new UnmodifiableMapEntry(entry); assertSame(key, entry2.getKey()); assertSame(value, entry2.getValue()); assertTrue(entry instanceof Unmodifiable); } + @SuppressWarnings("unchecked") public void testAccessorsAndMutators() { - Map.Entry entry = makeMapEntry(key, value); + Map.Entry entry = makeMapEntry((K) key, (V) value); assertSame(key, entry.getKey()); assertSame(value, entry.getValue()); @@ -108,11 +109,10 @@ public class TestUnmodifiableMapEntry extends AbstractTestMapEntry { } public void testUnmodifiable() { - Map.Entry entry = makeMapEntry(); + Map.Entry entry = makeMapEntry(); try { entry.setValue(null); fail(); - } catch (UnsupportedOperationException ex) {} } diff --git a/src/test/org/apache/commons/collections/list/TestAbstractLinkedList.java b/src/test/org/apache/commons/collections/list/TestAbstractLinkedList.java index ba30d15b9..ee12658b7 100644 --- a/src/test/org/apache/commons/collections/list/TestAbstractLinkedList.java +++ b/src/test/org/apache/commons/collections/list/TestAbstractLinkedList.java @@ -27,100 +27,104 @@ import java.util.Arrays; * @author David Hay * @author Phil Steitz */ -public abstract class TestAbstractLinkedList extends AbstractTestList { - +public abstract class TestAbstractLinkedList extends AbstractTestList { + public TestAbstractLinkedList(String testName) { super(testName); } - //----------------------------------------------------------------------- + //----------------------------------------------------------------------- + @SuppressWarnings("unchecked") public void testRemoveFirst() { resetEmpty(); - AbstractLinkedList list = (AbstractLinkedList) collection; + AbstractLinkedList list = getCollection(); if (isRemoveSupported() == false) { try { list.removeFirst(); } catch (UnsupportedOperationException ex) {} - } - - list.addAll( Arrays.asList( new String[]{"value1", "value2"})); - assertEquals( "value1", list.removeFirst() ); + } + + list.addAll(Arrays.asList((E[]) new String[] { "value1", "value2" })); + assertEquals("value1", list.removeFirst()); checkNodes(); - list.addLast( "value3"); + list.addLast((E) "value3"); checkNodes(); - assertEquals( "value2", list.removeFirst() ); - assertEquals( "value3", list.removeFirst() ); + assertEquals("value2", list.removeFirst()); + assertEquals("value3", list.removeFirst()); checkNodes(); - list.addLast( "value4" ); + list.addLast((E) "value4"); checkNodes(); - assertEquals( "value4", list.removeFirst() ); + assertEquals("value4", list.removeFirst()); checkNodes(); } - + + @SuppressWarnings("unchecked") public void testRemoveLast() { resetEmpty(); - AbstractLinkedList list = (AbstractLinkedList) collection; + AbstractLinkedList list = getCollection(); if (isRemoveSupported() == false) { try { list.removeLast(); } catch (UnsupportedOperationException ex) {} - } - - list.addAll( Arrays.asList( new String[]{"value1", "value2"})); - assertEquals( "value2", list.removeLast() ); - list.addFirst( "value3"); + } + + list.addAll(Arrays.asList((E[]) new String[] { "value1", "value2" })); + assertEquals("value2", list.removeLast()); + list.addFirst((E) "value3"); checkNodes(); - assertEquals( "value1", list.removeLast() ); - assertEquals( "value3", list.removeLast() ); - list.addFirst( "value4" ); + assertEquals("value1", list.removeLast()); + assertEquals("value3", list.removeLast()); + list.addFirst((E) "value4"); checkNodes(); - assertEquals( "value4", list.removeFirst() ); + assertEquals("value4", list.removeFirst()); } - + + @SuppressWarnings("unchecked") public void testAddNodeAfter() { resetEmpty(); - AbstractLinkedList list = (AbstractLinkedList) collection; + AbstractLinkedList list = getCollection(); if (isAddSupported() == false) { try { list.addFirst(null); } catch (UnsupportedOperationException ex) {} - } - - list.addFirst("value1"); - list.addNodeAfter(list.getNode(0,false),"value2"); + } + + list.addFirst((E) "value1"); + list.addNodeAfter(list.getNode(0, false), (E) "value2"); assertEquals("value1", list.getFirst()); assertEquals("value2", list.getLast()); list.removeFirst(); checkNodes(); - list.addNodeAfter(list.getNode(0,false),"value3"); + list.addNodeAfter(list.getNode(0, false), (E) "value3"); checkNodes(); assertEquals("value2", list.getFirst()); assertEquals("value3", list.getLast()); - list.addNodeAfter(list.getNode(0, false),"value4"); + list.addNodeAfter(list.getNode(0, false), (E) "value4"); checkNodes(); assertEquals("value2", list.getFirst()); assertEquals("value3", list.getLast()); assertEquals("value4", list.get(1)); - list.addNodeAfter(list.getNode(2, false), "value5"); + list.addNodeAfter(list.getNode(2, false), (E) "value5"); checkNodes(); assertEquals("value2", list.getFirst()); assertEquals("value4", list.get(1)); assertEquals("value3", list.get(2)); assertEquals("value5", list.getLast()); } - + + @SuppressWarnings("unchecked") public void testRemoveNode() { resetEmpty(); if (isAddSupported() == false || isRemoveSupported() == false) return; - AbstractLinkedList list = (AbstractLinkedList) collection; - - list.addAll( Arrays.asList( new String[]{"value1", "value2"})); + AbstractLinkedList list = getCollection(); + + list.addAll(Arrays.asList((E[]) new String[] { "value1", "value2" })); list.removeNode(list.getNode(0, false)); checkNodes(); assertEquals("value2", list.getFirst()); assertEquals("value2", list.getLast()); - list.addFirst("value1"); - list.addFirst("value0"); + list.addFirst((E) "value1"); + list.addFirst((E) "value0"); checkNodes(); list.removeNode(list.getNode(1, false)); assertEquals("value0", list.getFirst()); @@ -131,53 +135,61 @@ public abstract class TestAbstractLinkedList extends AbstractTestList { assertEquals("value0", list.getLast()); checkNodes(); } - + + @SuppressWarnings("unchecked") public void testGetNode() { resetEmpty(); - AbstractLinkedList list = (AbstractLinkedList) collection; + AbstractLinkedList list = getCollection(); // get marker assertEquals(list.getNode(0, true).previous, list.getNode(0, true).next); try { - Object obj = list.getNode(0, false); + list.getNode(0, false); fail("Expecting IndexOutOfBoundsException."); } catch (IndexOutOfBoundsException ex) { // expected } - list.addAll( Arrays.asList( new String[]{"value1", "value2"})); + list.addAll( Arrays.asList((E[]) new String[]{"value1", "value2"})); checkNodes(); - list.addFirst("value0"); + list.addFirst((E) "value0"); checkNodes(); list.removeNode(list.getNode(1, false)); checkNodes(); try { - Object obj = list.getNode(2, false); + list.getNode(2, false); fail("Expecting IndexOutOfBoundsException."); } catch (IndexOutOfBoundsException ex) { // expected } try { - Object obj = list.getNode(-1, false); + list.getNode(-1, false); fail("Expecting IndexOutOfBoundsException."); } catch (IndexOutOfBoundsException ex) { // expected } try { - Object obj = list.getNode(3, true); + list.getNode(3, true); fail("Expecting IndexOutOfBoundsException."); } catch (IndexOutOfBoundsException ex) { // expected - } + } } - + protected void checkNodes() { - AbstractLinkedList list = (AbstractLinkedList) collection; + AbstractLinkedList list = getCollection(); for (int i = 0; i < list.size; i++) { assertEquals(list.getNode(i, false).next, list.getNode(i + 1, true)); if (i < list.size - 1) { - assertEquals(list.getNode(i + 1, false).previous, - list.getNode(i, false)); + assertEquals(list.getNode(i + 1, false).previous, + list.getNode(i, false)); } } } - + + /** + * {@inheritDoc} + */ + @Override + public AbstractLinkedList getCollection() { + return (AbstractLinkedList) super.getCollection(); + } } diff --git a/src/test/org/apache/commons/collections/list/TestFixedSizeList.java b/src/test/org/apache/commons/collections/list/TestFixedSizeList.java index dc6867964..c0f955548 100644 --- a/src/test/org/apache/commons/collections/list/TestFixedSizeList.java +++ b/src/test/org/apache/commons/collections/list/TestFixedSizeList.java @@ -32,7 +32,7 @@ import junit.framework.TestSuite; * * @author Stephen Colebourne */ -public class TestFixedSizeList extends AbstractTestList { +public class TestFixedSizeList extends AbstractTestList { public TestFixedSizeList(String testName) { super(testName); @@ -47,16 +47,16 @@ public class TestFixedSizeList extends AbstractTestList { junit.textui.TestRunner.main(testCaseName); } - public List makeEmptyList() { - return FixedSizeList.decorate(new ArrayList()); + public List makeObject() { + return FixedSizeList.decorate(new ArrayList()); } - public List makeFullList() { - List list = new ArrayList(); + public List makeFullCollection() { + List list = new ArrayList(); list.addAll(Arrays.asList(getFullElements())); return FixedSizeList.decorate(list); } - + public boolean isAddSupported() { return false; } diff --git a/src/test/org/apache/commons/collections/list/TestGrowthList.java b/src/test/org/apache/commons/collections/list/TestGrowthList.java index 85800a039..6346beba7 100644 --- a/src/test/org/apache/commons/collections/list/TestGrowthList.java +++ b/src/test/org/apache/commons/collections/list/TestGrowthList.java @@ -32,7 +32,7 @@ import junit.framework.TestSuite; * * @author Stephen Colebourne */ -public class TestGrowthList extends AbstractTestList { +public class TestGrowthList extends AbstractTestList { public TestGrowthList(String testName) { super(testName); @@ -47,12 +47,12 @@ public class TestGrowthList extends AbstractTestList { junit.textui.TestRunner.main(testCaseName); } - public List makeEmptyList() { - return new GrowthList(); + public List makeObject() { + return new GrowthList(); } - public List makeFullList() { - List list = new ArrayList(); + public List makeFullCollection() { + List list = new ArrayList(); list.addAll(Arrays.asList(getFullElements())); return GrowthList.decorate(list); } @@ -60,7 +60,7 @@ public class TestGrowthList extends AbstractTestList { //----------------------------------------------------------------------- public void testGrowthAdd() { Integer one = new Integer(1); - GrowthList grower = new GrowthList(); + GrowthList grower = new GrowthList(); assertEquals(0, grower.size()); grower.add(1, one); assertEquals(2, grower.size()); @@ -71,10 +71,10 @@ public class TestGrowthList extends AbstractTestList { public void testGrowthAddAll() { Integer one = new Integer(1); Integer two = new Integer(2); - Collection coll = new ArrayList(); + Collection coll = new ArrayList(); coll.add(one); coll.add(two); - GrowthList grower = new GrowthList(); + GrowthList grower = new GrowthList(); assertEquals(0, grower.size()); grower.addAll(1, coll); assertEquals(3, grower.size()); @@ -85,7 +85,7 @@ public class TestGrowthList extends AbstractTestList { public void testGrowthSet1() { Integer one = new Integer(1); - GrowthList grower = new GrowthList(); + GrowthList grower = new GrowthList(); assertEquals(0, grower.size()); grower.set(1, one); assertEquals(2, grower.size()); @@ -95,7 +95,7 @@ public class TestGrowthList extends AbstractTestList { public void testGrowthSet2() { Integer one = new Integer(1); - GrowthList grower = new GrowthList(); + GrowthList grower = new GrowthList(); assertEquals(0, grower.size()); grower.set(0, one); assertEquals(1, grower.size()); @@ -107,10 +107,10 @@ public class TestGrowthList extends AbstractTestList { * Override. */ public void testListAddByIndexBoundsChecking() { - List list; - Object element = getOtherElements()[0]; + List list; + E element = getOtherElements()[0]; try { - list = makeEmptyList(); + list = makeObject(); list.add(-1, element); fail("List.add should throw IndexOutOfBoundsException [-1]"); } catch (IndexOutOfBoundsException e) { @@ -122,10 +122,10 @@ public class TestGrowthList extends AbstractTestList { * Override. */ public void testListAddByIndexBoundsChecking2() { - List list; - Object element = getOtherElements()[0]; + List list; + E element = getOtherElements()[0]; try { - list = makeFullList(); + list = makeFullCollection(); list.add(-1, element); fail("List.add should throw IndexOutOfBoundsException [-1]"); } catch (IndexOutOfBoundsException e) { @@ -137,8 +137,8 @@ public class TestGrowthList extends AbstractTestList { * Override. */ public void testListSetByIndexBoundsChecking() { - List list = makeEmptyList(); - Object element = getOtherElements()[0]; + List list = makeObject(); + E element = getOtherElements()[0]; try { list.set(-1, element); fail("List.set should throw IndexOutOfBoundsException [-1]"); @@ -151,8 +151,8 @@ public class TestGrowthList extends AbstractTestList { * Override. */ public void testListSetByIndexBoundsChecking2() { - List list = makeFullList(); - Object element = getOtherElements()[0]; + List list = makeFullCollection(); + E element = getOtherElements()[0]; try { list.set(-1, element); fail("List.set should throw IndexOutOfBoundsException [-1]"); diff --git a/src/test/org/apache/commons/collections/list/TestNodeCachingLinkedList.java b/src/test/org/apache/commons/collections/list/TestNodeCachingLinkedList.java index dada23854..a46489672 100644 --- a/src/test/org/apache/commons/collections/list/TestNodeCachingLinkedList.java +++ b/src/test/org/apache/commons/collections/list/TestNodeCachingLinkedList.java @@ -18,7 +18,6 @@ package org.apache.commons.collections.list; import java.util.Arrays; import java.util.LinkedList; -import java.util.List; import junit.framework.Test; @@ -32,7 +31,7 @@ import org.apache.commons.collections.BulkTest; * @author Jeff Varszegi * @author Phil Steitz */ -public class TestNodeCachingLinkedList extends TestAbstractLinkedList { +public class TestNodeCachingLinkedList extends TestAbstractLinkedList { public TestNodeCachingLinkedList(String testName) { super(testName); @@ -48,49 +47,50 @@ public class TestNodeCachingLinkedList extends TestAbstractLinkedList { return BulkTest.makeSuite(TestNodeCachingLinkedList.class); } - //----------------------------------------------------------------------- - public List makeEmptyList() { - return new NodeCachingLinkedList(); + //----------------------------------------------------------------------- + public NodeCachingLinkedList makeObject() { + return new NodeCachingLinkedList(); } public String getCompatibilityVersion() { return "3"; } - + //----------------------------------------------------------------------- + @SuppressWarnings("unchecked") public void testShrinkCache() { if (isRemoveSupported() == false || isAddSupported() == false) return; resetEmpty(); - NodeCachingLinkedList list = (NodeCachingLinkedList) collection; - - list.addAll( Arrays.asList( new String[]{"1", "2", "3", "4"})); - list.removeAllNodes(); // Will dump all 4 elements into cache - ((NodeCachingLinkedList) list).setMaximumCacheSize(2); // shrink cache - list.addAll( Arrays.asList( new String[]{"1", "2", "3", "4"})); + NodeCachingLinkedList list = getCollection(); + + list.addAll(Arrays.asList((E[]) new String[] { "1", "2", "3", "4" })); + list.removeAllNodes(); // Will dump all 4 elements into cache + list.setMaximumCacheSize(2); // shrink cache + list.addAll(Arrays.asList((E[]) new String[] { "1", "2", "3", "4" })); checkNodes(); list.removeNode(list.getNode(0, false)); // no room in cache - list.removeNode(list.getNode(0, false)); - list.removeNode(list.getNode(0, false)); - checkNodes(); - list.addAll( Arrays.asList( new String[]{"1", "2", "3", "4"})); - checkNodes(); - } - + list.removeNode(list.getNode(0, false)); + list.removeNode(list.getNode(0, false)); + checkNodes(); + list.addAll(Arrays.asList((E[]) new String[] { "1", "2", "3", "4" })); + checkNodes(); + } + //----------------------------------------------------------------------- public static void compareSpeed() { - NodeCachingLinkedList ncll = new NodeCachingLinkedList(); - LinkedList ll = new LinkedList(); - + NodeCachingLinkedList ncll = new NodeCachingLinkedList(); + LinkedList ll = new LinkedList(); + Object o1 = new Object(); Object o2 = new Object(); - + int loopCount = 4000000; - + long startTime, endTime; - + System.out.println("Testing relative execution time of commonly-used methods..."); - - startTime = System.currentTimeMillis(); + + startTime = System.currentTimeMillis(); for(int x = loopCount; x > 0; x--) { // unrolled a few times to minimize effect of loop ll.addFirst(o1); @@ -114,10 +114,10 @@ public class TestNodeCachingLinkedList extends TestAbstractLinkedList { ll.add(o1); ll.remove(0); } - endTime = System.currentTimeMillis(); + endTime = System.currentTimeMillis(); System.out.println("Time with LinkedList: " + (endTime - startTime) + " ms"); - startTime = System.currentTimeMillis(); + startTime = System.currentTimeMillis(); for(int x = loopCount; x > 0; x--) { ncll.addFirst(o1); ncll.addLast(o2); @@ -140,11 +140,11 @@ public class TestNodeCachingLinkedList extends TestAbstractLinkedList { ncll.add(o1); ncll.remove(0); } - endTime = System.currentTimeMillis(); + endTime = System.currentTimeMillis(); System.out.println("Time with NodeCachingLinkedList: " + (endTime - startTime) + " ms"); } - + // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) collection, @@ -153,4 +153,12 @@ public class TestNodeCachingLinkedList extends TestAbstractLinkedList { // writeExternalFormToDisk((java.io.Serializable) collection, // "D:/dev/collections/data/test/NodeCachingLinkedList.fullCollection.version3.obj"); // } + + /** + * {@inheritDoc} + */ + @Override + public NodeCachingLinkedList getCollection() { + return (NodeCachingLinkedList) super.getCollection(); + } } diff --git a/src/test/org/apache/commons/collections/list/TestPredicatedList.java b/src/test/org/apache/commons/collections/list/TestPredicatedList.java index cb9070799..d668a3e85 100644 --- a/src/test/org/apache/commons/collections/list/TestPredicatedList.java +++ b/src/test/org/apache/commons/collections/list/TestPredicatedList.java @@ -23,7 +23,7 @@ import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections.Predicate; -import org.apache.commons.collections.PredicateUtils; +import org.apache.commons.collections.functors.TruePredicate; /** * Extension of {@link AbstractTestList} for exercising the @@ -34,113 +34,118 @@ import org.apache.commons.collections.PredicateUtils; * * @author Phil Steitz */ -public class TestPredicatedList extends AbstractTestList { - +public class TestPredicatedList extends AbstractTestList { + public TestPredicatedList(String testName) { super(testName); } - + public static Test suite() { return new TestSuite(TestPredicatedList.class); } - + public static void main(String args[]) { String[] testCaseName = { TestPredicatedList.class.getName()}; junit.textui.TestRunner.main(testCaseName); } - + //------------------------------------------------------------------- - - protected Predicate truePredicate = PredicateUtils.truePredicate(); - - protected List decorateList(List list, Predicate predicate) { + + protected Predicate truePredicate = TruePredicate.truePredicate(); + + protected List decorateList(List list, Predicate predicate) { return PredicatedList.decorate(list, predicate); } - - public List makeEmptyList() { - return decorateList(new ArrayList(), truePredicate); - } - - public Object[] getFullElements() { - return new Object[] {"1", "3", "5", "7", "2", "4", "6"}; - } - -//-------------------------------------------------------------------- - - protected Predicate testPredicate = - new Predicate() { - public boolean evaluate(Object o) { - return o instanceof String; - } - }; - - public List makeTestList() { - return decorateList(new ArrayList(), testPredicate); - } - - public void testIllegalAdd() { - List list = makeTestList(); - Integer i = new Integer(3); - try { - list.add(i); - fail("Integer should fail string predicate."); - } catch (IllegalArgumentException e) { - // expected - } - assertTrue("Collection shouldn't contain illegal element", - !list.contains(i)); + + public List makeObject() { + return decorateList(new ArrayList(), truePredicate); } + @SuppressWarnings("unchecked") + public E[] getFullElements() { + return (E[]) new Object[] { "1", "3", "5", "7", "2", "4", "6" }; + } + +//-------------------------------------------------------------------- + + protected Predicate testPredicate = + new Predicate() { + public boolean evaluate(E o) { + return o instanceof String; + } + }; + + public List makeTestList() { + return decorateList(new ArrayList(), testPredicate); + } + + @SuppressWarnings("unchecked") + public void testIllegalAdd() { + List list = makeTestList(); + Integer i = new Integer(3); + try { + list.add((E) i); + fail("Integer should fail string predicate."); + } catch (IllegalArgumentException e) { + // expected + } + assertTrue("Collection shouldn't contain illegal element", + !list.contains(i)); + } + + @SuppressWarnings("unchecked") public void testIllegalAddAll() { - List list = makeTestList(); - List elements = new ArrayList(); - elements.add("one"); - elements.add("two"); - elements.add(new Integer(3)); - elements.add("four"); + List list = makeTestList(); + List elements = new ArrayList(); + elements.add((E) "one"); + elements.add((E) "two"); + elements.add((E) new Integer(3)); + elements.add((E) "four"); try { - list.addAll(0,elements); + list.addAll(0, elements); fail("Integer should fail string predicate."); } catch (IllegalArgumentException e) { // expected } - assertTrue("List shouldn't contain illegal element", - !list.contains("one")); - assertTrue("List shouldn't contain illegal element", - !list.contains("two")); - assertTrue("List shouldn't contain illegal element", - !list.contains(new Integer(3))); - assertTrue("List shouldn't contain illegal element", - !list.contains("four")); + assertTrue("List shouldn't contain illegal element", + !list.contains("one")); + assertTrue("List shouldn't contain illegal element", + !list.contains("two")); + assertTrue("List shouldn't contain illegal element", + !list.contains(new Integer(3))); + assertTrue("List shouldn't contain illegal element", + !list.contains("four")); } - + + @SuppressWarnings("unchecked") public void testIllegalSet() { - List list = makeTestList(); + List list = makeTestList(); try { - list.set(0,new Integer(3)); + list.set(0, (E) new Integer(3)); fail("Integer should fail string predicate."); } catch (IllegalArgumentException e) { // expected } } - + + @SuppressWarnings("unchecked") public void testLegalAddAll() { - List list = makeTestList(); - list.add("zero"); - List elements = new ArrayList(); - elements.add("one"); - elements.add("two"); - elements.add("three"); + List list = makeTestList(); + list.add((E) "zero"); + List elements = new ArrayList(); + elements.add((E) "one"); + elements.add((E) "two"); + elements.add((E) "three"); list.addAll(1,elements); - assertTrue("List should contain legal element", - list.contains("zero")); - assertTrue("List should contain legal element", - list.contains("one")); - assertTrue("List should contain legal element", - list.contains("two")); - assertTrue("List should contain legal element", - list.contains("three")); - } + assertTrue("List should contain legal element", + list.contains("zero")); + assertTrue("List should contain legal element", + list.contains("one")); + assertTrue("List should contain legal element", + list.contains("two")); + assertTrue("List should contain legal element", + list.contains("three")); + } public String getCompatibilityVersion() { return "3.1"; diff --git a/src/test/org/apache/commons/collections/list/TestSetUniqueList.java b/src/test/org/apache/commons/collections/list/TestSetUniqueList.java index 32396cfbb..0851a3f3f 100644 --- a/src/test/org/apache/commons/collections/list/TestSetUniqueList.java +++ b/src/test/org/apache/commons/collections/list/TestSetUniqueList.java @@ -18,6 +18,7 @@ package org.apache.commons.collections.list; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collection; import java.util.HashSet; import java.util.LinkedList; import java.util.List; @@ -37,7 +38,7 @@ import junit.textui.TestRunner; * @author Matthew Hawthorne * @author Tom Dunham */ -public class TestSetUniqueList extends AbstractTestList { +public class TestSetUniqueList extends AbstractTestList { public static void main(String[] args) { TestRunner.run(suite()); @@ -52,53 +53,54 @@ public class TestSetUniqueList extends AbstractTestList { } //----------------------------------------------------------------------- - public List makeEmptyList() { - return new SetUniqueList(new ArrayList(), new HashSet()); + public List makeObject() { + return new SetUniqueList(new ArrayList(), new HashSet()); } public void testListIteratorSet() { // override to block resetFull(); - ListIterator it = getList().listIterator(); + ListIterator it = getCollection().listIterator(); it.next(); try { it.set(null); fail(); } catch (UnsupportedOperationException ex) {} } - - public Object[] getFullNonNullElements() { + + @SuppressWarnings("unchecked") + public E[] getFullNonNullElements() { // override to avoid duplicate "One" - return new Object[] { - new String(""), - new String("One"), - new Integer(2), - "Three", - new Integer(4), - new Double(5), - new Float(6), - "Seven", - "Eight", - new String("Nine"), - new Integer(10), - new Short((short)11), - new Long(12), - "Thirteen", - "14", - "15", - new Byte((byte)16) + return (E[]) new Object[] { + new String(""), + new String("One"), + new Integer(2), + "Three", + new Integer(4), + new Double(5), + new Float(6), + "Seven", + "Eight", + new String("Nine"), + new Integer(10), + new Short((short)11), + new Long(12), + "Thirteen", + "14", + "15", + new Byte((byte)16) }; } - + public void testListIteratorAdd() { // override to cope with Set behaviour resetEmpty(); - List list1 = getList(); - List list2 = getConfirmedList(); + List list1 = getCollection(); + List list2 = getConfirmed(); - Object[] elements = getOtherElements(); // changed here - ListIterator iter1 = list1.listIterator(); - ListIterator iter2 = list2.listIterator(); + E[] elements = getOtherElements(); // changed here + ListIterator iter1 = list1.listIterator(); + ListIterator iter2 = list2.listIterator(); for (int i = 0; i < elements.length; i++) { iter1.add(elements[i]); @@ -107,8 +109,8 @@ public class TestSetUniqueList extends AbstractTestList { } resetFull(); - iter1 = getList().listIterator(); - iter2 = getConfirmedList().listIterator(); + iter1 = getCollection().listIterator(); + iter2 = getConfirmed().listIterator(); for (int i = 0; i < elements.length; i++) { iter1.next(); iter2.next(); @@ -117,35 +119,36 @@ public class TestSetUniqueList extends AbstractTestList { super.verify(); // changed here } } - + public void testCollectionAddAll() { // override for set behaviour resetEmpty(); - Object[] elements = getFullElements(); - boolean r = collection.addAll(Arrays.asList(elements)); - confirmed.addAll(Arrays.asList(elements)); + E[] elements = getFullElements(); + boolean r = getCollection().addAll(Arrays.asList(elements)); + getConfirmed().addAll(Arrays.asList(elements)); verify(); assertTrue("Empty collection should change after addAll", r); for (int i = 0; i < elements.length; i++) { assertTrue("Collection should contain added element", - collection.contains(elements[i])); + getCollection().contains(elements[i])); } resetFull(); - int size = collection.size(); + int size = getCollection().size(); elements = getOtherElements(); - r = collection.addAll(Arrays.asList(elements)); - confirmed.addAll(Arrays.asList(elements)); + r = getCollection().addAll(Arrays.asList(elements)); + getConfirmed().addAll(Arrays.asList(elements)); verify(); assertTrue("Full collection should change after addAll", r); for (int i = 0; i < elements.length; i++) { assertTrue("Full collection should contain added element " + i, - collection.contains(elements[i])); + getCollection().contains(elements[i])); } - assertEquals("Size should increase after addAll", - size + elements.length, collection.size()); + assertEquals("Size should increase after addAll", + size + elements.length, getCollection().size()); } + // TODO: Generics public void testIntCollectionAddAll() { // make a SetUniqueList with one element List list = new SetUniqueList(new ArrayList(), new HashSet()); @@ -155,7 +158,7 @@ public class TestSetUniqueList extends AbstractTestList { // add two new unique elements at index 0 final Integer firstNewElement = new Integer(2); final Integer secondNewElement = new Integer(3); - collection = Arrays.asList(new Integer[] {firstNewElement, secondNewElement}); + Collection collection = Arrays.asList(new Integer[] {firstNewElement, secondNewElement}); list.addAll(0, collection); assertEquals("Unique elements should be added.", 3, list.size()); assertEquals("First new element should be at index 0", firstNewElement, list.get(0)); @@ -171,18 +174,19 @@ public class TestSetUniqueList extends AbstractTestList { assertEquals("Third new element should be at index 0", thirdNewElement, list.get(0)); } + @SuppressWarnings("unchecked") public void testListSetByIndex() { // override for set behaviour resetFull(); - int size = collection.size(); - getList().set(0, new Long(1000)); - assertEquals(size, collection.size()); + int size = getCollection().size(); + getCollection().set(0, (E) new Long(1000)); + assertEquals(size, getCollection().size()); - getList().set(2, new Long(1000)); - assertEquals(size - 1, collection.size()); - assertEquals(new Long(1000), getList().get(1)); // set into 2, but shifted down to 1 + getCollection().set(2, (E) new Long(1000)); + assertEquals(size - 1, getCollection().size()); + assertEquals(new Long(1000), getCollection().get(1)); // set into 2, but shifted down to 1 } - + boolean extraVerify = true; public void testCollectionIteratorRemove() { try { @@ -192,28 +196,29 @@ public class TestSetUniqueList extends AbstractTestList { extraVerify = true; } } - + + @SuppressWarnings("unchecked") public void verify() { super.verify(); - - if (extraVerify) { - int size = collection.size(); - getList().add(new Long(1000)); - assertEquals(size + 1, collection.size()); - getList().add(new Long(1000)); - assertEquals(size + 1, collection.size()); - assertEquals(new Long(1000), getList().get(size)); - - getList().remove(size); + if (extraVerify) { + int size = getCollection().size(); + getCollection().add((E) new Long(1000)); + assertEquals(size + 1, getCollection().size()); + + getCollection().add((E) new Long(1000)); + assertEquals(size + 1, getCollection().size()); + assertEquals(new Long(1000), getCollection().get(size)); + + getCollection().remove(size); } } - + //----------------------------------------------------------------------- public void testFactory() { - Integer[] array = new Integer[] {new Integer(1), new Integer(2), new Integer(1)}; - ArrayList list = new ArrayList(Arrays.asList(array)); - final SetUniqueList lset = SetUniqueList.decorate(list); + Integer[] array = new Integer[] { new Integer(1), new Integer(2), new Integer(1) }; + ArrayList list = new ArrayList(Arrays.asList(array)); + final SetUniqueList lset = SetUniqueList.decorate(list); assertEquals("Duplicate element was added.", 2, lset.size()); assertEquals(new Integer(1), lset.get(0)); @@ -222,36 +227,39 @@ public class TestSetUniqueList extends AbstractTestList { assertEquals(new Integer(2), list.get(1)); } + @SuppressWarnings("unchecked") public void testAdd() { - final SetUniqueList lset = new SetUniqueList(new ArrayList(), new HashSet()); + final SetUniqueList lset = new SetUniqueList(new ArrayList(), new HashSet()); // Duplicate element - final Object obj = new Integer(1); + final E obj = (E) new Integer(1); lset.add(obj); lset.add(obj); assertEquals("Duplicate element was added.", 1, lset.size()); // Unique element - lset.add(new Integer(2)); + lset.add((E) new Integer(2)); assertEquals("Unique element was not added.", 2, lset.size()); } + @SuppressWarnings("unchecked") public void testAddAll() { - final SetUniqueList lset = new SetUniqueList(new ArrayList(), new HashSet()); + final SetUniqueList lset = new SetUniqueList(new ArrayList(), new HashSet()); lset.addAll( - Arrays.asList(new Integer[] { new Integer(1), new Integer(1)})); + Arrays.asList((E[]) new Integer[] { new Integer(1), new Integer(1)})); assertEquals("Duplicate element was added.", 1, lset.size()); } + @SuppressWarnings("unchecked") public void testSet() { - final SetUniqueList lset = new SetUniqueList(new ArrayList(), new HashSet()); + final SetUniqueList lset = new SetUniqueList(new ArrayList(), new HashSet()); // Duplicate element - final Object obj1 = new Integer(1); - final Object obj2 = new Integer(2); - final Object obj3 = new Integer(3); + final E obj1 = (E) new Integer(1); + final E obj2 = (E) new Integer(2); + final E obj3 = (E) new Integer(3); lset.add(obj1); lset.add(obj2); @@ -283,16 +291,17 @@ public class TestSetUniqueList extends AbstractTestList { assertSame(obj1, lset.get(0)); } + @SuppressWarnings("unchecked") public void testListIterator() { - final SetUniqueList lset = new SetUniqueList(new ArrayList(), new HashSet()); + final SetUniqueList lset = new SetUniqueList(new ArrayList(), new HashSet()); - final Object obj1 = new Integer(1); - final Object obj2 = new Integer(2); + final E obj1 = (E) new Integer(1); + final E obj2 = (E) new Integer(2); lset.add(obj1); lset.add(obj2); // Attempts to add a duplicate object - for (final ListIterator it = lset.listIterator(); it.hasNext();) { + for (final ListIterator it = lset.listIterator(); it.hasNext();) { it.next(); if (!it.hasNext()) { @@ -304,36 +313,39 @@ public class TestSetUniqueList extends AbstractTestList { assertEquals("Duplicate element was added", 2, lset.size()); } + @SuppressWarnings("unchecked") public void testUniqueListReInsert() { - List l = SetUniqueList.decorate(new LinkedList()); - l.add(new Object()); - l.add(new Object()); - - Object a = l.get(0); - + List l = SetUniqueList.decorate(new LinkedList()); + l.add((E) new Object()); + l.add((E) new Object()); + + E a = l.get(0); + // duplicate is removed - l.set(0, l.get(1)); + l.set(0, l.get(1)); assertEquals(1, l.size()); - - // old object is added back in - l.add(1, a); + + // old object is added back in + l.add(1, a); assertEquals(2, l.size()); } - + + @SuppressWarnings("unchecked") public void testUniqueListDoubleInsert() { - List l = SetUniqueList.decorate(new LinkedList()); - l.add(new Object()); - l.add(new Object()); - + List l = SetUniqueList.decorate(new LinkedList()); + l.add((E) new Object()); + l.add((E) new Object()); + // duplicate is removed - l.set(0, l.get(1)); + l.set(0, l.get(1)); assertEquals(1, l.size()); - + // duplicate should be removed again l.add(1, l.get(0)); assertEquals(1, l.size()); } + @SuppressWarnings("unchecked") public void testSetDownwardsInList() { /* * Checks the following semantics @@ -341,19 +353,19 @@ public class TestSetUniqueList extends AbstractTestList { * set(0,b): [b]->a * So UniqList contains [b] and a is returned */ - ArrayList l = new ArrayList(); - HashSet s = new HashSet(); - final SetUniqueList ul = new SetUniqueList(l, s); + ArrayList l = new ArrayList(); + HashSet s = new HashSet(); + final SetUniqueList ul = new SetUniqueList(l, s); - Object a = new Object(); - Object b = new Object(); + E a = (E) new Object(); + E b = (E) new Object(); ul.add(a); ul.add(b); assertEquals(a, l.get(0)); assertEquals(b, l.get(1)); - assertTrue(s.contains(a)); + assertTrue(s.contains(a)); assertTrue(s.contains(b)); - + assertEquals(a, ul.set(0, b)); assertEquals(1, s.size()); assertEquals(1, l.size()); @@ -362,6 +374,7 @@ public class TestSetUniqueList extends AbstractTestList { assertFalse(s.contains(a)); } + @SuppressWarnings("unchecked") public void testSetInBiggerList() { /* * Checks the following semantics @@ -369,13 +382,13 @@ public class TestSetUniqueList extends AbstractTestList { * set(0,b): [b,c]->a * So UniqList contains [b,c] and a is returned */ - ArrayList l = new ArrayList(); - HashSet s = new HashSet(); - final SetUniqueList ul = new SetUniqueList(l, s); + ArrayList l = new ArrayList(); + HashSet s = new HashSet(); + final SetUniqueList ul = new SetUniqueList(l, s); - Object a = new Object(); - Object b = new Object(); - Object c = new Object(); + E a = (E) new Object(); + E b = (E) new Object(); + E c = (E) new Object(); ul.add(a); ul.add(b); @@ -383,10 +396,10 @@ public class TestSetUniqueList extends AbstractTestList { assertEquals(a, l.get(0)); assertEquals(b, l.get(1)); assertEquals(c, l.get(2)); - assertTrue(s.contains(a)); + assertTrue(s.contains(a)); assertTrue(s.contains(b)); assertTrue(s.contains(c)); - + assertEquals(a, ul.set(0, b)); assertEquals(2, s.size()); assertEquals(2, l.size()); @@ -395,8 +408,9 @@ public class TestSetUniqueList extends AbstractTestList { assertFalse(s.contains(a)); assertTrue(s.contains(b)); assertTrue(s.contains(c)); - } + } + @SuppressWarnings("unchecked") public void testSetUpwardsInList() { /* * Checks the following semantics @@ -404,13 +418,13 @@ public class TestSetUniqueList extends AbstractTestList { * set(1,a): [a,c]->b * So UniqList contains [a,c] and b is returned */ - ArrayList l = new ArrayList(); - HashSet s = new HashSet(); - final SetUniqueList ul = new SetUniqueList(l, s); + ArrayList l = new ArrayList(); + HashSet s = new HashSet(); + final SetUniqueList ul = new SetUniqueList(l, s); - Object a = new String("A"); - Object b = new String("B"); - Object c = new String("C"); + E a = (E) new String("A"); + E b = (E) new String("B"); + E c = (E) new String("C"); ul.add(a); ul.add(b); @@ -418,10 +432,10 @@ public class TestSetUniqueList extends AbstractTestList { assertEquals(a, l.get(0)); assertEquals(b, l.get(1)); assertEquals(c, l.get(2)); - assertTrue(s.contains(a)); + assertTrue(s.contains(a)); assertTrue(s.contains(b)); assertTrue(s.contains(c)); - + assertEquals(b, ul.set(1, a)); assertEquals(2, s.size()); assertEquals(2, l.size()); @@ -444,6 +458,7 @@ public class TestSetUniqueList extends AbstractTestList { // writeExternalFormToDisk((java.io.Serializable) collection, "D:/dev/collections/data/test/SetUniqueList.fullCollection.version3.1.obj"); // } + // TODO: Generics public void testCollections304() { List list = new LinkedList(); SetUniqueList decoratedList = SetUniqueList.decorate(list); @@ -471,33 +486,34 @@ public class TestSetUniqueList extends AbstractTestList { assertEquals(4, decoratedList.size()); } + @SuppressWarnings("unchecked") public void testCollections307() { - List list = new ArrayList(); - List uniqueList = SetUniqueList.decorate(list); + List list = new ArrayList(); + List uniqueList = SetUniqueList.decorate(list); String hello = "Hello"; String world = "World"; - uniqueList.add(hello); - uniqueList.add(world); + uniqueList.add((E) hello); + uniqueList.add((E) world); - List subList = list.subList(0, 0); - List subUniqueList = uniqueList.subList(0, 0); + List subList = list.subList(0, 0); + List subUniqueList = uniqueList.subList(0, 0); assertFalse(subList.contains(world)); // passes assertFalse(subUniqueList.contains(world)); // fails - List worldList = new ArrayList(); - worldList.add(world); + List worldList = new ArrayList(); + worldList.add((E) world); assertFalse(subList.contains("World")); // passes assertFalse(subUniqueList.contains("World")); // fails - // repeat the test with a different class than HashSet; + // repeat the test with a different class than HashSet; // which means subclassing SetUniqueList below - list = new ArrayList(); - uniqueList = new SetUniqueList307(list, new java.util.TreeSet()); + list = new ArrayList(); + uniqueList = new SetUniqueList307(list, new java.util.TreeSet()); - uniqueList.add(hello); - uniqueList.add(world); + uniqueList.add((E) hello); + uniqueList.add((E) world); subList = list.subList(0, 0); subUniqueList = uniqueList.subList(0, 0); @@ -505,14 +521,15 @@ public class TestSetUniqueList extends AbstractTestList { assertFalse(subList.contains(world)); // passes assertFalse(subUniqueList.contains(world)); // fails - worldList = new ArrayList(); - worldList.add(world); + worldList = new ArrayList(); + worldList.add((E) world); assertFalse(subList.contains("World")); // passes assertFalse(subUniqueList.contains("World")); // fails } - class SetUniqueList307 extends SetUniqueList { - public SetUniqueList307(List list, Set set) { + @SuppressWarnings("serial") + class SetUniqueList307 extends SetUniqueList { + public SetUniqueList307(List list, Set set) { super(list, set); } } diff --git a/src/test/org/apache/commons/collections/list/TestSynchronizedList.java b/src/test/org/apache/commons/collections/list/TestSynchronizedList.java index 2641da4bf..bf95432b6 100644 --- a/src/test/org/apache/commons/collections/list/TestSynchronizedList.java +++ b/src/test/org/apache/commons/collections/list/TestSynchronizedList.java @@ -17,7 +17,6 @@ package org.apache.commons.collections.list; import java.util.ArrayList; -import java.util.Collection; import java.util.List; import junit.framework.Test; @@ -32,8 +31,8 @@ import junit.framework.TestSuite; * * @author Stephen Colebourne */ -public class TestSynchronizedList extends AbstractTestList { - +public class TestSynchronizedList extends AbstractTestList { + public TestSynchronizedList(String testName) { super(testName); } @@ -47,12 +46,12 @@ public class TestSynchronizedList extends AbstractTestList { junit.textui.TestRunner.main(testCaseName); } - public Collection makeConfirmedCollection() { - return new ArrayList(); + public List makeConfirmedCollection() { + return new ArrayList(); } - public List makeEmptyList() { - return SynchronizedList.decorate(new ArrayList()); + public List makeObject() { + return SynchronizedList.decorate(new ArrayList()); } public String getCompatibilityVersion() { diff --git a/src/test/org/apache/commons/collections/list/TestTransformedList.java b/src/test/org/apache/commons/collections/list/TestTransformedList.java index 645869360..a2971b3db 100644 --- a/src/test/org/apache/commons/collections/list/TestTransformedList.java +++ b/src/test/org/apache/commons/collections/list/TestTransformedList.java @@ -18,13 +18,13 @@ package org.apache.commons.collections.list; import java.util.ArrayList; import java.util.Arrays; -import java.util.Collection; import java.util.List; import java.util.ListIterator; import junit.framework.Test; import junit.framework.TestSuite; +import org.apache.commons.collections.Transformer; import org.apache.commons.collections.collection.TestTransformedCollection; /** @@ -36,8 +36,8 @@ import org.apache.commons.collections.collection.TestTransformedCollection; * * @author Stephen Colebourne */ -public class TestTransformedList extends AbstractTestList { - +public class TestTransformedList extends AbstractTestList { + public TestTransformedList(String testName) { super(testName); } @@ -51,67 +51,70 @@ public class TestTransformedList extends AbstractTestList { junit.textui.TestRunner.main(testCaseName); } - public Collection makeConfirmedCollection() { - return new ArrayList(); + public List makeConfirmedCollection() { + return new ArrayList(); } - public Collection makeConfirmedFullCollection() { - List list = new ArrayList(); + public List makeConfirmedFullCollection() { + List list = new ArrayList(); list.addAll(Arrays.asList(getFullElements())); return list; } - - public List makeEmptyList() { - return TransformedList.decorate(new ArrayList(), TestTransformedCollection.NOOP_TRANSFORMER); + + @SuppressWarnings("unchecked") + public List makeObject() { + return TransformedList.decorate(new ArrayList(), (Transformer) TestTransformedCollection.NOOP_TRANSFORMER); } - public List makeFullList() { - List list = new ArrayList(); + @SuppressWarnings("unchecked") + public List makeFullCollection() { + List list = new ArrayList(); list.addAll(Arrays.asList(getFullElements())); - return TransformedList.decorate(list, TestTransformedCollection.NOOP_TRANSFORMER); + return TransformedList.decorate(list, (Transformer) TestTransformedCollection.NOOP_TRANSFORMER); } - + + @SuppressWarnings("unchecked") public void testTransformedList() { - List list = TransformedList.decorate(new ArrayList(), TestTransformedCollection.STRING_TO_INTEGER_TRANSFORMER); + List list = TransformedList.decorate(new ArrayList(), (Transformer) TestTransformedCollection.STRING_TO_INTEGER_TRANSFORMER); assertEquals(0, list.size()); - Object[] els = new Object[] {"1", "3", "5", "7", "2", "4", "6"}; + E[] els = (E[]) new Object[] {"1", "3", "5", "7", "2", "4", "6"}; for (int i = 0; i < els.length; i++) { list.add(els[i]); assertEquals(i + 1, list.size()); assertEquals(true, list.contains(new Integer((String) els[i]))); assertEquals(false, list.contains(els[i])); } - + assertEquals(false, list.remove(els[0])); assertEquals(true, list.remove(new Integer((String) els[0]))); - + list.clear(); for (int i = 0; i < els.length; i++) { list.add(0, els[i]); assertEquals(i + 1, list.size()); assertEquals(new Integer((String) els[i]), list.get(0)); } - - list.set(0, "22"); + + list.set(0, (E) "22"); assertEquals(new Integer(22), list.get(0)); - - ListIterator it = list.listIterator(); + + ListIterator it = list.listIterator(); it.next(); - it.set("33"); + it.set((E) "33"); assertEquals(new Integer(33), list.get(0)); - it.add("44"); + it.add((E) "44"); assertEquals(new Integer(44), list.get(1)); - - List adds = new ArrayList(); - adds.add("1"); - adds.add("2"); + + List adds = new ArrayList(); + adds.add((E) "1"); + adds.add((E) "2"); list.clear(); list.addAll(adds); assertEquals(new Integer(1), list.get(0)); assertEquals(new Integer(2), list.get(1)); - + adds.clear(); - adds.add("3"); + adds.add((E) "3"); list.addAll(1, adds); assertEquals(new Integer(1), list.get(0)); assertEquals(new Integer(3), list.get(1)); diff --git a/src/test/org/apache/commons/collections/list/TestUnmodifiableList.java b/src/test/org/apache/commons/collections/list/TestUnmodifiableList.java index 2aa55c155..3ef9a4620 100644 --- a/src/test/org/apache/commons/collections/list/TestUnmodifiableList.java +++ b/src/test/org/apache/commons/collections/list/TestUnmodifiableList.java @@ -25,7 +25,7 @@ import junit.framework.Test; import junit.framework.TestSuite; /** - * Extension of {@link AbstractTestList} for exercising the + * Extension of {@link AbstractTestList} for exercising the * {@link UnmodifiableList} implementation. * * @since Commons Collections 3.0 @@ -33,72 +33,74 @@ import junit.framework.TestSuite; * * @author Phil Steitz */ -public class TestUnmodifiableList extends AbstractTestList { - +public class TestUnmodifiableList extends AbstractTestList { + public TestUnmodifiableList(String testName) { super(testName); } - + public static Test suite() { return new TestSuite(TestUnmodifiableList.class); } - + public static void main(String args[]) { String[] testCaseName = { TestUnmodifiableList.class.getName()}; junit.textui.TestRunner.main(testCaseName); } - //----------------------------------------------------------------------- - public List makeEmptyList() { - return UnmodifiableList.decorate(new ArrayList()); + //----------------------------------------------------------------------- + public UnmodifiableList makeObject() { + return new UnmodifiableList(new ArrayList()); } - - public List makeFullList() { - ArrayList list = new ArrayList(); + + public UnmodifiableList makeFullCollection() { + ArrayList list = new ArrayList(); list.addAll(Arrays.asList(getFullElements())); - return UnmodifiableList.decorate(list); + return new UnmodifiableList(list); } - + public boolean isSetSupported() { return false; } - + public boolean isAddSupported() { return false; } - + public boolean isRemoveSupported() { return false; } - - //----------------------------------------------------------------------- - protected UnmodifiableList list = null; - protected ArrayList array = null; - + + //----------------------------------------------------------------------- + protected UnmodifiableList list; + protected ArrayList array; + + @SuppressWarnings("unchecked") protected void setupList() { - list = (UnmodifiableList) makeFullList(); - array = new ArrayList(); - array.add(new Integer(1)); + list = makeFullCollection(); + array = new ArrayList(); + array.add((E) new Integer(1)); } - - /** + + /** * Verify that base list and sublists are not modifiable */ public void testUnmodifiable() { setupList(); - verifyUnmodifiable(list); + verifyUnmodifiable(list); verifyUnmodifiable(list.subList(0, 2)); - } - - protected void verifyUnmodifiable(List list) { + } + + @SuppressWarnings("unchecked") + protected void verifyUnmodifiable(List list) { try { - list.add(0, new Integer(0)); + list.add(0, (E) new Integer(0)); fail("Expecting UnsupportedOperationException."); } catch (UnsupportedOperationException e) { // expected - } + } try { - list.add(new Integer(0)); + list.add((E) new Integer(0)); fail("Expecting UnsupportedOperationException."); } catch (UnsupportedOperationException e) { // expected @@ -146,21 +148,21 @@ public class TestUnmodifiableList extends AbstractTestList { // expected } try { - list.set(0, new Integer(0)); + list.set(0, (E) new Integer(0)); fail("Expecting UnsupportedOperationException."); } catch (UnsupportedOperationException e) { // expected } } - + /** * Verify that iterator is not modifiable */ public void testUnmodifiableIterator() { setupList(); - Iterator iterator = list.iterator(); + Iterator iterator = list.iterator(); try { - Object obj = iterator.next(); + iterator.next(); iterator.remove(); fail("Expecting UnsupportedOperationException."); } catch (UnsupportedOperationException e) { diff --git a/src/test/org/apache/commons/collections/map/AbstractTestOrderedMap.java b/src/test/org/apache/commons/collections/map/AbstractTestOrderedMap.java index 90a4a0ca6..8e69a6524 100644 --- a/src/test/org/apache/commons/collections/map/AbstractTestOrderedMap.java +++ b/src/test/org/apache/commons/collections/map/AbstractTestOrderedMap.java @@ -26,8 +26,8 @@ import java.util.NoSuchElementException; import java.util.TreeMap; import org.apache.commons.collections.BulkTest; -import org.apache.commons.collections.MapIterator; import org.apache.commons.collections.OrderedMap; +import org.apache.commons.collections.OrderedMapIterator; import org.apache.commons.collections.comparators.NullComparator; import org.apache.commons.collections.iterators.AbstractTestOrderedMapIterator; @@ -38,93 +38,108 @@ import org.apache.commons.collections.iterators.AbstractTestOrderedMapIterator; * * @author Stephen Colebourne */ -public abstract class AbstractTestOrderedMap extends AbstractTestIterableMap { +public abstract class AbstractTestOrderedMap extends AbstractTestIterableMap { /** * JUnit constructor. - * + * * @param testName the test name */ public AbstractTestOrderedMap(String testName) { super(testName); } - + + /** + * {@inheritDoc} + */ + @Override + public abstract OrderedMap makeObject(); + + /** + * {@inheritDoc} + */ + @Override + public OrderedMap makeFullMap() { + return (OrderedMap) super.makeFullMap(); + } + //----------------------------------------------------------------------- /** * OrderedMap uses TreeMap as its known comparison. - * + * * @return a map that is known to be valid */ - public Map makeConfirmedMap() { - return new TreeMap(new NullComparator()); + public Map makeConfirmedMap() { + return new TreeMap(new NullComparator()); } - + /** * The only confirmed collection we have that is ordered is the sorted one. * Thus, sort the keys. */ - public Object[] getSampleKeys() { - List list = new ArrayList(Arrays.asList(super.getSampleKeys())); - Collections.sort(list, new NullComparator()); - return list.toArray(); + @SuppressWarnings("unchecked") + public K[] getSampleKeys() { + List list = new ArrayList(Arrays.asList(super.getSampleKeys())); + Collections.sort(list, new NullComparator()); + return (K[]) list.toArray(); } //----------------------------------------------------------------------- public void testFirstKey() { resetEmpty(); - OrderedMap ordered = (OrderedMap) map; + OrderedMap ordered = getMap(); try { ordered.firstKey(); fail(); } catch (NoSuchElementException ex) {} - + resetFull(); - ordered = (OrderedMap) map; - Object confirmedFirst = confirmed.keySet().iterator().next(); + ordered = getMap(); + K confirmedFirst = confirmed.keySet().iterator().next(); assertEquals(confirmedFirst, ordered.firstKey()); } - + public void testLastKey() { resetEmpty(); - OrderedMap ordered = (OrderedMap) map; + OrderedMap ordered = getMap(); try { ordered.lastKey(); fail(); } catch (NoSuchElementException ex) {} - + resetFull(); - ordered = (OrderedMap) map; - Object confirmedLast = null; - for (Iterator it = confirmed.keySet().iterator(); it.hasNext();) { + ordered = getMap(); + K confirmedLast = null; + for (Iterator it = confirmed.keySet().iterator(); it.hasNext();) { confirmedLast = it.next(); } assertEquals(confirmedLast, ordered.lastKey()); } - //----------------------------------------------------------------------- + //----------------------------------------------------------------------- public void testNextKey() { resetEmpty(); - OrderedMap ordered = (OrderedMap) map; + OrderedMap ordered = getMap(); assertEquals(null, ordered.nextKey(getOtherKeys()[0])); - if (isAllowNullKey() == false) { + if (!isAllowNullKey()) { try { assertEquals(null, ordered.nextKey(null)); // this is allowed too } catch (NullPointerException ex) {} } else { assertEquals(null, ordered.nextKey(null)); } - + resetFull(); - ordered = (OrderedMap) map; - Iterator it = confirmed.keySet().iterator(); - Object confirmedLast = it.next(); + ordered = getMap(); + Iterator it = confirmed.keySet().iterator(); + K confirmedLast = it.next(); while (it.hasNext()) { - Object confirmedObject = it.next(); + K confirmedObject = it.next(); assertEquals(confirmedObject, ordered.nextKey(confirmedLast)); confirmedLast = confirmedObject; } assertEquals(null, ordered.nextKey(confirmedLast)); - + if (isAllowNullKey() == false) { try { ordered.nextKey(null); @@ -134,10 +149,10 @@ public abstract class AbstractTestOrderedMap extends AbstractTestIterableMap { assertEquals(null, ordered.nextKey(null)); } } - + public void testPreviousKey() { resetEmpty(); - OrderedMap ordered = (OrderedMap) map; + OrderedMap ordered = getMap(); assertEquals(null, ordered.previousKey(getOtherKeys()[0])); if (isAllowNullKey() == false) { try { @@ -146,20 +161,20 @@ public abstract class AbstractTestOrderedMap extends AbstractTestIterableMap { } else { assertEquals(null, ordered.previousKey(null)); } - + resetFull(); - ordered = (OrderedMap) map; - List list = new ArrayList(confirmed.keySet()); + ordered = getMap(); + List list = new ArrayList(confirmed.keySet()); Collections.reverse(list); - Iterator it = list.iterator(); - Object confirmedLast = it.next(); + Iterator it = list.iterator(); + K confirmedLast = it.next(); while (it.hasNext()) { - Object confirmedObject = it.next(); + K confirmedObject = it.next(); assertEquals(confirmedObject, ordered.previousKey(confirmedLast)); confirmedLast = confirmedObject; } assertEquals(null, ordered.previousKey(confirmedLast)); - + if (isAllowNullKey() == false) { try { ordered.previousKey(null); @@ -171,17 +186,17 @@ public abstract class AbstractTestOrderedMap extends AbstractTestIterableMap { } } } - + //----------------------------------------------------------------------- public BulkTest bulkTestOrderedMapIterator() { return new InnerTestOrderedMapIterator(); } - - public class InnerTestOrderedMapIterator extends AbstractTestOrderedMapIterator { + + public class InnerTestOrderedMapIterator extends AbstractTestOrderedMapIterator { public InnerTestOrderedMapIterator() { super("InnerTestOrderedMapIterator"); } - + public boolean supportsRemove() { return AbstractTestOrderedMap.this.isRemoveSupported(); } @@ -189,35 +204,42 @@ public abstract class AbstractTestOrderedMap extends AbstractTestIterableMap { public boolean isGetStructuralModify() { return AbstractTestOrderedMap.this.isGetStructuralModify(); } - + public boolean supportsSetValue() { return AbstractTestOrderedMap.this.isSetValueSupported(); } - public MapIterator makeEmptyMapIterator() { + public OrderedMapIterator makeEmptyIterator() { resetEmpty(); - return ((OrderedMap) AbstractTestOrderedMap.this.map).orderedMapIterator(); + return AbstractTestOrderedMap.this.getMap().mapIterator(); } - public MapIterator makeFullMapIterator() { + public OrderedMapIterator makeObject() { resetFull(); - return ((OrderedMap) AbstractTestOrderedMap.this.map).orderedMapIterator(); + return AbstractTestOrderedMap.this.getMap().mapIterator(); } - - public Map getMap() { + + public OrderedMap getMap() { // assumes makeFullMapIterator() called first - return AbstractTestOrderedMap.this.map; + return AbstractTestOrderedMap.this.getMap(); } - - public Map getConfirmedMap() { + + public Map getConfirmedMap() { // assumes makeFullMapIterator() called first - return AbstractTestOrderedMap.this.confirmed; + return AbstractTestOrderedMap.this.getConfirmed(); } - + public void verify() { super.verify(); AbstractTestOrderedMap.this.verify(); } } - + + /** + * {@inheritDoc} + */ + @Override + public OrderedMap getMap() { + return (OrderedMap) super.getMap(); + } } diff --git a/src/test/org/apache/commons/collections/map/AbstractTestSortedMap.java b/src/test/org/apache/commons/collections/map/AbstractTestSortedMap.java index c6e691b06..b56e37209 100644 --- a/src/test/org/apache/commons/collections/map/AbstractTestSortedMap.java +++ b/src/test/org/apache/commons/collections/map/AbstractTestSortedMap.java @@ -33,21 +33,21 @@ import org.apache.commons.collections.BulkTest; * * @author Stephen Colebourne */ -public abstract class AbstractTestSortedMap extends AbstractTestMap { +public abstract class AbstractTestSortedMap extends AbstractTestMap { /** * JUnit constructor. - * + * * @param testName the test name */ public AbstractTestSortedMap(String testName) { super(testName); } - + //----------------------------------------------------------------------- /** * Can't sort null keys. - * + * * @return false */ public boolean isAllowNullKey() { @@ -56,53 +56,67 @@ public abstract class AbstractTestSortedMap extends AbstractTestMap { /** * SortedMap uses TreeMap as its known comparison. - * + * * @return a map that is known to be valid */ - public Map makeConfirmedMap() { - return new TreeMap(); + public SortedMap makeConfirmedMap() { + return new TreeMap(); } //----------------------------------------------------------------------- public void testComparator() { - SortedMap sm = (SortedMap) makeFullMap(); +// SortedMap sm = makeFullMap(); // no tests I can think of } - + + /** + * {@inheritDoc} + */ + @Override + public abstract SortedMap makeObject(); + + /** + * {@inheritDoc} + */ + @Override + public SortedMap makeFullMap() { + return (SortedMap) super.makeFullMap(); + } + public void testFirstKey() { - SortedMap sm = (SortedMap) makeFullMap(); + SortedMap sm = makeFullMap(); assertSame(sm.keySet().iterator().next(), sm.firstKey()); } - + public void testLastKey() { - SortedMap sm = (SortedMap) makeFullMap(); - Object obj = null; - for (Iterator it = sm.keySet().iterator(); it.hasNext();) { - obj = (Object) it.next(); + SortedMap sm = makeFullMap(); + K obj = null; + for (Iterator it = sm.keySet().iterator(); it.hasNext();) { + obj = it.next(); } assertSame(obj, sm.lastKey()); } - - //----------------------------------------------------------------------- + + //----------------------------------------------------------------------- public BulkTest bulkTestHeadMap() { - return new TestHeadMap(this); + return new TestHeadMap(this); } public BulkTest bulkTestTailMap() { - return new TestTailMap(this); + return new TestTailMap(this); } public BulkTest bulkTestSubMap() { - return new TestSubMap(this); + return new TestSubMap(this); } - public static abstract class TestViewMap extends AbstractTestSortedMap { - protected final AbstractTestMap main; - protected final List subSortedKeys = new ArrayList(); - protected final List subSortedValues = new ArrayList(); - protected final List subSortedNewValues = new ArrayList(); - - public TestViewMap(String name, AbstractTestMap main) { + public static abstract class TestViewMap extends AbstractTestSortedMap { + protected final AbstractTestMap main; + protected final List subSortedKeys = new ArrayList(); + protected final List subSortedValues = new ArrayList(); + protected final List subSortedNewValues = new ArrayList(); + + public TestViewMap(String name, AbstractTestMap main) { super(name); this.main = main; } @@ -130,17 +144,20 @@ public abstract class AbstractTestSortedMap extends AbstractTestMap { public BulkTest bulkTestSubMap() { return null; // block infinite recursion } - - public Object[] getSampleKeys() { - return subSortedKeys.toArray(); + + @SuppressWarnings("unchecked") + public K[] getSampleKeys() { + return (K[]) subSortedKeys.toArray(); } - public Object[] getSampleValues() { - return subSortedValues.toArray(); + @SuppressWarnings("unchecked") + public V[] getSampleValues() { + return (V[]) subSortedValues.toArray(); } - public Object[] getNewSampleValues() { - return subSortedNewValues.toArray(); + @SuppressWarnings("unchecked") + public V[] getNewSampleValues() { + return (V[]) subSortedNewValues.toArray(); } - + public boolean isAllowNullKey() { return main.isAllowNullKey(); } @@ -176,16 +193,16 @@ public abstract class AbstractTestSortedMap extends AbstractTestMap { // super.testFullMapCompatibility(); // } } - - public static class TestHeadMap extends TestViewMap { + + public static class TestHeadMap extends TestViewMap { static final int SUBSIZE = 6; - final Object toKey; - - public TestHeadMap(AbstractTestMap main) { + final K toKey; + + public TestHeadMap(AbstractTestMap main) { super("SortedMap.HeadMap", main); - SortedMap sm = (SortedMap) main.makeFullMap(); - for (Iterator it = sm.entrySet().iterator(); it.hasNext();) { - Map.Entry entry = (Map.Entry) it.next(); + Map sm = main.makeFullMap(); + for (Iterator> it = sm.entrySet().iterator(); it.hasNext();) { + Map.Entry entry = it.next(); this.subSortedKeys.add(entry.getKey()); this.subSortedValues.add(entry.getValue()); } @@ -194,18 +211,18 @@ public abstract class AbstractTestSortedMap extends AbstractTestMap { this.subSortedValues.subList(SUBSIZE, this.subSortedValues.size()).clear(); this.subSortedNewValues.addAll(Arrays.asList(main.getNewSampleValues()).subList(0, SUBSIZE)); } - public Map makeEmptyMap() { + public SortedMap makeObject() { // done this way so toKey is correctly set in the returned map - return ((SortedMap) main.makeEmptyMap()).headMap(toKey); + return ((SortedMap) main.makeObject()).headMap(toKey); } - public Map makeFullMap() { - return ((SortedMap) main.makeFullMap()).headMap(toKey); + public SortedMap makeFullMap() { + return ((SortedMap) main.makeFullMap()).headMap(toKey); } public void testHeadMapOutOfRange() { if (isPutAddSupported() == false) return; resetEmpty(); try { - ((SortedMap) map).put(toKey, subSortedValues.get(0)); + getMap().put(toKey, subSortedValues.get(0)); fail(); } catch (IllegalArgumentException ex) {} verify(); @@ -225,17 +242,17 @@ public abstract class AbstractTestSortedMap extends AbstractTestMap { // "D:/dev/collections/data/test/FixedSizeSortedMap.fullCollection.version3.1.HeadMapView.obj"); // } } - - public static class TestTailMap extends TestViewMap { + + public static class TestTailMap extends TestViewMap { static final int SUBSIZE = 6; - final Object fromKey; - final Object invalidKey; - - public TestTailMap(AbstractTestMap main) { + final K fromKey; + final K invalidKey; + + public TestTailMap(AbstractTestMap main) { super("SortedMap.TailMap", main); - SortedMap sm = (SortedMap) main.makeFullMap(); - for (Iterator it = sm.entrySet().iterator(); it.hasNext();) { - Map.Entry entry = (Map.Entry) it.next(); + Map sm = main.makeFullMap(); + for (Iterator> it = sm.entrySet().iterator(); it.hasNext();) { + Map.Entry entry = it.next(); this.subSortedKeys.add(entry.getKey()); this.subSortedValues.add(entry.getValue()); } @@ -245,18 +262,18 @@ public abstract class AbstractTestSortedMap extends AbstractTestMap { this.subSortedValues.subList(0, this.subSortedValues.size() - SUBSIZE).clear(); this.subSortedNewValues.addAll(Arrays.asList(main.getNewSampleValues()).subList(0, SUBSIZE)); } - public Map makeEmptyMap() { + public SortedMap makeObject() { // done this way so toKey is correctly set in the returned map - return ((SortedMap) main.makeEmptyMap()).tailMap(fromKey); + return ((SortedMap) main.makeObject()).tailMap(fromKey); } - public Map makeFullMap() { - return ((SortedMap) main.makeFullMap()).tailMap(fromKey); + public SortedMap makeFullMap() { + return ((SortedMap) main.makeFullMap()).tailMap(fromKey); } public void testTailMapOutOfRange() { if (isPutAddSupported() == false) return; resetEmpty(); try { - ((SortedMap) map).put(invalidKey, subSortedValues.get(0)); + getMap().put(invalidKey, subSortedValues.get(0)); fail(); } catch (IllegalArgumentException ex) {} verify(); @@ -276,45 +293,45 @@ public abstract class AbstractTestSortedMap extends AbstractTestMap { // "D:/dev/collections/data/test/FixedSizeSortedMap.fullCollection.version3.1.TailMapView.obj"); // } } - - public static class TestSubMap extends TestViewMap { + + public static class TestSubMap extends TestViewMap { static final int SUBSIZE = 3; - final Object fromKey; - final Object toKey; - - public TestSubMap(AbstractTestMap main) { + final K fromKey; + final K toKey; + + public TestSubMap(AbstractTestMap main) { super("SortedMap.SubMap", main); - SortedMap sm = (SortedMap) main.makeFullMap(); - for (Iterator it = sm.entrySet().iterator(); it.hasNext();) { - Map.Entry entry = (Map.Entry) it.next(); + Map sm = main.makeFullMap(); + for (Iterator> it = sm.entrySet().iterator(); it.hasNext();) { + Map.Entry entry = it.next(); this.subSortedKeys.add(entry.getKey()); this.subSortedValues.add(entry.getValue()); } this.fromKey = this.subSortedKeys.get(SUBSIZE); this.toKey = this.subSortedKeys.get(this.subSortedKeys.size() - SUBSIZE); - + this.subSortedKeys.subList(0, SUBSIZE).clear(); this.subSortedKeys.subList(this.subSortedKeys.size() - SUBSIZE, this.subSortedKeys.size()).clear(); - + this.subSortedValues.subList(0, SUBSIZE).clear(); this.subSortedValues.subList(this.subSortedValues.size() - SUBSIZE, this.subSortedValues.size()).clear(); - + this.subSortedNewValues.addAll(Arrays.asList(main.getNewSampleValues()).subList( SUBSIZE, this.main.getNewSampleValues().length - SUBSIZE)); } - - public Map makeEmptyMap() { + + public SortedMap makeObject() { // done this way so toKey is correctly set in the returned map - return ((SortedMap) main.makeEmptyMap()).subMap(fromKey, toKey); + return ((SortedMap) main.makeObject()).subMap(fromKey, toKey); } - public Map makeFullMap() { - return ((SortedMap) main.makeFullMap()).subMap(fromKey, toKey); + public SortedMap makeFullMap() { + return ((SortedMap) main.makeFullMap()).subMap(fromKey, toKey); } public void testSubMapOutOfRange() { if (isPutAddSupported() == false) return; resetEmpty(); try { - ((SortedMap) map).put(toKey, subSortedValues.get(0)); + getMap().put(toKey, subSortedValues.get(0)); fail(); } catch (IllegalArgumentException ex) {} verify(); @@ -334,5 +351,20 @@ public abstract class AbstractTestSortedMap extends AbstractTestMap { // "D:/dev/collections/data/test/TransformedSortedMap.fullCollection.version3.1.SubMapView.obj"); // } } - + + /** + * {@inheritDoc} + */ + @Override + public SortedMap getMap() { + return (SortedMap) super.getMap(); + } + + /** + * {@inheritDoc} + */ + @Override + public SortedMap getConfirmed() { + return (SortedMap) super.getConfirmed(); + } } diff --git a/src/test/org/apache/commons/collections/map/TestCaseInsensitiveMap.java b/src/test/org/apache/commons/collections/map/TestCaseInsensitiveMap.java index 3056c5303..2670063e3 100644 --- a/src/test/org/apache/commons/collections/map/TestCaseInsensitiveMap.java +++ b/src/test/org/apache/commons/collections/map/TestCaseInsensitiveMap.java @@ -33,7 +33,7 @@ import org.apache.commons.collections.BulkTest; * * @author Commons-Collections team */ -public class TestCaseInsensitiveMap extends AbstractTestIterableMap { +public class TestCaseInsensitiveMap extends AbstractTestIterableMap { public TestCaseInsensitiveMap(String testName) { super(testName); @@ -42,74 +42,77 @@ public class TestCaseInsensitiveMap extends AbstractTestIterableMap { public static void main(String[] args) { TestRunner.run(suite()); } - + public static Test suite() { return BulkTest.makeSuite(TestCaseInsensitiveMap.class); } - public Map makeEmptyMap() { - return new CaseInsensitiveMap(); + public CaseInsensitiveMap makeObject() { + return new CaseInsensitiveMap(); } - + public String getCompatibilityVersion() { return "3"; } - + //------------------------------------------------------------------------- - + + @SuppressWarnings("unchecked") public void testCaseInsensitive() { - Map map = new CaseInsensitiveMap(); - map.put("One", "One"); - map.put("Two", "Two"); - assertEquals("One", (String) map.get("one")); - assertEquals("One", (String) map.get("oNe")); - map.put("two", "Three"); - assertEquals("Three", (String) map.get("Two")); - } - + Map map = makeObject(); + map.put((K) "One", (V) "One"); + map.put((K) "Two", (V) "Two"); + assertEquals("One", map.get("one")); + assertEquals("One", map.get("oNe")); + map.put((K) "two", (V) "Three"); + assertEquals("Three", map.get("Two")); + } + + @SuppressWarnings("unchecked") public void testNullHandling() { - Map map = new CaseInsensitiveMap(); - map.put("One", "One"); - map.put("Two", "Two"); - map.put(null, "Three"); - assertEquals("Three", (String) map.get(null)); - map.put(null, "Four"); - assertEquals("Four", (String) map.get(null)); - Set keys = map.keySet(); + Map map = makeObject(); + map.put((K) "One", (V) "One"); + map.put((K) "Two", (V) "Two"); + map.put(null, (V) "Three"); + assertEquals("Three", map.get(null)); + map.put(null, (V) "Four"); + assertEquals("Four", map.get(null)); + Set keys = map.keySet(); assertTrue(keys.contains("one")); assertTrue(keys.contains("two")); assertTrue(keys.contains(null)); assertEquals(3, keys.size()); } - + public void testPutAll() { - Map map = new HashMap(); + Map map = new HashMap(); map.put("One", "One"); map.put("Two", "Two"); map.put("one", "Three"); map.put(null, "Four"); map.put(new Integer(20), "Five"); - Map caseInsensitiveMap = new CaseInsensitiveMap(map); + Map caseInsensitiveMap = new CaseInsensitiveMap(map); assertEquals(4, caseInsensitiveMap.size()); // ones collapsed - Set keys = caseInsensitiveMap.keySet(); + Set keys = caseInsensitiveMap.keySet(); assertTrue(keys.contains("one")); assertTrue(keys.contains("two")); assertTrue(keys.contains(null)); assertTrue(keys.contains(Integer.toString(20))); assertEquals(4, keys.size()); - assertTrue(!caseInsensitiveMap.containsValue("One") + assertTrue(!caseInsensitiveMap.containsValue("One") || !caseInsensitiveMap.containsValue("Three")); // ones collaped assertEquals("Four", caseInsensitiveMap.get(null)); - } + } + @SuppressWarnings("unchecked") public void testClone() { - CaseInsensitiveMap map = new CaseInsensitiveMap(10); - map.put("1", "1"); - Map cloned = (Map) map.clone(); + CaseInsensitiveMap map = new CaseInsensitiveMap(10); + map.put((K) "1", (V) "1"); + CaseInsensitiveMap cloned = map.clone(); assertEquals(map.size(), cloned.size()); assertSame(map.get("1"), cloned.get("1")); } - + /* public void testCreate() throws Exception { resetEmpty(); diff --git a/src/test/org/apache/commons/collections/map/TestFixedSizeSortedMap.java b/src/test/org/apache/commons/collections/map/TestFixedSizeSortedMap.java index b199de9b0..5eaffce98 100644 --- a/src/test/org/apache/commons/collections/map/TestFixedSizeSortedMap.java +++ b/src/test/org/apache/commons/collections/map/TestFixedSizeSortedMap.java @@ -16,7 +16,6 @@ */ package org.apache.commons.collections.map; -import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; @@ -33,7 +32,7 @@ import org.apache.commons.collections.BulkTest; * * @author Stephen Colebourne */ -public class TestFixedSizeSortedMap extends AbstractTestSortedMap { +public class TestFixedSizeSortedMap extends AbstractTestSortedMap { public TestFixedSizeSortedMap(String testName) { super(testName); @@ -49,16 +48,16 @@ public class TestFixedSizeSortedMap extends AbstractTestSortedMap { } //----------------------------------------------------------------------- - public Map makeEmptyMap() { - return FixedSizeSortedMap.decorate(new TreeMap()); + public SortedMap makeObject() { + return FixedSizeSortedMap.decorate(new TreeMap()); } - public Map makeFullMap() { - SortedMap map = new TreeMap(); + public SortedMap makeFullMap() { + SortedMap map = new TreeMap(); addSampleMappings(map); return FixedSizeSortedMap.decorate(map); } - + public boolean isSubMapViewsSerializable() { // TreeMap sub map views have a bug in deserialization. return false; @@ -76,7 +75,7 @@ public class TestFixedSizeSortedMap extends AbstractTestSortedMap { public String getCompatibilityVersion() { return "3.1"; } - + // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk( diff --git a/src/test/org/apache/commons/collections/map/TestFlat3Map.java b/src/test/org/apache/commons/collections/map/TestFlat3Map.java index 6885103a1..7ff3d47a6 100644 --- a/src/test/org/apache/commons/collections/map/TestFlat3Map.java +++ b/src/test/org/apache/commons/collections/map/TestFlat3Map.java @@ -27,6 +27,7 @@ import junit.framework.Test; import junit.textui.TestRunner; import org.apache.commons.collections.BulkTest; +import org.apache.commons.collections.IterableMap; import org.apache.commons.collections.MapIterator; import org.apache.commons.collections.iterators.AbstractTestMapIterator; @@ -37,7 +38,7 @@ import org.apache.commons.collections.iterators.AbstractTestMapIterator; * * @author Stephen Colebourne */ -public class TestFlat3Map extends AbstractTestIterableMap { +public class TestFlat3Map extends AbstractTestIterableMap { private static final Integer ONE = new Integer(1); private static final Integer TWO = new Integer(2); @@ -45,7 +46,7 @@ public class TestFlat3Map extends AbstractTestIterableMap { private static final String TEN = "10"; private static final String TWENTY = "20"; private static final String THIRTY = "30"; - + public TestFlat3Map(String testName) { super(testName); } @@ -53,75 +54,80 @@ public class TestFlat3Map extends AbstractTestIterableMap { public static void main(String[] args) { TestRunner.run(suite()); } - + public static Test suite() { return BulkTest.makeSuite(TestFlat3Map.class); } - public Map makeEmptyMap() { - return new Flat3Map(); + public Flat3Map makeObject() { + return new Flat3Map(); } //----------------------------------------------------------------------- + @SuppressWarnings("unchecked") public void testEquals1() { - Flat3Map map1 = new Flat3Map(); - map1.put("a", "testA"); - map1.put("b", "testB"); - Flat3Map map2 = new Flat3Map(); - map2.put("a", "testB"); - map2.put("b", "testA"); + Flat3Map map1 = makeObject(); + map1.put((K) "a", (V) "testA"); + map1.put((K) "b", (V) "testB"); + Flat3Map map2 = makeObject(); + map2.put((K) "a", (V) "testB"); + map2.put((K) "b", (V) "testA"); assertEquals(false, map1.equals(map2)); } + @SuppressWarnings("unchecked") public void testEquals2() { - Flat3Map map1 = new Flat3Map(); - map1.put("a", "testA"); - map1.put("b", "testB"); - Flat3Map map2 = new Flat3Map(); - map2.put("a", "testB"); - map2.put("c", "testA"); + Flat3Map map1 = makeObject(); + map1.put((K) "a", (V) "testA"); + map1.put((K) "b", (V) "testB"); + Flat3Map map2 = makeObject(); + map2.put((K) "a", (V) "testB"); + map2.put((K) "c", (V) "testA"); assertEquals(false, map1.equals(map2)); } + @SuppressWarnings("unchecked") public void testClone2() { - Flat3Map map = new Flat3Map(); + Flat3Map map = makeObject(); assertEquals(0, map.size()); - map.put(ONE, TEN); - map.put(TWO, TWENTY); + map.put((K) ONE, (V) TEN); + map.put((K) TWO, (V) TWENTY); assertEquals(2, map.size()); assertEquals(true, map.containsKey(ONE)); assertEquals(true, map.containsKey(TWO)); assertSame(TEN, map.get(ONE)); assertSame(TWENTY, map.get(TWO)); - // clone works (size = 2) - Flat3Map cloned = (Flat3Map) map.clone(); + // clone works (size = 2) + Flat3Map cloned = map.clone(); assertEquals(2, cloned.size()); assertEquals(true, cloned.containsKey(ONE)); assertEquals(true, cloned.containsKey(TWO)); assertSame(TEN, cloned.get(ONE)); assertSame(TWENTY, cloned.get(TWO)); - + // change original doesn't change clone - map.put(TEN, ONE); - map.put(TWENTY, TWO); + map.put((K) TEN, (V) ONE); + map.put((K) TWENTY, (V) TWO); assertEquals(4, map.size()); assertEquals(2, cloned.size()); assertEquals(true, cloned.containsKey(ONE)); assertEquals(true, cloned.containsKey(TWO)); assertSame(TEN, cloned.get(ONE)); assertSame(TWENTY, cloned.get(TWO)); - } + } + + @SuppressWarnings("unchecked") public void testClone4() { - Flat3Map map = new Flat3Map(); + Flat3Map map = makeObject(); assertEquals(0, map.size()); - map.put(ONE, TEN); - map.put(TWO, TWENTY); - map.put(TEN, ONE); - map.put(TWENTY, TWO); - + map.put((K) ONE, (V) TEN); + map.put((K) TWO, (V) TWENTY); + map.put((K) TEN, (V) ONE); + map.put((K) TWENTY, (V) TWO); + // clone works (size = 4) - Flat3Map cloned = (Flat3Map) map.clone(); + Flat3Map cloned = map.clone(); assertEquals(4, map.size()); assertEquals(4, cloned.size()); assertEquals(true, cloned.containsKey(ONE)); @@ -132,7 +138,7 @@ public class TestFlat3Map extends AbstractTestIterableMap { assertSame(TWENTY, cloned.get(TWO)); assertSame(ONE, cloned.get(TEN)); assertSame(TWO, cloned.get(TWENTY)); - + // change original doesn't change clone map.clear(); assertEquals(0, map.size()); @@ -146,9 +152,10 @@ public class TestFlat3Map extends AbstractTestIterableMap { assertSame(ONE, cloned.get(TEN)); assertSame(TWO, cloned.get(TWENTY)); } - + + @SuppressWarnings("unchecked") public void testSerialisation0() throws Exception { - Flat3Map map = new Flat3Map(); + Flat3Map map = makeObject(); ByteArrayOutputStream bout = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(bout); out.writeObject(map); @@ -161,12 +168,13 @@ public class TestFlat3Map extends AbstractTestIterableMap { assertEquals(0, map.size()); assertEquals(0, ser.size()); } - + + @SuppressWarnings("unchecked") public void testSerialisation2() throws Exception { - Flat3Map map = new Flat3Map(); - map.put(ONE, TEN); - map.put(TWO, TWENTY); - + Flat3Map map = makeObject(); + map.put((K) ONE, (V) TEN); + map.put((K) TWO, (V) TWENTY); + ByteArrayOutputStream bout = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(bout); out.writeObject(map); @@ -183,14 +191,15 @@ public class TestFlat3Map extends AbstractTestIterableMap { assertEquals(TEN, ser.get(ONE)); assertEquals(TWENTY, ser.get(TWO)); } - + + @SuppressWarnings("unchecked") public void testSerialisation4() throws Exception { - Flat3Map map = new Flat3Map(); - map.put(ONE, TEN); - map.put(TWO, TWENTY); - map.put(TEN, ONE); - map.put(TWENTY, TWO); - + Flat3Map map = makeObject(); + map.put((K) ONE, (V) TEN); + map.put((K) TWO, (V) TWENTY); + map.put((K) TEN, (V) ONE); + map.put((K) TWENTY, (V) TWO); + ByteArrayOutputStream bout = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(bout); out.writeObject(map); @@ -213,15 +222,16 @@ public class TestFlat3Map extends AbstractTestIterableMap { } //----------------------------------------------------------------------- + @SuppressWarnings("unchecked") public void testEntryIteratorSetValue1() throws Exception { - Flat3Map map = new Flat3Map(); - map.put(ONE, TEN); - map.put(TWO, TWENTY); - map.put(THREE, THIRTY); - - Iterator it = map.entrySet().iterator(); - Map.Entry entry = (Map.Entry) it.next(); - entry.setValue("NewValue"); + Flat3Map map = makeObject(); + map.put((K) ONE, (V) TEN); + map.put((K) TWO, (V) TWENTY); + map.put((K) THREE, (V) THIRTY); + + Iterator> it = map.entrySet().iterator(); + Map.Entry entry = it.next(); + entry.setValue((V) "NewValue"); assertEquals(3, map.size()); assertEquals(true, map.containsKey(ONE)); assertEquals(true, map.containsKey(TWO)); @@ -231,16 +241,17 @@ public class TestFlat3Map extends AbstractTestIterableMap { assertEquals(THIRTY, map.get(THREE)); } + @SuppressWarnings("unchecked") public void testEntryIteratorSetValue2() throws Exception { - Flat3Map map = new Flat3Map(); - map.put(ONE, TEN); - map.put(TWO, TWENTY); - map.put(THREE, THIRTY); - - Iterator it = map.entrySet().iterator(); + Flat3Map map = makeObject(); + map.put((K) ONE, (V) TEN); + map.put((K) TWO, (V) TWENTY); + map.put((K) THREE, (V) THIRTY); + + Iterator> it = map.entrySet().iterator(); it.next(); - Map.Entry entry = (Map.Entry) it.next(); - entry.setValue("NewValue"); + Map.Entry entry = it.next(); + entry.setValue((V) "NewValue"); assertEquals(3, map.size()); assertEquals(true, map.containsKey(ONE)); assertEquals(true, map.containsKey(TWO)); @@ -250,17 +261,18 @@ public class TestFlat3Map extends AbstractTestIterableMap { assertEquals(THIRTY, map.get(THREE)); } + @SuppressWarnings("unchecked") public void testEntryIteratorSetValue3() throws Exception { - Flat3Map map = new Flat3Map(); - map.put(ONE, TEN); - map.put(TWO, TWENTY); - map.put(THREE, THIRTY); - - Iterator it = map.entrySet().iterator(); + Flat3Map map = makeObject(); + map.put((K) ONE, (V) TEN); + map.put((K) TWO, (V) TWENTY); + map.put((K) THREE, (V) THIRTY); + + Iterator> it = map.entrySet().iterator(); it.next(); it.next(); - Map.Entry entry = (Map.Entry) it.next(); - entry.setValue("NewValue"); + Map.Entry entry = it.next(); + entry.setValue((V) "NewValue"); assertEquals(3, map.size()); assertEquals(true, map.containsKey(ONE)); assertEquals(true, map.containsKey(TWO)); @@ -271,15 +283,16 @@ public class TestFlat3Map extends AbstractTestIterableMap { } //----------------------------------------------------------------------- + @SuppressWarnings("unchecked") public void testMapIteratorSetValue1() throws Exception { - Flat3Map map = new Flat3Map(); - map.put(ONE, TEN); - map.put(TWO, TWENTY); - map.put(THREE, THIRTY); - - MapIterator it = map.mapIterator(); + Flat3Map map = makeObject(); + map.put((K) ONE, (V) TEN); + map.put((K) TWO, (V) TWENTY); + map.put((K) THREE, (V) THIRTY); + + MapIterator it = map.mapIterator(); it.next(); - it.setValue("NewValue"); + it.setValue((V) "NewValue"); assertEquals(3, map.size()); assertEquals(true, map.containsKey(ONE)); assertEquals(true, map.containsKey(TWO)); @@ -289,16 +302,17 @@ public class TestFlat3Map extends AbstractTestIterableMap { assertEquals(THIRTY, map.get(THREE)); } + @SuppressWarnings("unchecked") public void testMapIteratorSetValue2() throws Exception { - Flat3Map map = new Flat3Map(); - map.put(ONE, TEN); - map.put(TWO, TWENTY); - map.put(THREE, THIRTY); - - MapIterator it = map.mapIterator(); + Flat3Map map = makeObject(); + map.put((K) ONE, (V) TEN); + map.put((K) TWO, (V) TWENTY); + map.put((K) THREE, (V) THIRTY); + + MapIterator it = map.mapIterator(); it.next(); it.next(); - it.setValue("NewValue"); + it.setValue((V) "NewValue"); assertEquals(3, map.size()); assertEquals(true, map.containsKey(ONE)); assertEquals(true, map.containsKey(TWO)); @@ -308,17 +322,18 @@ public class TestFlat3Map extends AbstractTestIterableMap { assertEquals(THIRTY, map.get(THREE)); } + @SuppressWarnings("unchecked") public void testMapIteratorSetValue3() throws Exception { - Flat3Map map = new Flat3Map(); - map.put(ONE, TEN); - map.put(TWO, TWENTY); - map.put(THREE, THIRTY); - - MapIterator it = map.mapIterator(); + Flat3Map map = makeObject(); + map.put((K) ONE, (V) TEN); + map.put((K) TWO, (V) TWENTY); + map.put((K) THREE, (V) THIRTY); + + MapIterator it = map.mapIterator(); it.next(); it.next(); it.next(); - it.setValue("NewValue"); + it.setValue((V) "NewValue"); assertEquals(3, map.size()); assertEquals(true, map.containsKey(ONE)); assertEquals(true, map.containsKey(TWO)); @@ -332,16 +347,16 @@ public class TestFlat3Map extends AbstractTestIterableMap { public BulkTest bulkTestMapIterator() { return new TestFlatMapIterator(); } - - public class TestFlatMapIterator extends AbstractTestMapIterator { + + public class TestFlatMapIterator extends AbstractTestMapIterator { public TestFlatMapIterator() { super("TestFlatMapIterator"); } - - public Object[] addSetValues() { + + public V[] addSetValues() { return TestFlat3Map.this.getNewSampleValues(); } - + public boolean supportsRemove() { return TestFlat3Map.this.isRemoveSupported(); } @@ -350,32 +365,32 @@ public class TestFlat3Map extends AbstractTestIterableMap { return TestFlat3Map.this.isSetValueSupported(); } - public MapIterator makeEmptyMapIterator() { + public MapIterator makeEmptyIterator() { resetEmpty(); - return ((Flat3Map) TestFlat3Map.this.map).mapIterator(); + return TestFlat3Map.this.getMap().mapIterator(); } - public MapIterator makeFullMapIterator() { + public MapIterator makeObject() { resetFull(); - return ((Flat3Map) TestFlat3Map.this.map).mapIterator(); + return TestFlat3Map.this.getMap().mapIterator(); } - - public Map getMap() { + + public IterableMap getMap() { // assumes makeFullMapIterator() called first - return TestFlat3Map.this.map; + return TestFlat3Map.this.getMap(); } - - public Map getConfirmedMap() { + + public Map getConfirmedMap() { // assumes makeFullMapIterator() called first - return TestFlat3Map.this.confirmed; + return TestFlat3Map.this.getConfirmed(); } - + public void verify() { super.verify(); TestFlat3Map.this.verify(); } } - + public String getCompatibilityVersion() { return "3.1"; } diff --git a/src/test/org/apache/commons/collections/map/TestHashedMap.java b/src/test/org/apache/commons/collections/map/TestHashedMap.java index 143947f84..f22220f21 100644 --- a/src/test/org/apache/commons/collections/map/TestHashedMap.java +++ b/src/test/org/apache/commons/collections/map/TestHashedMap.java @@ -16,8 +16,6 @@ */ package org.apache.commons.collections.map; -import java.util.Map; - import junit.framework.Test; import junit.textui.TestRunner; @@ -30,7 +28,7 @@ import org.apache.commons.collections.BulkTest; * * @author Stephen Colebourne */ -public class TestHashedMap extends AbstractTestIterableMap { +public class TestHashedMap extends AbstractTestIterableMap { public TestHashedMap(String testName) { super(testName); @@ -39,29 +37,30 @@ public class TestHashedMap extends AbstractTestIterableMap { public static void main(String[] args) { TestRunner.run(suite()); } - + public static Test suite() { return BulkTest.makeSuite(TestHashedMap.class); } - public Map makeEmptyMap() { - return new HashedMap(); + public HashedMap makeObject() { + return new HashedMap(); } - + public String getCompatibilityVersion() { return "3"; } + @SuppressWarnings("unchecked") public void testClone() { - HashedMap map = new HashedMap(10); - map.put("1", "1"); - Map cloned = (Map) map.clone(); + HashedMap map = new HashedMap(10); + map.put((K) "1", (V) "1"); + HashedMap cloned = map.clone(); assertEquals(map.size(), cloned.size()); assertSame(map.get("1"), cloned.get("1")); } public void testInternalState() { - HashedMap map = new HashedMap(42, 0.75f); + HashedMap map = new HashedMap(42, 0.75f); assertEquals(0.75f, map.loadFactor, 0.1f); assertEquals(0, map.size); assertEquals(64, map.data.length); diff --git a/src/test/org/apache/commons/collections/map/TestIdentityMap.java b/src/test/org/apache/commons/collections/map/TestIdentityMap.java index b791e72bf..ba303729f 100644 --- a/src/test/org/apache/commons/collections/map/TestIdentityMap.java +++ b/src/test/org/apache/commons/collections/map/TestIdentityMap.java @@ -35,8 +35,8 @@ import org.apache.commons.collections.IterableMap; * * @author Stephen Colebourne */ -public class TestIdentityMap extends AbstractTestObject { - +public class TestIdentityMap extends AbstractTestObject { + private static final Integer I1A = new Integer(1); private static final Integer I1B = new Integer(1); private static final Integer I2A = new Integer(2); @@ -49,26 +49,27 @@ public class TestIdentityMap extends AbstractTestObject { public static void main(String[] args) { TestRunner.run(suite()); } - + public static Test suite() { return new TestSuite(TestIdentityMap.class); // return BulkTest.makeSuite(TestIdentityMap.class); // causes race condition! } - - public Object makeObject() { - return new IdentityMap(); + + public IdentityMap makeObject() { + return new IdentityMap(); } - + public String getCompatibilityVersion() { return "3"; } - + //----------------------------------------------------------------------- + @SuppressWarnings("unchecked") public void testBasics() { - IterableMap map = new IdentityMap(); + IterableMap map = new IdentityMap(); assertEquals(0, map.size()); - - map.put(I1A, I2A); + + map.put((K) I1A, (V) I2A); assertEquals(1, map.size()); assertSame(I2A, map.get(I1A)); assertSame(null, map.get(I1B)); @@ -76,8 +77,8 @@ public class TestIdentityMap extends AbstractTestObject { assertEquals(false, map.containsKey(I1B)); assertEquals(true, map.containsValue(I2A)); assertEquals(false, map.containsValue(I2B)); - - map.put(I1A, I2B); + + map.put((K) I1A, (V) I2B); assertEquals(1, map.size()); assertSame(I2B, map.get(I1A)); assertSame(null, map.get(I1B)); @@ -85,8 +86,8 @@ public class TestIdentityMap extends AbstractTestObject { assertEquals(false, map.containsKey(I1B)); assertEquals(false, map.containsValue(I2A)); assertEquals(true, map.containsValue(I2B)); - - map.put(I1B, I2B); + + map.put((K) I1B, (V) I2B); assertEquals(2, map.size()); assertSame(I2B, map.get(I1A)); assertSame(I2B, map.get(I1B)); @@ -95,45 +96,48 @@ public class TestIdentityMap extends AbstractTestObject { assertEquals(false, map.containsValue(I2A)); assertEquals(true, map.containsValue(I2B)); } - + //----------------------------------------------------------------------- + @SuppressWarnings("unchecked") public void testHashEntry() { - IterableMap map = new IdentityMap(); - - map.put(I1A, I2A); - map.put(I1B, I2A); - - Map.Entry entry1 = (Map.Entry) map.entrySet().iterator().next(); - Iterator it = map.entrySet().iterator(); - Map.Entry entry2 = (Map.Entry) it.next(); - Map.Entry entry3 = (Map.Entry) it.next(); - + IterableMap map = new IdentityMap(); + + map.put((K) I1A, (V) I2A); + map.put((K) I1B, (V) I2A); + + Map.Entry entry1 = map.entrySet().iterator().next(); + Iterator> it = map.entrySet().iterator(); + Map.Entry entry2 = it.next(); + Map.Entry entry3 = it.next(); + assertEquals(true, entry1.equals(entry2)); assertEquals(true, entry2.equals(entry1)); assertEquals(false, entry1.equals(entry3)); } - + /** * Compare the current serialized form of the Map * against the canonical version in SVN. */ + @SuppressWarnings("unchecked") public void testEmptyMapCompatibility() throws IOException, ClassNotFoundException { // test to make sure the canonical form has been preserved - Map map = (Map) makeObject(); + Map map = makeObject(); if (map instanceof Serializable && !skipSerializedCanonicalTests()) { Map map2 = (Map) readExternalFormFromDisk(getCanonicalEmptyCollectionName(map)); assertEquals("Map is empty", 0, map2.size()); } } + @SuppressWarnings("unchecked") public void testClone() { - IdentityMap map = new IdentityMap(10); - map.put("1", "1"); - Map cloned = (Map) map.clone(); + IdentityMap map = new IdentityMap(10); + map.put((K) "1", (V) "1"); + Map cloned = map.clone(); assertEquals(map.size(), cloned.size()); assertSame(map.get("1"), cloned.get("1")); } - + // public void testCreate() throws Exception { // Map map = new IdentityMap(); // writeExternalFormToDisk((java.io.Serializable) map, "D:/dev/collections/data/test/IdentityMap.emptyCollection.version3.obj"); diff --git a/src/test/org/apache/commons/collections/map/TestLRUMap.java b/src/test/org/apache/commons/collections/map/TestLRUMap.java index c2ea54526..6df45ec8c 100644 --- a/src/test/org/apache/commons/collections/map/TestLRUMap.java +++ b/src/test/org/apache/commons/collections/map/TestLRUMap.java @@ -37,7 +37,7 @@ import org.apache.commons.collections.ResettableIterator; * * @author Stephen Colebourne */ -public class TestLRUMap extends AbstractTestOrderedMap { +public class TestLRUMap extends AbstractTestOrderedMap { public TestLRUMap(String testName) { super(testName); @@ -46,19 +46,27 @@ public class TestLRUMap extends AbstractTestOrderedMap { public static void main(String[] args) { TestRunner.run(suite()); } - + public static Test suite() { return BulkTest.makeSuite(TestLRUMap.class); } - public Map makeEmptyMap() { - return new LRUMap(); + public LRUMap makeObject() { + return new LRUMap(); + } + + /** + * {@inheritDoc} + */ + @Override + public LRUMap makeFullMap() { + return (LRUMap) super.makeFullMap(); } public boolean isGetStructuralModify() { return true; } - + public String getCompatibilityVersion() { return "3"; } @@ -66,169 +74,174 @@ public class TestLRUMap extends AbstractTestOrderedMap { //----------------------------------------------------------------------- public void testLRU() { if (isPutAddSupported() == false || isPutChangeSupported() == false) return; - Object[] keys = getSampleKeys(); - Object[] values = getSampleValues(); - Iterator it = null; - - LRUMap map = new LRUMap(2); + K[] keys = getSampleKeys(); + V[] values = getSampleValues(); + Iterator kit; + Iterator vit; + + LRUMap map = new LRUMap(2); assertEquals(0, map.size()); assertEquals(false, map.isFull()); assertEquals(2, map.maxSize()); - + map.put(keys[0], values[0]); assertEquals(1, map.size()); assertEquals(false, map.isFull()); assertEquals(2, map.maxSize()); - + map.put(keys[1], values[1]); assertEquals(2, map.size()); assertEquals(true, map.isFull()); assertEquals(2, map.maxSize()); - it = map.keySet().iterator(); - assertSame(keys[0], it.next()); - assertSame(keys[1], it.next()); - it = map.values().iterator(); - assertSame(values[0], it.next()); - assertSame(values[1], it.next()); + kit = map.keySet().iterator(); + assertSame(keys[0], kit.next()); + assertSame(keys[1], kit.next()); + vit = map.values().iterator(); + assertSame(values[0], vit.next()); + assertSame(values[1], vit.next()); map.put(keys[2], values[2]); assertEquals(2, map.size()); assertEquals(true, map.isFull()); assertEquals(2, map.maxSize()); - it = map.keySet().iterator(); - assertSame(keys[1], it.next()); - assertSame(keys[2], it.next()); - it = map.values().iterator(); - assertSame(values[1], it.next()); - assertSame(values[2], it.next()); + kit = map.keySet().iterator(); + assertSame(keys[1], kit.next()); + assertSame(keys[2], kit.next()); + vit = map.values().iterator(); + assertSame(values[1], vit.next()); + assertSame(values[2], vit.next()); map.put(keys[2], values[0]); assertEquals(2, map.size()); assertEquals(true, map.isFull()); assertEquals(2, map.maxSize()); - it = map.keySet().iterator(); - assertSame(keys[1], it.next()); - assertSame(keys[2], it.next()); - it = map.values().iterator(); - assertSame(values[1], it.next()); - assertSame(values[0], it.next()); + kit = map.keySet().iterator(); + assertSame(keys[1], kit.next()); + assertSame(keys[2], kit.next()); + vit = map.values().iterator(); + assertSame(values[1], vit.next()); + assertSame(values[0], vit.next()); map.put(keys[1], values[3]); assertEquals(2, map.size()); assertEquals(true, map.isFull()); assertEquals(2, map.maxSize()); - it = map.keySet().iterator(); - assertSame(keys[2], it.next()); - assertSame(keys[1], it.next()); - it = map.values().iterator(); - assertSame(values[0], it.next()); - assertSame(values[3], it.next()); + kit = map.keySet().iterator(); + assertSame(keys[2], kit.next()); + assertSame(keys[1], kit.next()); + vit = map.values().iterator(); + assertSame(values[0], vit.next()); + assertSame(values[3], vit.next()); } - - //----------------------------------------------------------------------- + + //----------------------------------------------------------------------- + @SuppressWarnings("unchecked") public void testReset() { resetEmpty(); - OrderedMap ordered = (OrderedMap) map; - ((ResettableIterator) ordered.mapIterator()).reset(); - + OrderedMap ordered = getMap(); + ((ResettableIterator) ordered.mapIterator()).reset(); + resetFull(); - ordered = (OrderedMap) map; - List list = new ArrayList(ordered.keySet()); - ResettableIterator it = (ResettableIterator) ordered.mapIterator(); + ordered = getMap(); + List list = new ArrayList(ordered.keySet()); + ResettableIterator it = (ResettableIterator) ordered.mapIterator(); assertSame(list.get(0), it.next()); assertSame(list.get(1), it.next()); it.reset(); assertSame(list.get(0), it.next()); } - + //----------------------------------------------------------------------- public void testAccessOrder() { if (isPutAddSupported() == false || isPutChangeSupported() == false) return; - Object[] keys = getSampleKeys(); - Object[] values = getSampleValues(); - Iterator it = null; - + K[] keys = getSampleKeys(); + V[] values = getSampleValues(); + Iterator kit = null; + Iterator vit = null; + resetEmpty(); map.put(keys[0], values[0]); map.put(keys[1], values[1]); - it = map.keySet().iterator(); - assertSame(keys[0], it.next()); - assertSame(keys[1], it.next()); - it = map.values().iterator(); - assertSame(values[0], it.next()); - assertSame(values[1], it.next()); + kit = map.keySet().iterator(); + assertSame(keys[0], kit.next()); + assertSame(keys[1], kit.next()); + vit = map.values().iterator(); + assertSame(values[0], vit.next()); + assertSame(values[1], vit.next()); // no change to order map.put(keys[1], values[1]); - it = map.keySet().iterator(); - assertSame(keys[0], it.next()); - assertSame(keys[1], it.next()); - it = map.values().iterator(); - assertSame(values[0], it.next()); - assertSame(values[1], it.next()); + kit = map.keySet().iterator(); + assertSame(keys[0], kit.next()); + assertSame(keys[1], kit.next()); + vit = map.values().iterator(); + assertSame(values[0], vit.next()); + assertSame(values[1], vit.next()); // no change to order map.put(keys[1], values[2]); - it = map.keySet().iterator(); - assertSame(keys[0], it.next()); - assertSame(keys[1], it.next()); - it = map.values().iterator(); - assertSame(values[0], it.next()); - assertSame(values[2], it.next()); + kit = map.keySet().iterator(); + assertSame(keys[0], kit.next()); + assertSame(keys[1], kit.next()); + vit = map.values().iterator(); + assertSame(values[0], vit.next()); + assertSame(values[2], vit.next()); // change to order map.put(keys[0], values[3]); - it = map.keySet().iterator(); - assertSame(keys[1], it.next()); - assertSame(keys[0], it.next()); - it = map.values().iterator(); - assertSame(values[2], it.next()); - assertSame(values[3], it.next()); + kit = map.keySet().iterator(); + assertSame(keys[1], kit.next()); + assertSame(keys[0], kit.next()); + vit = map.values().iterator(); + assertSame(values[2], vit.next()); + assertSame(values[3], vit.next()); // change to order map.get(keys[1]); - it = map.keySet().iterator(); - assertSame(keys[0], it.next()); - assertSame(keys[1], it.next()); - it = map.values().iterator(); - assertSame(values[3], it.next()); - assertSame(values[2], it.next()); + kit = map.keySet().iterator(); + assertSame(keys[0], kit.next()); + assertSame(keys[1], kit.next()); + vit = map.values().iterator(); + assertSame(values[3], vit.next()); + assertSame(values[2], vit.next()); // change to order map.get(keys[0]); - it = map.keySet().iterator(); - assertSame(keys[1], it.next()); - assertSame(keys[0], it.next()); - it = map.values().iterator(); - assertSame(values[2], it.next()); - assertSame(values[3], it.next()); + kit = map.keySet().iterator(); + assertSame(keys[1], kit.next()); + assertSame(keys[0], kit.next()); + vit = map.values().iterator(); + assertSame(values[2], vit.next()); + assertSame(values[3], vit.next()); // no change to order map.get(keys[0]); - it = map.keySet().iterator(); - assertSame(keys[1], it.next()); - assertSame(keys[0], it.next()); - it = map.values().iterator(); - assertSame(values[2], it.next()); - assertSame(values[3], it.next()); + kit = map.keySet().iterator(); + assertSame(keys[1], kit.next()); + assertSame(keys[0], kit.next()); + vit = map.values().iterator(); + assertSame(values[2], vit.next()); + assertSame(values[3], vit.next()); } - + + @SuppressWarnings("unchecked") public void testClone() { - LRUMap map = new LRUMap(10); - map.put("1", "1"); - Map cloned = (Map) map.clone(); + LRUMap map = new LRUMap(10); + map.put((K) "1", (V) "1"); + Map cloned = map.clone(); assertEquals(map.size(), cloned.size()); assertSame(map.get("1"), cloned.get("1")); } - + + @SuppressWarnings("unchecked") public void testRemoveLRU() { MockLRUMapSubclass map = new MockLRUMapSubclass(2); assertNull(map.entry); - map.put("A", "a"); + map.put((K) "A", "a"); assertNull(map.entry); - map.put("B", "b"); + map.put((K) "B", "b"); assertNull(map.entry); - map.put("C", "c"); // removes oldest, which is A=a + map.put((K) "C", "c"); // removes oldest, which is A=a assertNotNull(map.entry); assertEquals("A", map.key); assertEquals("a", map.value); @@ -238,32 +251,34 @@ public class TestLRUMap extends AbstractTestOrderedMap { assertEquals(true, map.containsKey("B")); assertEquals(true, map.containsKey("C")); } - - static class MockLRUMapSubclass extends LRUMap { - LinkEntry entry; - Object key; - Object value; + + @SuppressWarnings("serial") + static class MockLRUMapSubclass extends LRUMap { + LinkEntry entry; + K key; + V value; MockLRUMapSubclass(int size) { super(size); } - protected boolean removeLRU(LinkEntry entry) { + protected boolean removeLRU(LinkEntry entry) { this.entry = entry; this.key = entry.getKey(); this.value = entry.getValue(); return true; } } - + + @SuppressWarnings("unchecked") public void testRemoveLRUBlocksRemove() { - MockLRUMapSubclassBlocksRemove map = new MockLRUMapSubclassBlocksRemove(2, false); + MockLRUMapSubclassBlocksRemove map = new MockLRUMapSubclassBlocksRemove(2, false); assertEquals(0, map.size()); - map.put("A", "a"); + map.put((K) "A", (V) "a"); assertEquals(1, map.size()); - map.put("B", "b"); + map.put((K) "B", (V) "b"); assertEquals(2, map.size()); - map.put("C", "c"); // should remove oldest, which is A=a, but this is blocked + map.put((K) "C", (V) "c"); // should remove oldest, which is A=a, but this is blocked assertEquals(3, map.size()); assertEquals(2, map.maxSize()); assertEquals(true, map.containsKey("A")); @@ -271,39 +286,42 @@ public class TestLRUMap extends AbstractTestOrderedMap { assertEquals(true, map.containsKey("C")); } + @SuppressWarnings("unchecked") public void testRemoveLRUBlocksRemoveScan() { - MockLRUMapSubclassBlocksRemove map = new MockLRUMapSubclassBlocksRemove(2, true); + MockLRUMapSubclassBlocksRemove map = new MockLRUMapSubclassBlocksRemove(2, true); assertEquals(0, map.size()); - map.put("A", "a"); + map.put((K) "A", (V) "a"); assertEquals(1, map.size()); - map.put("B", "b"); + map.put((K) "B", (V) "b"); assertEquals(2, map.size()); - map.put("C", "c"); // should remove oldest, which is A=a, but this is blocked + map.put((K) "C", (V) "c"); // should remove oldest, which is A=a, but this is blocked assertEquals(3, map.size()); assertEquals(2, map.maxSize()); assertEquals(true, map.containsKey("A")); assertEquals(true, map.containsKey("B")); assertEquals(true, map.containsKey("C")); } - - static class MockLRUMapSubclassBlocksRemove extends LRUMap { + + @SuppressWarnings("serial") + static class MockLRUMapSubclassBlocksRemove extends LRUMap { MockLRUMapSubclassBlocksRemove(int size, boolean scanUntilRemove) { super(size, scanUntilRemove); } - protected boolean removeLRU(LinkEntry entry) { + protected boolean removeLRU(LinkEntry entry) { return false; } } - + + @SuppressWarnings("unchecked") public void testRemoveLRUFirstBlocksRemove() { - MockLRUMapSubclassFirstBlocksRemove map = new MockLRUMapSubclassFirstBlocksRemove(2); + MockLRUMapSubclassFirstBlocksRemove map = new MockLRUMapSubclassFirstBlocksRemove(2); assertEquals(0, map.size()); - map.put("A", "a"); + map.put((K) "A", (V) "a"); assertEquals(1, map.size()); - map.put("B", "b"); + map.put((K) "B", (V) "b"); assertEquals(2, map.size()); - map.put("C", "c"); // should remove oldest, which is A=a but this is blocked - so advance to B=b + map.put((K) "C", (V) "c"); // should remove oldest, which is A=a but this is blocked - so advance to B=b assertEquals(2, map.size()); assertEquals(2, map.maxSize()); assertEquals(true, map.containsKey("A")); @@ -311,12 +329,13 @@ public class TestLRUMap extends AbstractTestOrderedMap { assertEquals(true, map.containsKey("C")); } - static class MockLRUMapSubclassFirstBlocksRemove extends LRUMap { + @SuppressWarnings("serial") + static class MockLRUMapSubclassFirstBlocksRemove extends LRUMap { MockLRUMapSubclassFirstBlocksRemove(int size) { super(size, true); } - protected boolean removeLRU(LinkEntry entry) { + protected boolean removeLRU(LinkEntry entry) { if ("a".equals(entry.getValue())) { return false; } else { @@ -341,6 +360,7 @@ public class TestLRUMap extends AbstractTestOrderedMap { } } + @SuppressWarnings("unchecked") public void testInternalState_Buckets() { if (isPutAddSupported() == false || isPutChangeSupported() == false) return; SingleHashCode one = new SingleHashCode("1"); @@ -350,12 +370,12 @@ public class TestLRUMap extends AbstractTestOrderedMap { SingleHashCode five = new SingleHashCode("5"); SingleHashCode six = new SingleHashCode("6"); - LRUMap map = new LRUMap(3, 1.0f); + LRUMap map = new LRUMap(3, 1.0f); int hashIndex = map.hashIndex(map.hash(one), 4); - map.put(one, "A"); - map.put(two, "B"); - map.put(three, "C"); - + map.put((K) one, (V) "A"); + map.put((K) two, (V) "B"); + map.put((K) three, (V) "C"); + assertEquals(4, map.data.length); assertEquals(3, map.size); assertEquals(null, map.header.next); @@ -365,9 +385,9 @@ public class TestLRUMap extends AbstractTestOrderedMap { assertEquals(three, map.data[hashIndex].key); assertEquals(two, map.data[hashIndex].next.key); assertEquals(one, map.data[hashIndex].next.next.key); - - map.put(four, "D"); // reuses last in next list - + + map.put((K) four, (V) "D"); // reuses last in next list + assertEquals(4, map.data.length); assertEquals(3, map.size); assertEquals(null, map.header.next); @@ -377,9 +397,9 @@ public class TestLRUMap extends AbstractTestOrderedMap { assertEquals(four, map.data[hashIndex].key); assertEquals(three, map.data[hashIndex].next.key); assertEquals(two, map.data[hashIndex].next.next.key); - + map.get(three); - + assertEquals(4, map.data.length); assertEquals(3, map.size); assertEquals(null, map.header.next); @@ -389,9 +409,9 @@ public class TestLRUMap extends AbstractTestOrderedMap { assertEquals(four, map.data[hashIndex].key); assertEquals(three, map.data[hashIndex].next.key); assertEquals(two, map.data[hashIndex].next.next.key); - - map.put(five, "E"); // reuses last in next list - + + map.put((K) five, (V) "E"); // reuses last in next list + assertEquals(4, map.data.length); assertEquals(3, map.size); assertEquals(null, map.header.next); @@ -401,10 +421,10 @@ public class TestLRUMap extends AbstractTestOrderedMap { assertEquals(five, map.data[hashIndex].key); assertEquals(four, map.data[hashIndex].next.key); assertEquals(three, map.data[hashIndex].next.next.key); - + map.get(three); map.get(five); - + assertEquals(4, map.data.length); assertEquals(3, map.size); assertEquals(null, map.header.next); @@ -414,9 +434,9 @@ public class TestLRUMap extends AbstractTestOrderedMap { assertEquals(five, map.data[hashIndex].key); assertEquals(four, map.data[hashIndex].next.key); assertEquals(three, map.data[hashIndex].next.next.key); - - map.put(six, "F"); // reuses middle in next list - + + map.put((K) six, (V) "F"); // reuses middle in next list + assertEquals(4, map.data.length); assertEquals(3, map.size); assertEquals(null, map.header.next); @@ -428,21 +448,18 @@ public class TestLRUMap extends AbstractTestOrderedMap { assertEquals(three, map.data[hashIndex].next.next.key); } + @SuppressWarnings("unchecked") public void testInternalState_getEntry_int() { if (isPutAddSupported() == false || isPutChangeSupported() == false) return; SingleHashCode one = new SingleHashCode("1"); SingleHashCode two = new SingleHashCode("2"); SingleHashCode three = new SingleHashCode("3"); - SingleHashCode four = new SingleHashCode("4"); - SingleHashCode five = new SingleHashCode("5"); - SingleHashCode six = new SingleHashCode("6"); - LRUMap map = new LRUMap(3, 1.0f); - int hashIndex = map.hashIndex(map.hash(one), 4); - map.put(one, "A"); - map.put(two, "B"); - map.put(three, "C"); - + LRUMap map = new LRUMap(3, 1.0f); + map.put((K) one, (V) "A"); + map.put((K) two, (V) "B"); + map.put((K) three, (V) "C"); + assertEquals(one, map.getEntry(0).key); assertEquals(two, map.getEntry(1).key); assertEquals(three, map.getEntry(2).key); @@ -787,4 +804,12 @@ public class TestLRUMap extends AbstractTestOrderedMap { // resetFull(); // writeExternalFormToDisk((java.io.Serializable) map, "D:/dev/collections/data/test/LRUMap.fullCollection.version3.obj"); // } + + /** + * {@inheritDoc} + */ + @Override + public LRUMap getMap() { + return (LRUMap) super.getMap(); + } } diff --git a/src/test/org/apache/commons/collections/map/TestLinkedMap.java b/src/test/org/apache/commons/collections/map/TestLinkedMap.java index 4a7f6186e..a29861218 100644 --- a/src/test/org/apache/commons/collections/map/TestLinkedMap.java +++ b/src/test/org/apache/commons/collections/map/TestLinkedMap.java @@ -37,7 +37,7 @@ import org.apache.commons.collections.list.AbstractTestList; * * @author Stephen Colebourne */ -public class TestLinkedMap extends AbstractTestOrderedMap { +public class TestLinkedMap extends AbstractTestOrderedMap { public TestLinkedMap(String testName) { super(testName); @@ -46,127 +46,137 @@ public class TestLinkedMap extends AbstractTestOrderedMap { public static void main(String[] args) { TestRunner.run(suite()); } - + public static Test suite() { return BulkTest.makeSuite(TestLinkedMap.class); } - public Map makeEmptyMap() { - return new LinkedMap(); + public LinkedMap makeObject() { + return new LinkedMap(); + } + + /** + * {@inheritDoc} + */ + @Override + public LinkedMap makeFullMap() { + return (LinkedMap) super.makeFullMap(); } public String getCompatibilityVersion() { return "3"; } - //----------------------------------------------------------------------- + //----------------------------------------------------------------------- + @SuppressWarnings("unchecked") public void testReset() { resetEmpty(); - OrderedMap ordered = (OrderedMap) map; - ((ResettableIterator) ordered.mapIterator()).reset(); - + OrderedMap ordered = getMap(); + ((ResettableIterator) ordered.mapIterator()).reset(); + resetFull(); - ordered = (OrderedMap) map; - List list = new ArrayList(ordered.keySet()); - ResettableIterator it = (ResettableIterator) ordered.mapIterator(); + ordered = getMap(); + List list = new ArrayList(ordered.keySet()); + ResettableIterator it = (ResettableIterator) ordered.mapIterator(); assertSame(list.get(0), it.next()); assertSame(list.get(1), it.next()); it.reset(); assertSame(list.get(0), it.next()); } - + //----------------------------------------------------------------------- public void testInsertionOrder() { if (isPutAddSupported() == false || isPutChangeSupported() == false) return; - Object[] keys = getSampleKeys(); - Object[] values = getSampleValues(); - Iterator it = null; - + K[] keys = getSampleKeys(); + V[] values = getSampleValues(); + Iterator keyIter; + Iterator valueIter; + resetEmpty(); map.put(keys[0], values[0]); map.put(keys[1], values[1]); - it = map.keySet().iterator(); - assertSame(keys[0], it.next()); - assertSame(keys[1], it.next()); - it = map.values().iterator(); - assertSame(values[0], it.next()); - assertSame(values[1], it.next()); + keyIter = map.keySet().iterator(); + assertSame(keys[0], keyIter.next()); + assertSame(keys[1], keyIter.next()); + valueIter = map.values().iterator(); + assertSame(values[0], valueIter.next()); + assertSame(values[1], valueIter.next()); // no change to order map.put(keys[1], values[1]); - it = map.keySet().iterator(); - assertSame(keys[0], it.next()); - assertSame(keys[1], it.next()); - it = map.values().iterator(); - assertSame(values[0], it.next()); - assertSame(values[1], it.next()); + keyIter = map.keySet().iterator(); + assertSame(keys[0], keyIter.next()); + assertSame(keys[1], keyIter.next()); + valueIter = map.values().iterator(); + assertSame(values[0], valueIter.next()); + assertSame(values[1], valueIter.next()); // no change to order map.put(keys[1], values[2]); - it = map.keySet().iterator(); - assertSame(keys[0], it.next()); - assertSame(keys[1], it.next()); - it = map.values().iterator(); - assertSame(values[0], it.next()); - assertSame(values[2], it.next()); + keyIter = map.keySet().iterator(); + assertSame(keys[0], keyIter.next()); + assertSame(keys[1], keyIter.next()); + valueIter = map.values().iterator(); + assertSame(values[0], valueIter.next()); + assertSame(values[2], valueIter.next()); // no change to order map.put(keys[0], values[3]); - it = map.keySet().iterator(); - assertSame(keys[0], it.next()); - assertSame(keys[1], it.next()); - it = map.values().iterator(); - assertSame(values[3], it.next()); - assertSame(values[2], it.next()); + keyIter = map.keySet().iterator(); + assertSame(keys[0], keyIter.next()); + assertSame(keys[1], keyIter.next()); + valueIter = map.values().iterator(); + assertSame(values[3], valueIter.next()); + assertSame(values[2], valueIter.next()); } - + //----------------------------------------------------------------------- public void testGetByIndex() { resetEmpty(); - LinkedMap lm = (LinkedMap) map; + LinkedMap lm = getMap(); try { lm.get(0); } catch (IndexOutOfBoundsException ex) {} try { lm.get(-1); } catch (IndexOutOfBoundsException ex) {} - + resetFull(); - lm = (LinkedMap) map; + lm = getMap(); try { lm.get(-1); } catch (IndexOutOfBoundsException ex) {} try { lm.get(lm.size()); } catch (IndexOutOfBoundsException ex) {} - + int i = 0; - for (MapIterator it = lm.mapIterator(); it.hasNext(); i++) { + for (MapIterator it = lm.mapIterator(); it.hasNext(); i++) { assertSame(it.next(), lm.get(i)); } } public void testGetValueByIndex() { resetEmpty(); - LinkedMap lm = (LinkedMap) map; + LinkedMap lm = getMap(); try { lm.getValue(0); } catch (IndexOutOfBoundsException ex) {} try { lm.getValue(-1); } catch (IndexOutOfBoundsException ex) {} - + resetFull(); - lm = (LinkedMap) map; + lm = getMap(); try { lm.getValue(-1); } catch (IndexOutOfBoundsException ex) {} try { lm.getValue(lm.size()); } catch (IndexOutOfBoundsException ex) {} - + int i = 0; - for (MapIterator it = lm.mapIterator(); it.hasNext(); i++) { + for (MapIterator it = lm.mapIterator(); it.hasNext(); i++) { it.next(); assertSame(it.getValue(), lm.getValue(i)); } @@ -174,13 +184,13 @@ public class TestLinkedMap extends AbstractTestOrderedMap { public void testIndexOf() { resetEmpty(); - LinkedMap lm = (LinkedMap) map; + LinkedMap lm = getMap(); assertEquals(-1, lm.indexOf(getOtherKeys())); - + resetFull(); - lm = (LinkedMap) map; - List list = new ArrayList(); - for (MapIterator it = lm.mapIterator(); it.hasNext();) { + lm = getMap(); + List list = new ArrayList(); + for (MapIterator it = lm.mapIterator(); it.hasNext();) { list.add(it.next()); } for (int i = 0; i < list.size(); i++) { @@ -190,25 +200,25 @@ public class TestLinkedMap extends AbstractTestOrderedMap { public void testRemoveByIndex() { resetEmpty(); - LinkedMap lm = (LinkedMap) map; + LinkedMap lm = getMap(); try { lm.remove(0); } catch (IndexOutOfBoundsException ex) {} try { lm.remove(-1); } catch (IndexOutOfBoundsException ex) {} - + resetFull(); - lm = (LinkedMap) map; + lm = getMap(); try { lm.remove(-1); } catch (IndexOutOfBoundsException ex) {} try { lm.remove(lm.size()); } catch (IndexOutOfBoundsException ex) {} - - List list = new ArrayList(); - for (MapIterator it = lm.mapIterator(); it.hasNext();) { + + List list = new ArrayList(); + for (MapIterator it = lm.mapIterator(); it.hasNext();) { list.add(it.next()); } for (int i = 0; i < list.size(); i++) { @@ -219,26 +229,26 @@ public class TestLinkedMap extends AbstractTestOrderedMap { assertEquals(false, lm.containsKey(key)); } } - + public BulkTest bulkTestListView() { return new TestListView(); } - - public class TestListView extends AbstractTestList { - + + public class TestListView extends AbstractTestList { + TestListView() { super("TestListView"); } - public List makeEmptyList() { - return ((LinkedMap) TestLinkedMap.this.makeEmptyMap()).asList(); + public List makeObject() { + return TestLinkedMap.this.makeObject().asList(); } - - public List makeFullList() { - return ((LinkedMap) TestLinkedMap.this.makeFullMap()).asList(); + + public List makeFullCollection() { + return TestLinkedMap.this.makeFullMap().asList(); } - - public Object[] getFullElements() { + + public K[] getFullElements() { return TestLinkedMap.this.getSampleKeys(); } public boolean isAddSupported() { @@ -258,18 +268,27 @@ public class TestLinkedMap extends AbstractTestOrderedMap { } } + @SuppressWarnings("unchecked") public void testClone() { - LinkedMap map = new LinkedMap(10); - map.put("1", "1"); - Map cloned = (Map) map.clone(); + LinkedMap map = new LinkedMap(10); + map.put((K) "1", (V) "1"); + Map cloned = map.clone(); assertEquals(map.size(), cloned.size()); assertSame(map.get("1"), cloned.get("1")); } - + // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) map, "D:/dev/collections/data/test/LinkedMap.emptyCollection.version3.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) map, "D:/dev/collections/data/test/LinkedMap.fullCollection.version3.obj"); // } + + /** + * {@inheritDoc} + */ + @Override + public LinkedMap getMap() { + return (LinkedMap) super.getMap(); + } } diff --git a/src/test/org/apache/commons/collections/map/TestListOrderedMap.java b/src/test/org/apache/commons/collections/map/TestListOrderedMap.java index c68b1963e..6272dd502 100644 --- a/src/test/org/apache/commons/collections/map/TestListOrderedMap.java +++ b/src/test/org/apache/commons/collections/map/TestListOrderedMap.java @@ -37,7 +37,7 @@ import org.apache.commons.collections.list.AbstractTestList; * @author Stephen Colebourne * @author Matt Benson */ -public class TestListOrderedMap extends AbstractTestOrderedMap { +public class TestListOrderedMap extends AbstractTestOrderedMap { public TestListOrderedMap(String testName) { super(testName); @@ -52,57 +52,65 @@ public class TestListOrderedMap extends AbstractTestOrderedMap { junit.textui.TestRunner.main(testCaseName); } - public Map makeEmptyMap() { - return ListOrderedMap.decorate(new HashMap()); + public ListOrderedMap makeObject() { + return (ListOrderedMap) ListOrderedMap.decorate(new HashMap()); } - + + /** + * {@inheritDoc} + */ + @Override + public ListOrderedMap makeFullMap() { + return (ListOrderedMap) super.makeFullMap(); + } + //----------------------------------------------------------------------- public void testGetByIndex() { resetEmpty(); - ListOrderedMap lom = (ListOrderedMap) map; + ListOrderedMap lom = getMap(); try { lom.get(0); } catch (IndexOutOfBoundsException ex) {} try { lom.get(-1); } catch (IndexOutOfBoundsException ex) {} - + resetFull(); - lom = (ListOrderedMap) map; + lom = getMap(); try { lom.get(-1); } catch (IndexOutOfBoundsException ex) {} try { lom.get(lom.size()); } catch (IndexOutOfBoundsException ex) {} - + int i = 0; - for (MapIterator it = lom.mapIterator(); it.hasNext(); i++) { + for (MapIterator it = lom.mapIterator(); it.hasNext(); i++) { assertSame(it.next(), lom.get(i)); } } public void testGetValueByIndex() { resetEmpty(); - ListOrderedMap lom = (ListOrderedMap) map; + ListOrderedMap lom = getMap(); try { lom.getValue(0); } catch (IndexOutOfBoundsException ex) {} try { lom.getValue(-1); } catch (IndexOutOfBoundsException ex) {} - + resetFull(); - lom = (ListOrderedMap) map; + lom = getMap(); try { lom.getValue(-1); } catch (IndexOutOfBoundsException ex) {} try { lom.getValue(lom.size()); } catch (IndexOutOfBoundsException ex) {} - + int i = 0; - for (MapIterator it = lom.mapIterator(); it.hasNext(); i++) { + for (MapIterator it = lom.mapIterator(); it.hasNext(); i++) { it.next(); assertSame(it.getValue(), lom.getValue(i)); } @@ -110,13 +118,13 @@ public class TestListOrderedMap extends AbstractTestOrderedMap { public void testIndexOf() { resetEmpty(); - ListOrderedMap lom = (ListOrderedMap) map; + ListOrderedMap lom = getMap(); assertEquals(-1, lom.indexOf(getOtherKeys())); - + resetFull(); - lom = (ListOrderedMap) map; - List list = new ArrayList(); - for (MapIterator it = lom.mapIterator(); it.hasNext();) { + lom = getMap(); + List list = new ArrayList(); + for (MapIterator it = lom.mapIterator(); it.hasNext();) { list.add(it.next()); } for (int i = 0; i < list.size(); i++) { @@ -124,54 +132,55 @@ public class TestListOrderedMap extends AbstractTestOrderedMap { } } + @SuppressWarnings("unchecked") public void testSetValueByIndex() { resetEmpty(); - ListOrderedMap lom = (ListOrderedMap) map; + ListOrderedMap lom = getMap(); try { - lom.setValue(0, ""); + lom.setValue(0, (V) ""); } catch (IndexOutOfBoundsException ex) {} try { - lom.setValue(-1, ""); + lom.setValue(-1, (V) ""); } catch (IndexOutOfBoundsException ex) {} - + resetFull(); - lom = (ListOrderedMap) map; + lom = getMap(); try { - lom.setValue(-1, ""); + lom.setValue(-1, (V) ""); } catch (IndexOutOfBoundsException ex) {} try { - lom.setValue(lom.size(), ""); + lom.setValue(lom.size(), (V) ""); } catch (IndexOutOfBoundsException ex) {} - + for (int i = 0; i < lom.size(); i++) { - Object value = lom.getValue(i); + V value = lom.getValue(i); Object input = new Integer(i); - assertEquals(value, lom.setValue(i, input)); + assertEquals(value, lom.setValue(i, (V) input)); assertEquals(input, lom.getValue(i)); } } public void testRemoveByIndex() { resetEmpty(); - ListOrderedMap lom = (ListOrderedMap) map; + ListOrderedMap lom = getMap(); try { lom.remove(0); } catch (IndexOutOfBoundsException ex) {} try { lom.remove(-1); } catch (IndexOutOfBoundsException ex) {} - + resetFull(); - lom = (ListOrderedMap) map; + lom = getMap(); try { lom.remove(-1); } catch (IndexOutOfBoundsException ex) {} try { lom.remove(lom.size()); } catch (IndexOutOfBoundsException ex) {} - - List list = new ArrayList(); - for (MapIterator it = lom.mapIterator(); it.hasNext();) { + + List list = new ArrayList(); + for (MapIterator it = lom.mapIterator(); it.hasNext();) { list.add(it.next()); } for (int i = 0; i < list.size(); i++) { @@ -183,74 +192,75 @@ public class TestListOrderedMap extends AbstractTestOrderedMap { } } + @SuppressWarnings("unchecked") public void testPut_intObjectObject() { resetEmpty(); - ListOrderedMap lom = (ListOrderedMap) map; - + ListOrderedMap lom = getMap(); + try { - lom.put(1, "testInsert1", "testInsert1v"); + lom.put(1, (K) "testInsert1", (V) "testInsert1v"); fail("should not be able to insert at pos 1 in empty Map"); } catch (IndexOutOfBoundsException ex) {} try { - lom.put(-1, "testInsert-1", "testInsert-1v"); + lom.put(-1, (K) "testInsert-1", (V) "testInsert-1v"); fail("should not be able to insert at pos -1 in empty Map"); } catch (IndexOutOfBoundsException ex) {} - + // put where key doesn't exist - lom.put(0, "testInsert1", "testInsert1v"); + lom.put(0, (K) "testInsert1", (V) "testInsert1v"); assertEquals("testInsert1v", lom.getValue(0)); - - lom.put("testInsertPut", "testInsertPutv"); + + lom.put((K) "testInsertPut", (V) "testInsertPutv"); assertEquals("testInsert1v", lom.getValue(0)); assertEquals("testInsertPutv", lom.getValue(1)); - - lom.put(0, "testInsert0", "testInsert0v"); + + lom.put(0, (K) "testInsert0", (V) "testInsert0v"); assertEquals("testInsert0v", lom.getValue(0)); assertEquals("testInsert1v", lom.getValue(1)); assertEquals("testInsertPutv", lom.getValue(2)); - - lom.put(3, "testInsert3", "testInsert3v"); + + lom.put(3, (K) "testInsert3", (V) "testInsert3v"); assertEquals("testInsert0v", lom.getValue(0)); assertEquals("testInsert1v", lom.getValue(1)); assertEquals("testInsertPutv", lom.getValue(2)); assertEquals("testInsert3v", lom.getValue(3)); - - // put in a full map + + // put in a full map resetFull(); - lom = (ListOrderedMap) map; - ListOrderedMap lom2 = new ListOrderedMap(); + lom = getMap(); + ListOrderedMap lom2 = new ListOrderedMap(); lom2.putAll(lom); - - lom2.put(0, "testInsert0", "testInsert0v"); + + lom2.put(0, (K) "testInsert0", (V) "testInsert0v"); assertEquals("testInsert0v", lom2.getValue(0)); for (int i = 0; i < lom.size(); i++) { assertEquals(lom2.getValue(i + 1), lom.getValue(i)); } - + // put where key does exist Integer i1 = new Integer(1); Integer i1b = new Integer(1); Integer i2 = new Integer(2); Integer i3 = new Integer(3); - + resetEmpty(); - lom = (ListOrderedMap) map; - lom.put(i1, "1"); - lom.put(i2, "2"); - lom.put(i3, "3"); - lom.put(0, i1, "One"); + lom = getMap(); + lom.put((K) i1, (V) "1"); + lom.put((K) i2, (V) "2"); + lom.put((K) i3, (V) "3"); + lom.put(0, (K) i1, (V) "One"); assertEquals(3, lom.size()); assertEquals(3, lom.map.size()); assertEquals(3, lom.insertOrder.size()); assertEquals("One", lom.getValue(0)); assertSame(i1, lom.get(0)); - + resetEmpty(); - lom = (ListOrderedMap) map; - lom.put(i1, "1"); - lom.put(i2, "2"); - lom.put(i3, "3"); - lom.put(0, i1b, "One"); + lom = getMap(); + lom.put((K) i1, (V) "1"); + lom.put((K) i2, (V) "2"); + lom.put((K) i3, (V) "3"); + lom.put(0, (K) i1b, (V) "One"); assertEquals(3, lom.size()); assertEquals(3, lom.map.size()); assertEquals(3, lom.insertOrder.size()); @@ -258,39 +268,39 @@ public class TestListOrderedMap extends AbstractTestOrderedMap { assertEquals("2", lom.getValue(1)); assertEquals("3", lom.getValue(2)); assertSame(i1b, lom.get(0)); - + resetEmpty(); - lom = (ListOrderedMap) map; - lom.put(i1, "1"); - lom.put(i2, "2"); - lom.put(i3, "3"); - lom.put(1, i1b, "One"); + lom = getMap(); + lom.put((K) i1, (V) "1"); + lom.put((K) i2, (V) "2"); + lom.put((K) i3, (V) "3"); + lom.put(1, (K) i1b, (V) "One"); assertEquals(3, lom.size()); assertEquals(3, lom.map.size()); assertEquals(3, lom.insertOrder.size()); assertEquals("One", lom.getValue(0)); assertEquals("2", lom.getValue(1)); assertEquals("3", lom.getValue(2)); - + resetEmpty(); - lom = (ListOrderedMap) map; - lom.put(i1, "1"); - lom.put(i2, "2"); - lom.put(i3, "3"); - lom.put(2, i1b, "One"); + lom = getMap(); + lom.put((K) i1, (V) "1"); + lom.put((K) i2, (V) "2"); + lom.put((K) i3, (V) "3"); + lom.put(2, (K) i1b, (V) "One"); assertEquals(3, lom.size()); assertEquals(3, lom.map.size()); assertEquals(3, lom.insertOrder.size()); assertEquals("2", lom.getValue(0)); assertEquals("One", lom.getValue(1)); assertEquals("3", lom.getValue(2)); - + resetEmpty(); - lom = (ListOrderedMap) map; - lom.put(i1, "1"); - lom.put(i2, "2"); - lom.put(i3, "3"); - lom.put(3, i1b, "One"); + lom = getMap(); + lom.put((K) i1, (V) "1"); + lom.put((K) i2, (V) "2"); + lom.put((K) i3, (V) "3"); + lom.put(3, (K) i1b, (V) "One"); assertEquals(3, lom.size()); assertEquals(3, lom.map.size()); assertEquals(3, lom.insertOrder.size()); @@ -328,20 +338,21 @@ public class TestListOrderedMap extends AbstractTestOrderedMap { //----------------------------------------------------------------------- public void testValueList_getByIndex() { resetFull(); - ListOrderedMap lom = (ListOrderedMap) map; + ListOrderedMap lom = getMap(); for (int i = 0; i < lom.size(); i++) { - Object expected = lom.getValue(i); + V expected = lom.getValue(i); assertEquals(expected, lom.valueList().get(i)); } } + @SuppressWarnings("unchecked") public void testValueList_setByIndex() { resetFull(); - ListOrderedMap lom = (ListOrderedMap) map; + ListOrderedMap lom = getMap(); for (int i = 0; i < lom.size(); i++) { Object input = new Integer(i); - Object expected = lom.getValue(i); - assertEquals(expected, lom.valueList().set(i, input)); + V expected = lom.getValue(i); + assertEquals(expected, lom.valueList().set(i, (V) input)); assertEquals(input, lom.getValue(i)); assertEquals(input, lom.valueList().get(i)); } @@ -349,9 +360,9 @@ public class TestListOrderedMap extends AbstractTestOrderedMap { public void testValueList_removeByIndex() { resetFull(); - ListOrderedMap lom = (ListOrderedMap) map; + ListOrderedMap lom = getMap(); while (lom.size() > 1) { - Object expected = lom.getValue(1); + V expected = lom.getValue(1); assertEquals(expected, lom.valueList().remove(1)); } } @@ -366,19 +377,19 @@ public class TestListOrderedMap extends AbstractTestOrderedMap { } //----------------------------------------------------------------------- - public class TestKeyListView extends AbstractTestList { + public class TestKeyListView extends AbstractTestList { TestKeyListView() { super("TestKeyListView"); } - public List makeEmptyList() { - return ((ListOrderedMap) TestListOrderedMap.this.makeEmptyMap()).keyList(); + public List makeObject() { + return TestListOrderedMap.this.makeObject().keyList(); } - public List makeFullList() { - return ((ListOrderedMap) TestListOrderedMap.this.makeFullMap()).keyList(); + public List makeFullCollection() { + return TestListOrderedMap.this.makeFullMap().keyList(); } - public Object[] getFullElements() { + public K[] getFullElements() { return TestListOrderedMap.this.getSampleKeys(); } public boolean isAddSupported() { @@ -399,19 +410,19 @@ public class TestListOrderedMap extends AbstractTestOrderedMap { } //----------------------------------------------------------------------- - public class TestValueListView extends AbstractTestList { + public class TestValueListView extends AbstractTestList { TestValueListView() { super("TestValueListView"); } - public List makeEmptyList() { - return ((ListOrderedMap) TestListOrderedMap.this.makeEmptyMap()).valueList(); + public List makeObject() { + return TestListOrderedMap.this.makeObject().valueList(); } - public List makeFullList() { - return ((ListOrderedMap) TestListOrderedMap.this.makeFullMap()).valueList(); + public List makeFullCollection() { + return TestListOrderedMap.this.makeFullMap().valueList(); } - public Object[] getFullElements() { + public V[] getFullElements() { return TestListOrderedMap.this.getSampleValues(); } public boolean isAddSupported() { @@ -446,4 +457,12 @@ public class TestListOrderedMap extends AbstractTestOrderedMap { // (java.io.Serializable) map, // "D:/dev/collections/data/test/ListOrderedMap.fullCollection.version3.1.obj"); // } + + /** + * {@inheritDoc} + */ + @Override + public ListOrderedMap getMap() { + return (ListOrderedMap) super.getMap(); + } } diff --git a/src/test/org/apache/commons/collections/map/TestListOrderedMap2.java b/src/test/org/apache/commons/collections/map/TestListOrderedMap2.java index 887cd37a7..8af2efe7b 100644 --- a/src/test/org/apache/commons/collections/map/TestListOrderedMap2.java +++ b/src/test/org/apache/commons/collections/map/TestListOrderedMap2.java @@ -18,7 +18,6 @@ package org.apache.commons.collections.map; import java.util.ArrayList; import java.util.List; -import java.util.Map; import junit.framework.Test; @@ -35,7 +34,7 @@ import org.apache.commons.collections.list.AbstractTestList; * * @author Stephen Colebourne */ -public class TestListOrderedMap2 extends AbstractTestOrderedMap { +public class TestListOrderedMap2 extends AbstractTestOrderedMap { public TestListOrderedMap2(String testName) { super(testName); @@ -50,57 +49,65 @@ public class TestListOrderedMap2 extends AbstractTestOrderedMap { junit.textui.TestRunner.main(testCaseName); } - public Map makeEmptyMap() { - return new ListOrderedMap(); + public ListOrderedMap makeObject() { + return new ListOrderedMap(); } - + + /** + * {@inheritDoc} + */ + @Override + public ListOrderedMap makeFullMap() { + return (ListOrderedMap) super.makeFullMap(); + } + //----------------------------------------------------------------------- public void testGetByIndex() { resetEmpty(); - ListOrderedMap lom = (ListOrderedMap) map; + ListOrderedMap lom = getMap(); try { lom.get(0); } catch (IndexOutOfBoundsException ex) {} try { lom.get(-1); } catch (IndexOutOfBoundsException ex) {} - + resetFull(); - lom = (ListOrderedMap) map; + lom = getMap(); try { lom.get(-1); } catch (IndexOutOfBoundsException ex) {} try { lom.get(lom.size()); } catch (IndexOutOfBoundsException ex) {} - + int i = 0; - for (MapIterator it = lom.mapIterator(); it.hasNext(); i++) { + for (MapIterator it = lom.mapIterator(); it.hasNext(); i++) { assertSame(it.next(), lom.get(i)); } } public void testGetValueByIndex() { resetEmpty(); - ListOrderedMap lom = (ListOrderedMap) map; + ListOrderedMap lom = getMap(); try { lom.getValue(0); } catch (IndexOutOfBoundsException ex) {} try { lom.getValue(-1); } catch (IndexOutOfBoundsException ex) {} - + resetFull(); - lom = (ListOrderedMap) map; + lom = getMap(); try { lom.getValue(-1); } catch (IndexOutOfBoundsException ex) {} try { lom.getValue(lom.size()); } catch (IndexOutOfBoundsException ex) {} - + int i = 0; - for (MapIterator it = lom.mapIterator(); it.hasNext(); i++) { + for (MapIterator it = lom.mapIterator(); it.hasNext(); i++) { it.next(); assertSame(it.getValue(), lom.getValue(i)); } @@ -108,13 +115,13 @@ public class TestListOrderedMap2 extends AbstractTestOrderedMap { public void testIndexOf() { resetEmpty(); - ListOrderedMap lom = (ListOrderedMap) map; + ListOrderedMap lom = getMap(); assertEquals(-1, lom.indexOf(getOtherKeys())); - + resetFull(); - lom = (ListOrderedMap) map; - List list = new ArrayList(); - for (MapIterator it = lom.mapIterator(); it.hasNext();) { + lom = getMap(); + List list = new ArrayList(); + for (MapIterator it = lom.mapIterator(); it.hasNext();) { list.add(it.next()); } for (int i = 0; i < list.size(); i++) { @@ -124,25 +131,25 @@ public class TestListOrderedMap2 extends AbstractTestOrderedMap { public void testRemoveByIndex() { resetEmpty(); - ListOrderedMap lom = (ListOrderedMap) map; + ListOrderedMap lom = getMap(); try { lom.remove(0); } catch (IndexOutOfBoundsException ex) {} try { lom.remove(-1); } catch (IndexOutOfBoundsException ex) {} - + resetFull(); - lom = (ListOrderedMap) map; + lom = getMap(); try { lom.remove(-1); } catch (IndexOutOfBoundsException ex) {} try { lom.remove(lom.size()); } catch (IndexOutOfBoundsException ex) {} - - List list = new ArrayList(); - for (MapIterator it = lom.mapIterator(); it.hasNext();) { + + List list = new ArrayList(); + for (MapIterator it = lom.mapIterator(); it.hasNext();) { list.add(it.next()); } for (int i = 0; i < list.size(); i++) { @@ -153,26 +160,26 @@ public class TestListOrderedMap2 extends AbstractTestOrderedMap { assertEquals(false, lom.containsKey(key)); } } - + public BulkTest bulkTestListView() { return new TestListView(); } - - public class TestListView extends AbstractTestList { - + + public class TestListView extends AbstractTestList { + TestListView() { super("TestListView"); } - public List makeEmptyList() { - return ((ListOrderedMap) TestListOrderedMap2.this.makeEmptyMap()).asList(); + public List makeObject() { + return TestListOrderedMap2.this.makeObject().asList(); } - - public List makeFullList() { - return ((ListOrderedMap) TestListOrderedMap2.this.makeFullMap()).asList(); + + public List makeFullCollection() { + return TestListOrderedMap2.this.makeFullMap().asList(); } - - public Object[] getFullElements() { + + public K[] getFullElements() { return TestListOrderedMap2.this.getSampleKeys(); } public boolean isAddSupported() { @@ -206,4 +213,13 @@ public class TestListOrderedMap2 extends AbstractTestOrderedMap { // (java.io.Serializable) map, // "D:/dev/collections/data/test/ListOrderedMap.fullCollection.version3.1.obj"); // } + + /** + * {@inheritDoc} + */ + @Override + public ListOrderedMap getMap() { + // TODO Auto-generated method stub + return (ListOrderedMap) super.getMap(); + } } diff --git a/src/test/org/apache/commons/collections/map/TestMultiKeyMap.java b/src/test/org/apache/commons/collections/map/TestMultiKeyMap.java index 6737100ec..b86db2cc3 100644 --- a/src/test/org/apache/commons/collections/map/TestMultiKeyMap.java +++ b/src/test/org/apache/commons/collections/map/TestMultiKeyMap.java @@ -32,8 +32,8 @@ import org.apache.commons.collections.keyvalue.MultiKey; * * @author Stephen Colebourne */ -public class TestMultiKeyMap extends AbstractTestIterableMap { - +public class TestMultiKeyMap extends AbstractTestIterableMap, V> { + static final Integer I1 = new Integer(1); static final Integer I2 = new Integer(2); static final Integer I3 = new Integer(3); @@ -55,15 +55,16 @@ public class TestMultiKeyMap extends AbstractTestIterableMap { return BulkTest.makeSuite(TestMultiKeyMap.class); } - public Map makeEmptyMap() { - return new MultiKeyMap(); + public MultiKeyMap makeObject() { + return new MultiKeyMap(); } - public Object[] getSampleKeys() { + public MultiKey[] getSampleKeys() { return getMultiKeyKeys(); } - private MultiKey[] getMultiKeyKeys() { + @SuppressWarnings("unchecked") + private MultiKey[] getMultiKeyKeys() { return new MultiKey[] { new MultiKey(I1, I2), new MultiKey(I2, I3), @@ -80,8 +81,9 @@ public class TestMultiKeyMap extends AbstractTestIterableMap { }; } - public Object[] getSampleValues() { - return new Object[] { + @SuppressWarnings("unchecked") + public V[] getSampleValues() { + return (V[]) new Object[] { "2A", "2B", "2C", "3D", "3E", "3F", "4G", "4H", "4I", @@ -89,8 +91,9 @@ public class TestMultiKeyMap extends AbstractTestIterableMap { }; } - public Object[] getNewSampleValues() { - return new Object[] { + @SuppressWarnings("unchecked") + public V[] getNewSampleValues() { + return (V[]) new Object[] { "1a", "1b", "1c", "2d", "2e", "2f", "3g", "3h", "3i", @@ -98,20 +101,22 @@ public class TestMultiKeyMap extends AbstractTestIterableMap { }; } - public Object[] getOtherKeys() { - return new Object[] { + @SuppressWarnings("unchecked") + public MultiKey[] getOtherKeys() { + return (MultiKey[]) new MultiKey[] { new MultiKey(I1, I7), new MultiKey(I1, I8), new MultiKey(I2, I4), new MultiKey(I2, I5), }; } - + public boolean isAllowNullKey() { return false; } //----------------------------------------------------------------------- + @SuppressWarnings("unchecked") public void testNullHandling() { resetFull(); assertEquals(null, map.get(null)); @@ -125,9 +130,9 @@ public class TestMultiKeyMap extends AbstractTestIterableMap { map.put(null, null); fail(); } catch (NullPointerException ex) {} - assertEquals(null, map.put(new MultiKey(null, null), null)); + assertEquals(null, map.put(new MultiKey(null, null), null)); try { - map.put(null, new Object()); + map.put(null, (V) new Object()); fail(); } catch (NullPointerException ex) {} } @@ -135,14 +140,14 @@ public class TestMultiKeyMap extends AbstractTestIterableMap { //----------------------------------------------------------------------- public void testMultiKeyGet() { resetFull(); - MultiKeyMap multimap = (MultiKeyMap) map; - MultiKey[] keys = getMultiKeyKeys(); - Object[] values = getSampleValues(); - + MultiKeyMap multimap = getMap(); + MultiKey[] keys = getMultiKeyKeys(); + V[] values = getSampleValues(); + for (int i = 0; i < keys.length; i++) { - MultiKey key = keys[i]; - Object value = values[i]; - + MultiKey key = keys[i]; + V value = values[i]; + switch (key.size()) { case 2: assertEquals(value, multimap.get(key.getKey(0), key.getKey(1))); @@ -185,17 +190,15 @@ public class TestMultiKeyMap extends AbstractTestIterableMap { } } } - + public void testMultiKeyContainsKey() { resetFull(); - MultiKeyMap multimap = (MultiKeyMap) map; - MultiKey[] keys = getMultiKeyKeys(); - Object[] values = getSampleValues(); - + MultiKeyMap multimap = getMap(); + MultiKey[] keys = getMultiKeyKeys(); + for (int i = 0; i < keys.length; i++) { - MultiKey key = keys[i]; - Object value = values[i]; - + MultiKey key = keys[i]; + switch (key.size()) { case 2: assertEquals(true, multimap.containsKey(key.getKey(0), key.getKey(1))); @@ -238,24 +241,24 @@ public class TestMultiKeyMap extends AbstractTestIterableMap { } } } - + public void testMultiKeyPut() { - MultiKey[] keys = getMultiKeyKeys(); - Object[] values = getSampleValues(); - + MultiKey[] keys = getMultiKeyKeys(); + V[] values = getSampleValues(); + for (int i = 0; i < keys.length; i++) { - MultiKeyMap multimap = new MultiKeyMap(); - - MultiKey key = keys[i]; - Object value = values[i]; - + MultiKeyMap multimap = new MultiKeyMap(); + + MultiKey key = keys[i]; + V value = values[i]; + switch (key.size()) { case 2: assertEquals(null, multimap.put(key.getKey(0), key.getKey(1), value)); assertEquals(1, multimap.size()); assertEquals(value, multimap.get(key.getKey(0), key.getKey(1))); assertEquals(true, multimap.containsKey(key.getKey(0), key.getKey(1))); - assertEquals(true, multimap.containsKey(new MultiKey(key.getKey(0), key.getKey(1)))); + assertEquals(true, multimap.containsKey(new MultiKey(key.getKey(0), key.getKey(1)))); assertEquals(value, multimap.put(key.getKey(0), key.getKey(1), null)); assertEquals(1, multimap.size()); assertEquals(null, multimap.get(key.getKey(0), key.getKey(1))); @@ -266,7 +269,7 @@ public class TestMultiKeyMap extends AbstractTestIterableMap { assertEquals(1, multimap.size()); assertEquals(value, multimap.get(key.getKey(0), key.getKey(1), key.getKey(2))); assertEquals(true, multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2))); - assertEquals(true, multimap.containsKey(new MultiKey(key.getKey(0), key.getKey(1), key.getKey(2)))); + assertEquals(true, multimap.containsKey(new MultiKey(key.getKey(0), key.getKey(1), key.getKey(2)))); assertEquals(value, multimap.put(key.getKey(0), key.getKey(1), key.getKey(2), null)); assertEquals(1, multimap.size()); assertEquals(null, multimap.get(key.getKey(0), key.getKey(1), key.getKey(2))); @@ -277,7 +280,7 @@ public class TestMultiKeyMap extends AbstractTestIterableMap { assertEquals(1, multimap.size()); assertEquals(value, multimap.get(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3))); assertEquals(true, multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3))); - assertEquals(true, multimap.containsKey(new MultiKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3)))); + assertEquals(true, multimap.containsKey(new MultiKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3)))); assertEquals(value, multimap.put(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), null)); assertEquals(1, multimap.size()); assertEquals(null, multimap.get(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3))); @@ -288,7 +291,7 @@ public class TestMultiKeyMap extends AbstractTestIterableMap { assertEquals(1, multimap.size()); assertEquals(value, multimap.get(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), key.getKey(4))); assertEquals(true, multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), key.getKey(4))); - assertEquals(true, multimap.containsKey(new MultiKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), key.getKey(4)))); + assertEquals(true, multimap.containsKey(new MultiKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), key.getKey(4)))); assertEquals(value, multimap.put(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), key.getKey(4), null)); assertEquals(1, multimap.size()); assertEquals(null, multimap.get(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), key.getKey(4))); @@ -299,19 +302,19 @@ public class TestMultiKeyMap extends AbstractTestIterableMap { } } } - + public void testMultiKeyRemove() { - MultiKey[] keys = getMultiKeyKeys(); - Object[] values = getSampleValues(); - + MultiKey[] keys = getMultiKeyKeys(); + V[] values = getSampleValues(); + for (int i = 0; i < keys.length; i++) { resetFull(); - MultiKeyMap multimap = (MultiKeyMap) map; + MultiKeyMap multimap = getMap(); int size = multimap.size(); - - MultiKey key = keys[i]; - Object value = values[i]; - + + MultiKey key = keys[i]; + V value = values[i]; + switch (key.size()) { case 2: assertEquals(true, multimap.containsKey(key.getKey(0), key.getKey(1))); @@ -350,86 +353,88 @@ public class TestMultiKeyMap extends AbstractTestIterableMap { } } } - + public void testMultiKeyRemoveAll1() { resetFull(); - MultiKeyMap multimap = (MultiKeyMap) map; + MultiKeyMap multimap = getMap(); assertEquals(12, multimap.size()); - + multimap.removeAll(I1); assertEquals(8, multimap.size()); - for (MapIterator it = multimap.mapIterator(); it.hasNext();) { - MultiKey key = (MultiKey) it.next(); + for (MapIterator, V> it = multimap.mapIterator(); it.hasNext();) { + MultiKey key = it.next(); assertEquals(false, I1.equals(key.getKey(0))); } } - + public void testMultiKeyRemoveAll2() { resetFull(); - MultiKeyMap multimap = (MultiKeyMap) map; + MultiKeyMap multimap = getMap(); assertEquals(12, multimap.size()); - + multimap.removeAll(I2, I3); assertEquals(9, multimap.size()); - for (MapIterator it = multimap.mapIterator(); it.hasNext();) { - MultiKey key = (MultiKey) it.next(); + for (MapIterator, V> it = multimap.mapIterator(); it.hasNext();) { + MultiKey key = it.next(); assertEquals(false, I2.equals(key.getKey(0)) && I3.equals(key.getKey(1))); } } - + public void testMultiKeyRemoveAll3() { resetFull(); - MultiKeyMap multimap = (MultiKeyMap) map; + MultiKeyMap multimap = getMap(); assertEquals(12, multimap.size()); - + multimap.removeAll(I1, I1, I2); assertEquals(9, multimap.size()); - for (MapIterator it = multimap.mapIterator(); it.hasNext();) { - MultiKey key = (MultiKey) it.next(); + for (MapIterator, V> it = multimap.mapIterator(); it.hasNext();) { + MultiKey key = it.next(); assertEquals(false, I1.equals(key.getKey(0)) && I1.equals(key.getKey(1)) && I2.equals(key.getKey(2))); } } - + public void testMultiKeyRemoveAll4() { resetFull(); - MultiKeyMap multimap = (MultiKeyMap) map; + MultiKeyMap multimap = getMap(); assertEquals(12, multimap.size()); - + multimap.removeAll(I1, I1, I2, I3); assertEquals(10, multimap.size()); - for (MapIterator it = multimap.mapIterator(); it.hasNext();) { - MultiKey key = (MultiKey) it.next(); + for (MapIterator, V> it = multimap.mapIterator(); it.hasNext();) { + MultiKey key = it.next(); assertEquals(false, I1.equals(key.getKey(0)) && I1.equals(key.getKey(1)) && I2.equals(key.getKey(2)) && key.size() >= 4 && I3.equals(key.getKey(3))); } } - + //----------------------------------------------------------------------- + @SuppressWarnings("unchecked") public void testClone() { - MultiKeyMap map = new MultiKeyMap(); - map.put(new MultiKey(I1, I2), "1-2"); - Map cloned = (Map) map.clone(); + MultiKeyMap map = new MultiKeyMap(); + map.put(new MultiKey((K) I1, (K) I2), (V) "1-2"); + Map, V> cloned = map.clone(); assertEquals(map.size(), cloned.size()); - assertSame(map.get(new MultiKey(I1, I2)), cloned.get(new MultiKey(I1, I2))); + assertSame(map.get(new MultiKey((K) I1, (K) I2)), cloned.get(new MultiKey((K) I1, (K) I2))); } //----------------------------------------------------------------------- + @SuppressWarnings("unchecked") public void testLRUMultiKeyMap() { - MultiKeyMap map = MultiKeyMap.decorate(new LRUMap(2)); - map.put(I1, I2, "1-2"); - map.put(I1, I3, "1-3"); + MultiKeyMap map = MultiKeyMap.decorate(new LRUMap, V>(2)); + map.put((K) I1, (K) I2, (V) "1-2"); + map.put((K) I1, (K) I3, (V) "1-1"); assertEquals(2, map.size()); - map.put(I1, I4, "1-4"); + map.put((K) I1, (K) I4, (V) "1-4"); assertEquals(2, map.size()); assertEquals(true, map.containsKey(I1, I3)); assertEquals(true, map.containsKey(I1, I4)); assertEquals(false, map.containsKey(I1, I2)); - - MultiKeyMap cloned = (MultiKeyMap) map.clone(); + + MultiKeyMap cloned = map.clone(); assertEquals(2, map.size()); assertEquals(true, cloned.containsKey(I1, I3)); assertEquals(true, cloned.containsKey(I1, I4)); assertEquals(false, cloned.containsKey(I1, I2)); - cloned.put(I1, I5, "1-5"); + cloned.put((K) I1, (K) I5, (V) "1-5"); assertEquals(2, cloned.size()); assertEquals(true, cloned.containsKey(I1, I4)); assertEquals(true, cloned.containsKey(I1, I5)); @@ -450,4 +455,12 @@ public class TestMultiKeyMap extends AbstractTestIterableMap { // (java.io.Serializable) map, // "D:/dev/collections/data/test/MultiKeyMap.fullCollection.version3.1.obj"); // } + + /** + * {@inheritDoc} + */ + @Override + public MultiKeyMap getMap() { + return (MultiKeyMap) super.getMap(); + } } diff --git a/src/test/org/apache/commons/collections/map/TestPredicatedSortedMap.java b/src/test/org/apache/commons/collections/map/TestPredicatedSortedMap.java index f0ec4a143..17e85b1a9 100644 --- a/src/test/org/apache/commons/collections/map/TestPredicatedSortedMap.java +++ b/src/test/org/apache/commons/collections/map/TestPredicatedSortedMap.java @@ -27,10 +27,10 @@ import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.collections.Predicate; -import org.apache.commons.collections.PredicateUtils; +import org.apache.commons.collections.functors.TruePredicate; /** - * Extension of {@link TestPredicatedMap} for exercising the + * Extension of {@link TestPredicatedMap} for exercising the * {@link PredicatedSortedMap} implementation. * * @since Commons Collections 3.0 @@ -38,46 +38,43 @@ import org.apache.commons.collections.PredicateUtils; * * @author Phil Steitz */ -public class TestPredicatedSortedMap extends AbstractTestSortedMap{ - - protected static final Predicate truePredicate = PredicateUtils.truePredicate(); - protected static final Predicate testPredicate = new Predicate() { +public class TestPredicatedSortedMap extends AbstractTestSortedMap { + + protected static final Predicate truePredicate = TruePredicate.truePredicate(); + + protected static final Predicate testPredicate = new Predicate() { public boolean evaluate(Object o) { return (o instanceof String); } }; - + public TestPredicatedSortedMap(String testName) { super(testName); } - + public static Test suite() { return new TestSuite(TestPredicatedSortedMap.class); } - + public static void main(String args[]) { String[] testCaseName = { TestPredicatedSortedMap.class.getName()}; junit.textui.TestRunner.main(testCaseName); } //----------------------------------------------------------------------- - protected SortedMap decorateMap(SortedMap map, Predicate keyPredicate, - Predicate valuePredicate) { + protected SortedMap decorateMap(SortedMap map, Predicate keyPredicate, + Predicate valuePredicate) { return PredicatedSortedMap.decorate(map, keyPredicate, valuePredicate); } - - public Map makeEmptyMap() { - return decorateMap(new TreeMap(), truePredicate, truePredicate); + + public SortedMap makeObject() { + return decorateMap(new TreeMap(), truePredicate, truePredicate); } - - public Map makeTestMap() { - return decorateMap(new TreeMap(), testPredicate, testPredicate); - } - - public SortedMap makeTestSortedMap() { - return decorateMap(new TreeMap(), testPredicate, testPredicate); + + public SortedMap makeTestMap() { + return decorateMap(new TreeMap(), testPredicate, testPredicate); } - + public boolean isSubMapViewsSerializable() { // TreeMap sub map views have a bug in deserialization. return false; @@ -89,28 +86,30 @@ public class TestPredicatedSortedMap extends AbstractTestSortedMap{ // from TestPredicatedMap //----------------------------------------------------------------------- + @SuppressWarnings("unchecked") public void testEntrySet() { - SortedMap map = makeTestSortedMap(); + SortedMap map = makeTestMap(); assertTrue("returned entryset should not be null", map.entrySet() != null); - map = decorateMap(new TreeMap(), null, null); - map.put("oneKey", "oneValue"); + map = decorateMap(new TreeMap(), null, null); + map.put((K) "oneKey", (V) "oneValue"); assertTrue("returned entryset should contain one entry", - map.entrySet().size() == 1); + map.entrySet().size() == 1); map = decorateMap(map, null, null); } - + + @SuppressWarnings("unchecked") public void testPut() { - Map map = makeTestMap(); + Map map = makeTestMap(); try { - map.put("Hi", new Integer(3)); + map.put((K) "Hi", (V) new Integer(3)); fail("Illegal value should raise IllegalArgument"); } catch (IllegalArgumentException e) { // expected } try { - map.put(new Integer(3), "Hi"); + map.put((K) new Integer(3), (V) "Hi"); fail("Illegal key should raise IllegalArgument"); } catch (IllegalArgumentException e) { // expected @@ -119,11 +118,11 @@ public class TestPredicatedSortedMap extends AbstractTestSortedMap{ assertTrue(!map.containsKey(new Integer(3))); assertTrue(!map.containsValue(new Integer(3))); - Map map2 = new HashMap(); - map2.put("A", "a"); - map2.put("B", "b"); - map2.put("C", "c"); - map2.put("c", new Integer(3)); + Map map2 = new HashMap(); + map2.put((K) "A", (V) "a"); + map2.put((K) "B", (V) "b"); + map2.put((K) "C", (V) "c"); + map2.put((K) "c", (V) new Integer(3)); try { map.putAll(map2); @@ -132,52 +131,53 @@ public class TestPredicatedSortedMap extends AbstractTestSortedMap{ // expected } - map.put("E", "e"); - Iterator iterator = map.entrySet().iterator(); + map.put((K) "E", (V) "e"); + Iterator> iterator = map.entrySet().iterator(); try { - Map.Entry entry = (Map.Entry)iterator.next(); - entry.setValue(new Integer(3)); + Map.Entry entry = iterator.next(); + entry.setValue((V) new Integer(3)); fail("Illegal value should raise IllegalArgument"); } catch (IllegalArgumentException e) { // expected } - - map.put("F", "f"); + + map.put((K) "F", (V) "f"); iterator = map.entrySet().iterator(); - Map.Entry entry = (Map.Entry)iterator.next(); - entry.setValue("x"); - + Map.Entry entry = iterator.next(); + entry.setValue((V) "x"); + } //----------------------------------------------------------------------- + @SuppressWarnings("unchecked") public void testSortOrder() { - SortedMap map = makeTestSortedMap(); - map.put("A", "a"); - map.put("B", "b"); + SortedMap map = makeTestMap(); + map.put((K) "A", (V) "a"); + map.put((K) "B", (V) "b"); try { - map.put(null, "c"); + map.put(null, (V) "c"); fail("Null key should raise IllegalArgument"); } catch (IllegalArgumentException e) { // expected } - map.put("C", "c"); + map.put((K) "C", (V) "c"); try { - map.put("D", null); + map.put((K) "D", null); fail("Null value should raise IllegalArgument"); } catch (IllegalArgumentException e) { // expected } assertEquals("First key should be A", "A", map.firstKey()); assertEquals("Last key should be C", "C", map.lastKey()); - assertEquals("First key in tail map should be B", - "B", map.tailMap("B").firstKey()); - assertEquals("Last key in head map should be B", - "B", map.headMap("C").lastKey()); + assertEquals("First key in tail map should be B", + "B", map.tailMap((K) "B").firstKey()); + assertEquals("Last key in head map should be B", + "B", map.headMap((K) "C").lastKey()); assertEquals("Last key in submap should be B", - "B", map.subMap("A","C").lastKey()); - - Comparator c = map.comparator(); - assertTrue("natural order, so comparator should be null", + "B", map.subMap((K) "A",(K) "C").lastKey()); + + Comparator c = map.comparator(); + assertTrue("natural order, so comparator should be null", c == null); } @@ -195,4 +195,4 @@ public class TestPredicatedSortedMap extends AbstractTestSortedMap{ // (java.io.Serializable) map, // "D:/dev/collections/data/test/PredicatedSortedMap.fullCollection.version3.1.obj"); // } -} \ No newline at end of file +} diff --git a/src/test/org/apache/commons/collections/map/TestReferenceIdentityMap.java b/src/test/org/apache/commons/collections/map/TestReferenceIdentityMap.java index efe120270..421950adc 100644 --- a/src/test/org/apache/commons/collections/map/TestReferenceIdentityMap.java +++ b/src/test/org/apache/commons/collections/map/TestReferenceIdentityMap.java @@ -24,9 +24,10 @@ import junit.framework.Test; import org.apache.commons.collections.BulkTest; import org.apache.commons.collections.IterableMap; +import org.apache.commons.collections.map.AbstractReferenceMap.ReferenceStrength; /** - * Tests for ReferenceIdentityMap. + * Tests for ReferenceIdentityMap. * * @version $Revision$ * @@ -34,7 +35,7 @@ import org.apache.commons.collections.IterableMap; * @author Stephen Colebourne * @author Guilhem Lavaux */ -public class TestReferenceIdentityMap extends AbstractTestIterableMap { +public class TestReferenceIdentityMap extends AbstractTestIterableMap { private static final Integer I1A = new Integer(1); private static final Integer I1B = new Integer(1); @@ -54,15 +55,15 @@ public class TestReferenceIdentityMap extends AbstractTestIterableMap { junit.textui.TestRunner.main(testCaseName); } - public Map makeEmptyMap() { - ReferenceIdentityMap map = new ReferenceIdentityMap(ReferenceIdentityMap.WEAK, ReferenceIdentityMap.WEAK); - return map; + public ReferenceIdentityMap makeObject() { + return new ReferenceIdentityMap(ReferenceStrength.WEAK, ReferenceStrength.WEAK); } - - public Map makeConfirmedMap() { + + public Map makeConfirmedMap() { // Testing against another [collections] class generally isn't a good idea, - // but the alternative is a JDK1.4 dependency in the tests - return new IdentityMap(); + // but the closest alternative is IdentityHashMap, which propagates reference-equality down to keySet and values. + // arguably ReferenceIdentityMap should do the same but that's a later discussion. + return new IdentityMap(); } public boolean isAllowNullKey() { @@ -78,11 +79,12 @@ public class TestReferenceIdentityMap extends AbstractTestIterableMap { } //----------------------------------------------------------------------- + @SuppressWarnings("unchecked") public void testBasics() { - IterableMap map = new ReferenceIdentityMap(ReferenceIdentityMap.HARD, ReferenceIdentityMap.HARD); + IterableMap map = new ReferenceIdentityMap(ReferenceStrength.HARD, ReferenceStrength.HARD); assertEquals(0, map.size()); - - map.put(I1A, I2A); + + map.put((K) I1A, (V) I2A); assertEquals(1, map.size()); assertSame(I2A, map.get(I1A)); assertSame(null, map.get(I1B)); @@ -90,8 +92,8 @@ public class TestReferenceIdentityMap extends AbstractTestIterableMap { assertEquals(false, map.containsKey(I1B)); assertEquals(true, map.containsValue(I2A)); assertEquals(false, map.containsValue(I2B)); - - map.put(I1A, I2B); + + map.put((K) I1A, (V) I2B); assertEquals(1, map.size()); assertSame(I2B, map.get(I1A)); assertSame(null, map.get(I1B)); @@ -99,8 +101,8 @@ public class TestReferenceIdentityMap extends AbstractTestIterableMap { assertEquals(false, map.containsKey(I1B)); assertEquals(false, map.containsValue(I2A)); assertEquals(true, map.containsValue(I2B)); - - map.put(I1B, I2B); + + map.put((K) I1B, (V) I2B); assertEquals(2, map.size()); assertSame(I2B, map.get(I1A)); assertSame(I2B, map.get(I1B)); @@ -109,45 +111,46 @@ public class TestReferenceIdentityMap extends AbstractTestIterableMap { assertEquals(false, map.containsValue(I2A)); assertEquals(true, map.containsValue(I2B)); } - + //----------------------------------------------------------------------- + @SuppressWarnings("unchecked") public void testHashEntry() { - IterableMap map = new ReferenceIdentityMap(ReferenceIdentityMap.HARD, ReferenceIdentityMap.HARD); - - map.put(I1A, I2A); - map.put(I1B, I2A); - - Map.Entry entry1 = (Map.Entry) map.entrySet().iterator().next(); - Iterator it = map.entrySet().iterator(); - Map.Entry entry2 = (Map.Entry) it.next(); - Map.Entry entry3 = (Map.Entry) it.next(); - + IterableMap map = new ReferenceIdentityMap(ReferenceStrength.HARD, ReferenceStrength.HARD); + + map.put((K) I1A, (V) I2A); + map.put((K) I1B, (V) I2A); + + Map.Entry entry1 = map.entrySet().iterator().next(); + Iterator> it = map.entrySet().iterator(); + Map.Entry entry2 = it.next(); + Map.Entry entry3 = it.next(); + assertEquals(true, entry1.equals(entry2)); assertEquals(true, entry2.equals(entry1)); assertEquals(false, entry1.equals(entry3)); } - - + //----------------------------------------------------------------------- + @SuppressWarnings("unchecked") public void testNullHandling() { resetFull(); - assertEquals(null, map.get(null)); - assertEquals(false, map.containsKey(null)); - assertEquals(false, map.containsValue(null)); - assertEquals(null, map.remove(null)); - assertEquals(false, map.entrySet().contains(null)); - assertEquals(false, map.keySet().contains(null)); - assertEquals(false, map.values().contains(null)); + assertEquals(null, getMap().get(null)); + assertEquals(false, getMap().containsKey(null)); + assertEquals(false, getMap().containsValue(null)); + assertEquals(null, getMap().remove(null)); + assertEquals(false, getMap().entrySet().contains(null)); + assertEquals(false, getMap().keySet().contains(null)); + assertEquals(false, getMap().values().contains(null)); try { - map.put(null, null); + getMap().put(null, null); fail(); } catch (NullPointerException ex) {} try { - map.put(new Object(), null); + getMap().put((K) new Object(), null); fail(); } catch (NullPointerException ex) {} try { - map.put(null, new Object()); + getMap().put(null, (V) new Object()); fail(); } catch (NullPointerException ex) {} } @@ -263,19 +266,20 @@ public class TestReferenceIdentityMap extends AbstractTestIterableMap { } */ - WeakReference keyReference; - WeakReference valueReference; + WeakReference keyReference; + WeakReference valueReference; - public Map buildRefMap() { - Object key = new Object(); - Object value = new Object(); - - keyReference = new WeakReference(key); - valueReference = new WeakReference(value); - - Map testMap = new ReferenceIdentityMap(ReferenceMap.WEAK, ReferenceMap.HARD, true); + @SuppressWarnings("unchecked") + private Map buildRefMap() { + K key = (K) new Object(); + V value = (V) new Object(); + + keyReference = new WeakReference(key); + valueReference = new WeakReference(value); + + Map testMap = new ReferenceIdentityMap(ReferenceStrength.WEAK, ReferenceStrength.HARD, true); testMap.put(key, value); - + assertEquals("In map", value, testMap.get(key)); assertNotNull("Weak reference released early (1)", keyReference.get()); assertNotNull("Weak reference released early (2)", valueReference.get()); @@ -285,29 +289,31 @@ public class TestReferenceIdentityMap extends AbstractTestIterableMap { /** Tests whether purge values setting works */ public void testPurgeValues() throws Exception { // many thanks to Juozas Baliuka for suggesting this method - Map testMap = buildRefMap(); - + Map testMap = buildRefMap(); + int iterations = 0; int bytz = 2; - while(true) { + while (true) { System.gc(); - if(iterations++ > 50){ + if (iterations++ > 50) { fail("Max iterations reached before resource released."); } testMap.isEmpty(); - if( + if ( keyReference.get() == null && valueReference.get() == null) { break; - + } else { // create garbage: + @SuppressWarnings("unused") byte[] b = new byte[bytz]; bytz = bytz * 2; } } } + @SuppressWarnings("unused") private static void gc() { try { // trigger GC diff --git a/src/test/org/apache/commons/collections/map/TestReferenceMap.java b/src/test/org/apache/commons/collections/map/TestReferenceMap.java index 1b84894f5..d4c05d295 100644 --- a/src/test/org/apache/commons/collections/map/TestReferenceMap.java +++ b/src/test/org/apache/commons/collections/map/TestReferenceMap.java @@ -22,16 +22,17 @@ import java.util.Map; import junit.framework.Test; import org.apache.commons.collections.BulkTest; +import org.apache.commons.collections.map.AbstractReferenceMap.ReferenceStrength; /** - * Tests for ReferenceMap. + * Tests for ReferenceMap. * * @version $Revision$ $Date$ * * @author Paul Jack * @author Guilhem Lavaux */ -public class TestReferenceMap extends AbstractTestIterableMap { +public class TestReferenceMap extends AbstractTestIterableMap { public TestReferenceMap(String testName) { super(testName); @@ -46,9 +47,8 @@ public class TestReferenceMap extends AbstractTestIterableMap { junit.textui.TestRunner.main(testCaseName); } - public Map makeEmptyMap() { - ReferenceMap map = new ReferenceMap(ReferenceMap.WEAK, ReferenceMap.WEAK); - return map; + public ReferenceMap makeObject() { + return new ReferenceMap(ReferenceStrength.WEAK, ReferenceStrength.WEAK); } public boolean isAllowNullKey() { @@ -64,6 +64,7 @@ public class TestReferenceMap extends AbstractTestIterableMap { } //----------------------------------------------------------------------- + @SuppressWarnings("unchecked") public void testNullHandling() { resetFull(); assertEquals(null, map.get(null)); @@ -78,11 +79,11 @@ public class TestReferenceMap extends AbstractTestIterableMap { fail(); } catch (NullPointerException ex) {} try { - map.put(new Object(), null); + map.put((K) new Object(), null); fail(); } catch (NullPointerException ex) {} try { - map.put(null, new Object()); + map.put(null, (V) new Object()); fail(); } catch (NullPointerException ex) {} } @@ -198,19 +199,20 @@ public class TestReferenceMap extends AbstractTestIterableMap { } */ - WeakReference keyReference; - WeakReference valueReference; + WeakReference keyReference; + WeakReference valueReference; - public Map buildRefMap() { - Object key = new Object(); - Object value = new Object(); - - keyReference = new WeakReference(key); - valueReference = new WeakReference(value); - - Map testMap = new ReferenceMap(ReferenceMap.WEAK, ReferenceMap.HARD, true); + @SuppressWarnings("unchecked") + public Map buildRefMap() { + K key = (K) new Object(); + V value = (V) new Object(); + + keyReference = new WeakReference(key); + valueReference = new WeakReference(value); + + Map testMap = new ReferenceMap(ReferenceStrength.WEAK, ReferenceStrength.HARD, true); testMap.put(key, value); - + assertEquals("In map", value, testMap.get(key)); assertNotNull("Weak reference released early (1)", keyReference.get()); assertNotNull("Weak reference released early (2)", valueReference.get()); @@ -220,29 +222,29 @@ public class TestReferenceMap extends AbstractTestIterableMap { /** Tests whether purge values setting works */ public void testPurgeValues() throws Exception { // many thanks to Juozas Baliuka for suggesting this method - Map testMap = buildRefMap(); + Map testMap = buildRefMap(); int iterations = 0; int bytz = 2; - while(true) { + while (true) { System.gc(); - if(iterations++ > 50){ + if (iterations++ > 50) { fail("Max iterations reached before resource released."); } testMap.isEmpty(); - if( - keyReference.get() == null && - valueReference.get() == null) { + if (keyReference.get() == null && valueReference.get() == null) { break; - + } else { // create garbage: - byte[] b = new byte[bytz]; + @SuppressWarnings("unused") + byte[] b = new byte[bytz]; bytz = bytz * 2; } } } + @SuppressWarnings("unused") private static void gc() { try { // trigger GC diff --git a/src/test/org/apache/commons/collections/map/TestSingletonMap.java b/src/test/org/apache/commons/collections/map/TestSingletonMap.java index 74a127fe3..575f1bca7 100644 --- a/src/test/org/apache/commons/collections/map/TestSingletonMap.java +++ b/src/test/org/apache/commons/collections/map/TestSingletonMap.java @@ -17,7 +17,6 @@ package org.apache.commons.collections.map; import java.util.HashMap; -import java.util.Map; import junit.framework.Test; import junit.textui.TestRunner; @@ -25,6 +24,7 @@ import junit.textui.TestRunner; import org.apache.commons.collections.BoundedMap; import org.apache.commons.collections.BulkTest; import org.apache.commons.collections.KeyValue; +import org.apache.commons.collections.OrderedMap; /** * JUnit tests. @@ -33,13 +33,12 @@ import org.apache.commons.collections.KeyValue; * * @author Stephen Colebourne */ -public class TestSingletonMap extends AbstractTestOrderedMap { +public class TestSingletonMap extends AbstractTestOrderedMap { private static final Integer ONE = new Integer(1); private static final Integer TWO = new Integer(2); private static final String TEN = "10"; - private static final String TWENTY = "20"; - + public TestSingletonMap(String testName) { super(testName); } @@ -47,18 +46,18 @@ public class TestSingletonMap extends AbstractTestOrderedMap { public static void main(String[] args) { TestRunner.run(suite()); } - + public static Test suite() { return BulkTest.makeSuite(TestSingletonMap.class); } //----------------------------------------------------------------------- - public Map makeEmptyMap() { + public OrderedMap makeObject() { // need an empty singleton map, but thats not possible // use a ridiculous fake instead to make the tests pass - return UnmodifiableOrderedMap.decorate(ListOrderedMap.decorate(new HashMap())); + return UnmodifiableOrderedMap.decorate(ListOrderedMap.decorate(new HashMap())); } - + public String[] ignoredTests() { // the ridiculous map above still doesn't pass these tests // but its not relevant, so we ignore them @@ -68,9 +67,9 @@ public class TestSingletonMap extends AbstractTestOrderedMap { }; } - - public Map makeFullMap() { - return new SingletonMap(ONE, TWO); + @SuppressWarnings("unchecked") + public SingletonMap makeFullMap() { + return new SingletonMap((K) ONE, (V) TWO); } public boolean isPutAddSupported() { @@ -81,30 +80,33 @@ public class TestSingletonMap extends AbstractTestOrderedMap { return false; } - public Object[] getSampleKeys() { - return new Object[] {ONE}; + @SuppressWarnings("unchecked") + public K[] getSampleKeys() { + return (K[]) new Object[] { ONE }; } - public Object[] getSampleValues() { - return new Object[] {TWO}; + @SuppressWarnings("unchecked") + public V[] getSampleValues() { + return (V[]) new Object[] { TWO }; } - public Object[] getNewSampleValues() { - return new Object[] {TEN}; + @SuppressWarnings("unchecked") + public V[] getNewSampleValues() { + return (V[]) new Object[] { TEN }; } //----------------------------------------------------------------------- public void testClone() { - SingletonMap map = new SingletonMap(ONE, TWO); + SingletonMap map = makeFullMap(); assertEquals(1, map.size()); - SingletonMap cloned = (SingletonMap) map.clone(); + SingletonMap cloned = map.clone(); assertEquals(1, cloned.size()); assertEquals(true, cloned.containsKey(ONE)); assertEquals(true, cloned.containsValue(TWO)); } public void testKeyValue() { - SingletonMap map = new SingletonMap(ONE, TWO); + SingletonMap map = makeFullMap(); assertEquals(1, map.size()); assertEquals(ONE, map.getKey()); assertEquals(TWO, map.getValue()); @@ -112,7 +114,7 @@ public class TestSingletonMap extends AbstractTestOrderedMap { } public void testBoundedMap() { - SingletonMap map = new SingletonMap(ONE, TWO); + SingletonMap map = makeFullMap(); assertEquals(1, map.size()); assertEquals(true, map.isFull()); assertEquals(1, map.maxSize()); @@ -123,16 +125,16 @@ public class TestSingletonMap extends AbstractTestOrderedMap { // public BulkTest bulkTestMapIterator() { // return new TestFlatMapIterator(); // } -// +// // public class TestFlatMapIterator extends AbstractTestOrderedMapIterator { // public TestFlatMapIterator() { // super("TestFlatMapIterator"); // } -// +// // public Object[] addSetValues() { // return TestSingletonMap.this.getNewSampleValues(); // } -// +// // public boolean supportsRemove() { // return TestSingletonMap.this.isRemoveSupported(); // } @@ -150,23 +152,23 @@ public class TestSingletonMap extends AbstractTestOrderedMap { // resetFull(); // return ((Flat3Map) TestSingletonMap.this.map).mapIterator(); // } -// +// // public Map getMap() { // // assumes makeFullMapIterator() called first // return TestSingletonMap.this.map; // } -// +// // public Map getConfirmedMap() { // // assumes makeFullMapIterator() called first // return TestSingletonMap.this.confirmed; // } -// +// // public void verify() { // super.verify(); // TestSingletonMap.this.verify(); // } // } - + public String getCompatibilityVersion() { return "3.1"; } diff --git a/src/test/org/apache/commons/collections/map/TestTransformedSortedMap.java b/src/test/org/apache/commons/collections/map/TestTransformedSortedMap.java index c14945432..0d5234853 100644 --- a/src/test/org/apache/commons/collections/map/TestTransformedSortedMap.java +++ b/src/test/org/apache/commons/collections/map/TestTransformedSortedMap.java @@ -24,6 +24,7 @@ import java.util.TreeMap; import junit.framework.Test; import org.apache.commons.collections.BulkTest; +import org.apache.commons.collections.Transformer; import org.apache.commons.collections.TransformerUtils; import org.apache.commons.collections.collection.TestTransformedCollection; @@ -36,8 +37,8 @@ import org.apache.commons.collections.collection.TestTransformedCollection; * * @author Stephen Colebourne */ -public class TestTransformedSortedMap extends AbstractTestSortedMap { - +public class TestTransformedSortedMap extends AbstractTestSortedMap { + public TestTransformedSortedMap(String testName) { super(testName); } @@ -52,8 +53,11 @@ public class TestTransformedSortedMap extends AbstractTestSortedMap { } //----------------------------------------------------------------------- - public Map makeEmptyMap() { - return TransformedSortedMap.decorate(new TreeMap(), TransformerUtils.nopTransformer(), TransformerUtils.nopTransformer()); + @SuppressWarnings("unchecked") + public SortedMap makeObject() { + return TransformedSortedMap.decorate(new TreeMap(), + (Transformer) TransformerUtils.nopTransformer(), + (Transformer) TransformerUtils.nopTransformer()); } public boolean isSubMapViewsSerializable() { @@ -61,14 +65,19 @@ public class TestTransformedSortedMap extends AbstractTestSortedMap { return false; } - //----------------------------------------------------------------------- + //----------------------------------------------------------------------- + @SuppressWarnings("unchecked") public void testTransformedMap() { - Object[] els = new Object[] {"1", "3", "5", "7", "2", "4", "6"}; + Object[] els = new Object[] { "1", "3", "5", "7", "2", "4", "6" }; - Map map = TransformedSortedMap.decorate(new TreeMap(), TestTransformedCollection.STRING_TO_INTEGER_TRANSFORMER, null); + SortedMap map = TransformedSortedMap + .decorate( + new TreeMap(), + (Transformer) TestTransformedCollection.STRING_TO_INTEGER_TRANSFORMER, + null); assertEquals(0, map.size()); for (int i = 0; i < els.length; i++) { - map.put(els[i], els[i]); + map.put((K) els[i], (V) els[i]); assertEquals(i + 1, map.size()); assertEquals(true, map.containsKey(new Integer((String) els[i]))); try { @@ -78,17 +87,21 @@ public class TestTransformedSortedMap extends AbstractTestSortedMap { assertEquals(true, map.containsValue(els[i])); assertEquals(els[i], map.get(new Integer((String) els[i]))); } - + try { map.remove(els[0]); fail(); } catch (ClassCastException ex) {} assertEquals(els[0], map.remove(new Integer((String) els[0]))); - - map = TransformedSortedMap.decorate(new TreeMap(), null, TestTransformedCollection.STRING_TO_INTEGER_TRANSFORMER); + + map = TransformedSortedMap + .decorate( + new TreeMap(), + null, + (Transformer) TestTransformedCollection.STRING_TO_INTEGER_TRANSFORMER); assertEquals(0, map.size()); for (int i = 0; i < els.length; i++) { - map.put(els[i], els[i]); + map.put((K) els[i], (V) els[i]); assertEquals(i + 1, map.size()); assertEquals(true, map.containsValue(new Integer((String) els[i]))); assertEquals(false, map.containsValue(els[i])); @@ -97,47 +110,57 @@ public class TestTransformedSortedMap extends AbstractTestSortedMap { } assertEquals(new Integer((String) els[0]), map.remove(els[0])); - - Set entrySet = map.entrySet(); - Map.Entry[] array = (Map.Entry[]) entrySet.toArray(new Map.Entry[0]); - array[0].setValue("66"); + + Set> entrySet = map.entrySet(); + Map.Entry[] array = (Map.Entry[]) entrySet.toArray(new Map.Entry[0]); + array[0].setValue((V) "66"); assertEquals(new Integer(66), array[0].getValue()); assertEquals(new Integer(66), map.get(array[0].getKey())); - - Map.Entry entry = (Map.Entry) entrySet.iterator().next(); - entry.setValue("88"); + + Map.Entry entry = entrySet.iterator().next(); + entry.setValue((V) "88"); assertEquals(new Integer(88), entry.getValue()); assertEquals(new Integer(88), map.get(entry.getKey())); } //----------------------------------------------------------------------- + @SuppressWarnings("unchecked") public void testFactory_Decorate() { - SortedMap base = new TreeMap(); - base.put("A", "1"); - base.put("B", "2"); - base.put("C", "3"); - - SortedMap trans = TransformedSortedMap.decorate(base, null, TestTransformedCollection.STRING_TO_INTEGER_TRANSFORMER); + SortedMap base = new TreeMap(); + base.put((K) "A", (V) "1"); + base.put((K) "B", (V) "2"); + base.put((K) "C", (V) "3"); + + SortedMap trans = TransformedSortedMap + .decorate( + base, + null, + (Transformer) TestTransformedCollection.STRING_TO_INTEGER_TRANSFORMER); assertEquals(3, trans.size()); assertEquals("1", trans.get("A")); assertEquals("2", trans.get("B")); assertEquals("3", trans.get("C")); - trans.put("D", "4"); + trans.put((K) "D", (V) "4"); assertEquals(new Integer(4), trans.get("D")); } + @SuppressWarnings("unchecked") public void testFactory_decorateTransform() { - SortedMap base = new TreeMap(); - base.put("A", "1"); - base.put("B", "2"); - base.put("C", "3"); - - SortedMap trans = TransformedSortedMap.decorateTransform(base, null, TestTransformedCollection.STRING_TO_INTEGER_TRANSFORMER); + SortedMap base = new TreeMap(); + base.put((K) "A", (V) "1"); + base.put((K) "B", (V) "2"); + base.put((K) "C", (V) "3"); + + SortedMap trans = TransformedSortedMap + .decorateTransform( + base, + null, + (Transformer) TestTransformedCollection.STRING_TO_INTEGER_TRANSFORMER); assertEquals(3, trans.size()); assertEquals(new Integer(1), trans.get("A")); assertEquals(new Integer(2), trans.get("B")); assertEquals(new Integer(3), trans.get("C")); - trans.put("D", "4"); + trans.put((K) "D", (V) "4"); assertEquals(new Integer(4), trans.get("D")); } diff --git a/src/test/org/apache/commons/collections/map/TestUnmodifiableMap.java b/src/test/org/apache/commons/collections/map/TestUnmodifiableMap.java index 5e792b04d..9eb2b8c64 100644 --- a/src/test/org/apache/commons/collections/map/TestUnmodifiableMap.java +++ b/src/test/org/apache/commons/collections/map/TestUnmodifiableMap.java @@ -22,10 +22,11 @@ import java.util.Map; import junit.framework.Test; import junit.framework.TestSuite; +import org.apache.commons.collections.IterableMap; import org.apache.commons.collections.Unmodifiable; /** - * Extension of {@link AbstractTestMap} for exercising the + * Extension of {@link AbstractTestMap} for exercising the * {@link UnmodifiableMap} implementation. * * @since Commons Collections 3.0 @@ -33,55 +34,55 @@ import org.apache.commons.collections.Unmodifiable; * * @author Phil Steitz */ -public class TestUnmodifiableMap extends AbstractTestIterableMap{ - +public class TestUnmodifiableMap extends AbstractTestIterableMap { + public TestUnmodifiableMap(String testName) { super(testName); } - + public static Test suite() { return new TestSuite(TestUnmodifiableMap.class); } - + public static void main(String args[]) { String[] testCaseName = { TestUnmodifiableMap.class.getName()}; junit.textui.TestRunner.main(testCaseName); } - + //------------------------------------------------------------------- - - public Map makeEmptyMap() { - return UnmodifiableMap.decorate(new HashMap()); + + public IterableMap makeObject() { + return (IterableMap) UnmodifiableMap.decorate(new HashMap()); } - + public boolean isPutChangeSupported() { return false; } - + public boolean isPutAddSupported() { return false; } - + public boolean isRemoveSupported() { return false; } - - public Map makeFullMap() { - Map m = new HashMap(); + + public IterableMap makeFullMap() { + Map m = new HashMap(); addSampleMappings(m); - return UnmodifiableMap.decorate(m); + return (IterableMap) UnmodifiableMap.decorate(m); } - + //----------------------------------------------------------------------- public void testUnmodifiable() { - assertTrue(makeEmptyMap() instanceof Unmodifiable); + assertTrue(makeObject() instanceof Unmodifiable); assertTrue(makeFullMap() instanceof Unmodifiable); } - + public void testDecorateFactory() { - Map map = makeFullMap(); + Map map = makeFullMap(); assertSame(map, UnmodifiableMap.decorate(map)); - + try { UnmodifiableMap.decorate(null); fail(); @@ -102,4 +103,4 @@ public class TestUnmodifiableMap extends AbstractTestIterableMap{ // (java.io.Serializable) map, // "D:/dev/collections/data/test/UnmodifiableMap.fullCollection.version3.1.obj"); // } -} \ No newline at end of file +} diff --git a/src/test/org/apache/commons/collections/map/TestUnmodifiableOrderedMap.java b/src/test/org/apache/commons/collections/map/TestUnmodifiableOrderedMap.java index 5ba3490df..74f4a9e31 100644 --- a/src/test/org/apache/commons/collections/map/TestUnmodifiableOrderedMap.java +++ b/src/test/org/apache/commons/collections/map/TestUnmodifiableOrderedMap.java @@ -17,7 +17,6 @@ package org.apache.commons.collections.map; import java.util.HashMap; -import java.util.Map; import junit.framework.Test; import junit.framework.TestSuite; @@ -26,7 +25,7 @@ import org.apache.commons.collections.OrderedMap; import org.apache.commons.collections.Unmodifiable; /** - * Extension of {@link AbstractTestOrderedMap} for exercising the + * Extension of {@link AbstractTestOrderedMap} for exercising the * {@link UnmodifiableOrderedMap} implementation. * * @since Commons Collections 3.0 @@ -34,55 +33,55 @@ import org.apache.commons.collections.Unmodifiable; * * @author Stephen Colebourne */ -public class TestUnmodifiableOrderedMap extends AbstractTestOrderedMap { - +public class TestUnmodifiableOrderedMap extends AbstractTestOrderedMap { + public TestUnmodifiableOrderedMap(String testName) { super(testName); } - + public static Test suite() { return new TestSuite(TestUnmodifiableOrderedMap.class); } - + public static void main(String args[]) { String[] testCaseName = { TestUnmodifiableOrderedMap.class.getName()}; junit.textui.TestRunner.main(testCaseName); } - + //------------------------------------------------------------------- - - public Map makeEmptyMap() { - return UnmodifiableOrderedMap.decorate(ListOrderedMap.decorate(new HashMap())); + + public OrderedMap makeObject() { + return UnmodifiableOrderedMap.decorate(ListOrderedMap.decorate(new HashMap())); } - + public boolean isPutChangeSupported() { return false; } - + public boolean isPutAddSupported() { return false; } - + public boolean isRemoveSupported() { return false; } - - public Map makeFullMap() { - OrderedMap m = ListOrderedMap.decorate(new HashMap()); + + public OrderedMap makeFullMap() { + OrderedMap m = ListOrderedMap.decorate(new HashMap()); addSampleMappings(m); return UnmodifiableOrderedMap.decorate(m); } - + //----------------------------------------------------------------------- public void testUnmodifiable() { - assertTrue(makeEmptyMap() instanceof Unmodifiable); + assertTrue(makeObject() instanceof Unmodifiable); assertTrue(makeFullMap() instanceof Unmodifiable); } - + public void testDecorateFactory() { - Map map = makeFullMap(); - assertSame(map, UnmodifiableOrderedMap.decorate((OrderedMap) map)); - + OrderedMap map = makeFullMap(); + assertSame(map, UnmodifiableOrderedMap.decorate(map)); + try { UnmodifiableOrderedMap.decorate(null); fail(); @@ -103,4 +102,4 @@ public class TestUnmodifiableOrderedMap extends AbstractTestOrderedMap { // (java.io.Serializable) map, // "D:/dev/collections/data/test/UnmodifiableOrderedMap.fullCollection.version3.1.obj"); // } -} \ No newline at end of file +} diff --git a/src/test/org/apache/commons/collections/map/TestUnmodifiableSortedMap.java b/src/test/org/apache/commons/collections/map/TestUnmodifiableSortedMap.java index 961668b52..eb155e9a9 100644 --- a/src/test/org/apache/commons/collections/map/TestUnmodifiableSortedMap.java +++ b/src/test/org/apache/commons/collections/map/TestUnmodifiableSortedMap.java @@ -16,7 +16,6 @@ */ package org.apache.commons.collections.map; -import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; @@ -26,7 +25,7 @@ import junit.framework.TestSuite; import org.apache.commons.collections.Unmodifiable; /** - * Extension of {@link AbstractTestSortedMap} for exercising the + * Extension of {@link AbstractTestSortedMap} for exercising the * {@link UnmodifiableSortedMap} implementation. * * @since Commons Collections 3.0 @@ -34,55 +33,55 @@ import org.apache.commons.collections.Unmodifiable; * * @author Stephen Colebourne */ -public class TestUnmodifiableSortedMap extends AbstractTestSortedMap { - +public class TestUnmodifiableSortedMap extends AbstractTestSortedMap { + public TestUnmodifiableSortedMap(String testName) { super(testName); } - + public static Test suite() { return new TestSuite(TestUnmodifiableSortedMap.class); } - + public static void main(String args[]) { String[] testCaseName = { TestUnmodifiableSortedMap.class.getName()}; junit.textui.TestRunner.main(testCaseName); } - + //------------------------------------------------------------------- - - public Map makeEmptyMap() { - return UnmodifiableSortedMap.decorate(new TreeMap()); + + public SortedMap makeObject() { + return UnmodifiableSortedMap.decorate(new TreeMap()); } - + public boolean isPutChangeSupported() { return false; } - + public boolean isPutAddSupported() { return false; } - + public boolean isRemoveSupported() { return false; } - - public Map makeFullMap() { - SortedMap m = new TreeMap(); + + public SortedMap makeFullMap() { + SortedMap m = new TreeMap(); addSampleMappings(m); return UnmodifiableSortedMap.decorate(m); } - + //----------------------------------------------------------------------- public void testUnmodifiable() { - assertTrue(makeEmptyMap() instanceof Unmodifiable); + assertTrue(makeObject() instanceof Unmodifiable); assertTrue(makeFullMap() instanceof Unmodifiable); } - + public void testDecorateFactory() { - Map map = makeFullMap(); - assertSame(map, UnmodifiableSortedMap.decorate((SortedMap) map)); - + SortedMap map = makeFullMap(); + assertSame(map, UnmodifiableSortedMap.decorate(map)); + try { UnmodifiableSortedMap.decorate(null); fail(); @@ -103,4 +102,4 @@ public class TestUnmodifiableSortedMap extends AbstractTestSortedMap { // (java.io.Serializable) map, // "D:/dev/collections/data/test/UnmodifiableSortedMap.fullCollection.version3.1.obj"); // } -} \ No newline at end of file +} diff --git a/src/test/org/apache/commons/collections/set/AbstractTestSet.java b/src/test/org/apache/commons/collections/set/AbstractTestSet.java index 0242c27f6..136ac7a20 100644 --- a/src/test/org/apache/commons/collections/set/AbstractTestSet.java +++ b/src/test/org/apache/commons/collections/set/AbstractTestSet.java @@ -43,7 +43,7 @@ import org.apache.commons.collections.collection.AbstractTestCollection; * * @author Paul Jack */ -public abstract class AbstractTestSet extends AbstractTestCollection { +public abstract class AbstractTestSet extends AbstractTestCollection { /** * JUnit constructor. @@ -61,14 +61,13 @@ public abstract class AbstractTestSet extends AbstractTestCollection { public void verify() { super.verify(); - assertEquals("Sets should be equal", confirmed, collection); + assertEquals("Sets should be equal", getConfirmed(), getCollection()); assertEquals("Sets should have equal hashCodes", - confirmed.hashCode(), collection.hashCode()); - Collection set = makeConfirmedCollection(); - Iterator iterator = collection.iterator(); + getConfirmed().hashCode(), getCollection().hashCode()); + Collection set = makeConfirmedCollection(); + Iterator iterator = getCollection().iterator(); while (iterator.hasNext()) { - assertTrue("Set.iterator should only return unique elements", - set.add(iterator.next())); + assertTrue("Set.iterator should only return unique elements", set.add(iterator.next())); } } @@ -85,8 +84,8 @@ public abstract class AbstractTestSet extends AbstractTestCollection { * * @return a confirmed empty collection */ - public Collection makeConfirmedCollection() { - return new HashSet(); + public Collection makeConfirmedCollection() { + return new HashSet(); } /** @@ -94,8 +93,8 @@ public abstract class AbstractTestSet extends AbstractTestCollection { * * @return a confirmed full collection */ - public Collection makeConfirmedFullCollection() { - Collection set = makeConfirmedCollection(); + public Collection makeConfirmedFullCollection() { + Collection set = makeConfirmedCollection(); set.addAll(Arrays.asList(getFullElements())); return set; } @@ -105,7 +104,7 @@ public abstract class AbstractTestSet extends AbstractTestCollection { * * @return an empty set */ - public abstract Set makeEmptySet(); + public abstract Set makeObject(); /** * Makes a full set by first creating an empty set and then adding @@ -115,68 +114,48 @@ public abstract class AbstractTestSet extends AbstractTestCollection { * * @return a full set */ - public Set makeFullSet() { - Set set = makeEmptySet(); + public Set makeFullCollection() { + Set set = makeObject(); set.addAll(Arrays.asList(getFullElements())); return set; } - /** - * Makes an empty collection by invoking {@link #makeEmptySet()}. - * - * @return an empty collection - */ - public final Collection makeCollection() { - return makeEmptySet(); - } - - /** - * Makes a full collection by invoking {@link #makeFullSet()}. - * - * @return a full collection - */ - public final Collection makeFullCollection() { - return makeFullSet(); - } - //----------------------------------------------------------------------- /** * Return the {@link AbstractTestCollection#collection} fixture, but cast as a Set. */ - public Set getSet() { - return (Set)collection; + public Set getCollection() { + return (Set) super.getCollection(); } /** * Return the {@link AbstractTestCollection#confirmed} fixture, but cast as a Set. */ - public Set getConfirmedSet() { - return (Set)confirmed; + public Set getConfirmed() { + return (Set) super.getConfirmed(); } //----------------------------------------------------------------------- /** * Tests {@link Set#equals(Object)}. */ + @SuppressWarnings("unchecked") public void testSetEquals() { resetEmpty(); - assertEquals("Empty sets should be equal", - getSet(), getConfirmedSet()); + assertEquals("Empty sets should be equal", getCollection(), getConfirmed()); verify(); - Collection set2 = makeConfirmedCollection(); - set2.add("foo"); - assertTrue("Empty set shouldn't equal nonempty set", - !getSet().equals(set2)); + Collection set2 = makeConfirmedCollection(); + set2.add((E) "foo"); + assertTrue("Empty set shouldn't equal nonempty set", !getCollection().equals(set2)); resetFull(); - assertEquals("Full sets should be equal", getSet(), getConfirmedSet()); + assertEquals("Full sets should be equal", getCollection(), getConfirmed()); verify(); set2.clear(); set2.addAll(Arrays.asList(getOtherElements())); - assertTrue("Sets with different contents shouldn't be equal", - !getSet().equals(set2)); + assertTrue("Sets with different contents shouldn't be equal", !getCollection().equals(set2)); } /** @@ -185,11 +164,11 @@ public abstract class AbstractTestSet extends AbstractTestCollection { public void testSetHashCode() { resetEmpty(); assertEquals("Empty sets have equal hashCodes", - getSet().hashCode(), getConfirmedSet().hashCode()); + getCollection().hashCode(), getConfirmed().hashCode()); resetFull(); assertEquals("Equal sets have equal hashCodes", - getSet().hashCode(), getConfirmedSet().hashCode()); + getCollection().hashCode(), getConfirmed().hashCode()); } } diff --git a/src/test/org/apache/commons/collections/set/AbstractTestSortedSet.java b/src/test/org/apache/commons/collections/set/AbstractTestSortedSet.java index ef056b181..e1f31e161 100644 --- a/src/test/org/apache/commons/collections/set/AbstractTestSortedSet.java +++ b/src/test/org/apache/commons/collections/set/AbstractTestSortedSet.java @@ -16,9 +16,7 @@ */ package org.apache.commons.collections.set; -import java.util.Collection; import java.util.Iterator; -import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; @@ -38,7 +36,7 @@ import org.apache.commons.collections.BulkTest; * @author Stephen Colebourne * @author Dieter Wimberger */ -public abstract class AbstractTestSortedSet extends AbstractTestSet { +public abstract class AbstractTestSortedSet extends AbstractTestSet { /** * JUnit constructor. @@ -59,10 +57,10 @@ public abstract class AbstractTestSortedSet extends AbstractTestSet { // Check that iterator returns elements in order and first() and last() // are consistent - Iterator colliter = collection.iterator(); - Iterator confiter = confirmed.iterator(); - Object first = null; - Object last = null; + Iterator colliter = getCollection().iterator(); + Iterator confiter = getConfirmed().iterator(); + E first = null; + E last = null; while (colliter.hasNext()) { if (first == null) { first = colliter.next(); @@ -72,11 +70,11 @@ public abstract class AbstractTestSortedSet extends AbstractTestSet { } assertEquals("Element appears to be out of order.", last, confiter.next()); } - if (collection.size() > 0) { + if (getCollection().size() > 0) { assertEquals("Incorrect element returned by first().", first, - ((SortedSet) collection).first()); + getCollection().first()); assertEquals("Incorrect element returned by last().", last, - ((SortedSet) collection).last()); + getCollection().last()); } } @@ -89,47 +87,56 @@ public abstract class AbstractTestSortedSet extends AbstractTestSet { return false; } + /** + * {@inheritDoc} + */ + @Override + public abstract SortedSet makeObject(); + + /** + * {@inheritDoc} + */ + @Override + public SortedSet makeFullCollection() { + return (SortedSet) super.makeFullCollection(); + } + //----------------------------------------------------------------------- /** * Returns an empty {@link TreeSet} for use in modification testing. * * @return a confirmed empty collection */ - public Collection makeConfirmedCollection() { - return new TreeSet(); + public SortedSet makeConfirmedCollection() { + return new TreeSet(); } //----------------------------------------------------------------------- - /** - * Return the {@link AbstractTestCollection#confirmed} fixture, but cast as a - * SortedSet. - */ - public SortedSet getConfirmedSortedSet() { - return (SortedSet) confirmed; - } //----------------------------------------------------------------------- /** * Override to return comparable objects. */ - public Object[] getFullNonNullElements() { + @SuppressWarnings("unchecked") + public E[] getFullNonNullElements() { Object[] elements = new Object[30]; for (int i = 0; i < 30; i++) { elements[i] = new Integer(i + i + 1); } - return elements; + return (E[]) elements; } /** * Override to return comparable objects. */ - public Object[] getOtherNonNullElements() { + @SuppressWarnings("unchecked") + public E[] getOtherNonNullElements() { Object[] elements = new Object[30]; for (int i = 0; i < 30; i++) { elements[i] = new Integer(i + i + 2); } - return elements; + return (E[]) elements; } //----------------------------------------------------------------------- @@ -181,23 +188,24 @@ public abstract class AbstractTestSortedSet extends AbstractTestSet { return new TestSortedSetSubSet(lobound, false); } - public class TestSortedSetSubSet extends AbstractTestSortedSet { + public class TestSortedSetSubSet extends AbstractTestSortedSet { private int m_Type; private int m_LowBound; private int m_HighBound; - private Object[] m_FullElements; - private Object[] m_OtherElements; + private E[] m_FullElements; + private E[] m_OtherElements; + @SuppressWarnings("unchecked") public TestSortedSetSubSet(int bound, boolean head) { super("TestSortedSetSubSet"); if (head) { //System.out.println("HEADSET"); m_Type = TYPE_HEADSET; m_HighBound = bound; - m_FullElements = new Object[bound]; + m_FullElements = (E[]) new Object[bound]; System.arraycopy(AbstractTestSortedSet.this.getFullElements(), 0, m_FullElements, 0, bound); - m_OtherElements = new Object[bound - 1]; + m_OtherElements = (E[]) new Object[bound - 1]; System.arraycopy(//src src_pos dst dst_pos length AbstractTestSortedSet.this.getOtherElements(), 0, m_OtherElements, 0, bound - 1); //System.out.println(new TreeSet(Arrays.asList(m_FullElements))); @@ -208,9 +216,9 @@ public abstract class AbstractTestSortedSet extends AbstractTestSet { m_LowBound = bound; Object[] allelements = AbstractTestSortedSet.this.getFullElements(); //System.out.println("bound = "+bound +"::length="+allelements.length); - m_FullElements = new Object[allelements.length - bound]; + m_FullElements = (E[]) new Object[allelements.length - bound]; System.arraycopy(allelements, bound, m_FullElements, 0, allelements.length - bound); - m_OtherElements = new Object[allelements.length - bound - 1]; + m_OtherElements = (E[]) new Object[allelements.length - bound - 1]; System.arraycopy(//src src_pos dst dst_pos length AbstractTestSortedSet.this.getOtherElements(), bound, m_OtherElements, 0, allelements.length - bound - 1); //System.out.println(new TreeSet(Arrays.asList(m_FullElements))); @@ -223,6 +231,7 @@ public abstract class AbstractTestSortedSet extends AbstractTestSet { } //type + @SuppressWarnings("unchecked") public TestSortedSetSubSet(int lobound, int hibound) { super("TestSortedSetSubSet"); //System.out.println("SUBSET"); @@ -231,9 +240,9 @@ public abstract class AbstractTestSortedSet extends AbstractTestSet { m_HighBound = hibound; int length = hibound - lobound; //System.out.println("Low=" + lobound + "::High=" + hibound + "::Length=" + length); - m_FullElements = new Object[length]; + m_FullElements = (E[]) new Object[length]; System.arraycopy(AbstractTestSortedSet.this.getFullElements(), lobound, m_FullElements, 0, length); - m_OtherElements = new Object[length - 1]; + m_OtherElements = (E[]) new Object[length - 1]; System.arraycopy(//src src_pos dst dst_pos length AbstractTestSortedSet.this.getOtherElements(), lobound, m_OtherElements, 0, length - 1); @@ -255,15 +264,15 @@ public abstract class AbstractTestSortedSet extends AbstractTestSet { return AbstractTestSortedSet.this.isFailFastSupported(); } - public Object[] getFullElements() { + public E[] getFullElements() { return m_FullElements; } - public Object[] getOtherElements() { + public E[] getOtherElements() { return m_OtherElements; } - private SortedSet getSubSet(SortedSet set) { - Object[] elements = AbstractTestSortedSet.this.getFullElements(); + private SortedSet getSubSet(SortedSet set) { + E[] elements = AbstractTestSortedSet.this.getFullElements(); switch (m_Type) { case TYPE_SUBSET : return set.subSet(elements[m_LowBound], elements[m_HighBound]); @@ -276,14 +285,12 @@ public abstract class AbstractTestSortedSet extends AbstractTestSet { } } - public Set makeEmptySet() { - SortedSet s = (SortedSet) AbstractTestSortedSet.this.makeEmptySet(); - return getSubSet(s); + public SortedSet makeObject() { + return getSubSet(AbstractTestSortedSet.this.makeObject()); } - public Set makeFullSet() { - SortedSet s = (SortedSet) AbstractTestSortedSet.this.makeFullCollection(); - return getSubSet(s); + public SortedSet makeFullCollection() { + return getSubSet(AbstractTestSortedSet.this.makeFullCollection()); } public boolean isTestSerialization() { @@ -306,4 +313,19 @@ public abstract class AbstractTestSortedSet extends AbstractTestSet { } + /** + * {@inheritDoc} + */ + @Override + public SortedSet getCollection() { + return (SortedSet) super.getCollection(); + } + + /** + * {@inheritDoc} + */ + @Override + public SortedSet getConfirmed() { + return (SortedSet) super.getConfirmed(); + } } diff --git a/src/test/org/apache/commons/collections/set/TestListOrderedSet2.java b/src/test/org/apache/commons/collections/set/TestListOrderedSet2.java index cb1106d6c..fcee5a932 100644 --- a/src/test/org/apache/commons/collections/set/TestListOrderedSet2.java +++ b/src/test/org/apache/commons/collections/set/TestListOrderedSet2.java @@ -19,7 +19,6 @@ package org.apache.commons.collections.set; import java.util.ArrayList; import java.util.Iterator; import java.util.List; -import java.util.Set; import junit.framework.Test; import junit.framework.TestSuite; @@ -34,7 +33,12 @@ import junit.framework.TestSuite; * @author Henning P. Schmiedehausen * @author Stephen Colebourne */ -public class TestListOrderedSet2 extends AbstractTestSet { +public class TestListOrderedSet2 extends AbstractTestSet { + + private static final Integer ZERO = new Integer(0); + private static final Integer ONE = new Integer(1); + private static final Integer TWO = new Integer(2); + private static final Integer THREE = new Integer(3); public TestListOrderedSet2(String testName) { super(testName); @@ -49,22 +53,24 @@ public class TestListOrderedSet2 extends AbstractTestSet { junit.textui.TestRunner.main(testCaseName); } - public Set makeEmptySet() { - return new ListOrderedSet(); + public ListOrderedSet makeObject() { + return new ListOrderedSet(); } - protected Set setupSet() { - Set set = makeEmptySet(); + @SuppressWarnings("unchecked") + protected ListOrderedSet setupSet() { + ListOrderedSet set = makeObject(); for (int i = 0; i < 10; i++) { - set.add(Integer.toString(i)); + set.add((E) Integer.toString(i)); } return set; } + @SuppressWarnings("unchecked") public void testOrdering() { - Set set = setupSet(); - Iterator it = set.iterator(); + ListOrderedSet set = setupSet(); + Iterator it = set.iterator(); for (int i = 0; i < 10; i++) { assertEquals("Sequence is wrong", Integer.toString(i), it.next()); @@ -80,7 +86,7 @@ public class TestListOrderedSet2 extends AbstractTestSet { } for (int i = 0; i < 10; i++) { - set.add(Integer.toString(i)); + set.add((E) Integer.toString(i)); } assertEquals("Size of set is wrong!", 10, set.size()); @@ -93,19 +99,15 @@ public class TestListOrderedSet2 extends AbstractTestSet { assertEquals("Sequence is wrong", Integer.toString(i), it.next()); } } - - private static final Integer ZERO = new Integer(0); - private static final Integer ONE = new Integer(1); - private static final Integer TWO = new Integer(2); - private static final Integer THREE = new Integer(3); - + + @SuppressWarnings("unchecked") public void testListAddRemove() { - ListOrderedSet set = (ListOrderedSet) makeEmptySet(); - List view = set.asList(); - set.add(ZERO); - set.add(ONE); - set.add(TWO); - + ListOrderedSet set = makeObject(); + List view = set.asList(); + set.add((E) ZERO); + set.add((E) ONE); + set.add((E) TWO); + assertEquals(3, set.size()); assertSame(ZERO, set.get(0)); assertSame(ONE, set.get(1)); @@ -114,11 +116,11 @@ public class TestListOrderedSet2 extends AbstractTestSet { assertSame(ZERO, view.get(0)); assertSame(ONE, view.get(1)); assertSame(TWO, view.get(2)); - + assertEquals(0, set.indexOf(ZERO)); assertEquals(1, set.indexOf(ONE)); assertEquals(2, set.indexOf(TWO)); - + set.remove(1); assertEquals(2, set.size()); assertSame(ZERO, set.get(0)); @@ -126,37 +128,37 @@ public class TestListOrderedSet2 extends AbstractTestSet { assertEquals(2, view.size()); assertSame(ZERO, view.get(0)); assertSame(TWO, view.get(1)); - } - + } + + @SuppressWarnings("unchecked") public void testListAddIndexed() { - ListOrderedSet set = (ListOrderedSet) makeEmptySet(); - List view = set.asList(); - set.add(ZERO); - set.add(TWO); - - set.add(1, ONE); + ListOrderedSet set = makeObject(); + set.add((E) ZERO); + set.add((E) TWO); + + set.add(1, (E) ONE); assertEquals(3, set.size()); assertSame(ZERO, set.get(0)); assertSame(ONE, set.get(1)); assertSame(TWO, set.get(2)); - - set.add(0, ONE); + + set.add(0, (E) ONE); assertEquals(3, set.size()); assertSame(ZERO, set.get(0)); assertSame(ONE, set.get(1)); assertSame(TWO, set.get(2)); - - List list = new ArrayList(); - list.add(ZERO); - list.add(TWO); - + + List list = new ArrayList(); + list.add((E) ZERO); + list.add((E) TWO); + set.addAll(0, list); assertEquals(3, set.size()); assertSame(ZERO, set.get(0)); assertSame(ONE, set.get(1)); assertSame(TWO, set.get(2)); - - list.add(0, THREE); // list = [3,0,2] + + list.add(0, (E) THREE); // list = [3,0,2] set.remove(TWO); // set = [0,1] set.addAll(1, list); assertEquals(4, set.size()); @@ -165,7 +167,7 @@ public class TestListOrderedSet2 extends AbstractTestSet { assertSame(TWO, set.get(2)); assertSame(ONE, set.get(3)); } - + public String getCompatibilityVersion() { return "3.1"; } diff --git a/src/test/org/apache/commons/collections/set/TestMapBackedSet.java b/src/test/org/apache/commons/collections/set/TestMapBackedSet.java index 663557564..91b1890d5 100644 --- a/src/test/org/apache/commons/collections/set/TestMapBackedSet.java +++ b/src/test/org/apache/commons/collections/set/TestMapBackedSet.java @@ -31,7 +31,7 @@ import org.apache.commons.collections.map.HashedMap; * * @author Stephen Colebourne */ -public class TestMapBackedSet extends AbstractTestSet { +public class TestMapBackedSet extends AbstractTestSet { public TestMapBackedSet(String testName) { super(testName); @@ -46,8 +46,8 @@ public class TestMapBackedSet extends AbstractTestSet { junit.textui.TestRunner.main(testCaseName); } - public Set makeEmptySet() { - return MapBackedSet.decorate(new HashedMap()); + public Set makeObject() { + return MapBackedSet.decorate(new HashedMap()); } public String getCompatibilityVersion() { diff --git a/src/test/org/apache/commons/collections/set/TestMapBackedSet2.java b/src/test/org/apache/commons/collections/set/TestMapBackedSet2.java index 75b6227b4..b32f33878 100644 --- a/src/test/org/apache/commons/collections/set/TestMapBackedSet2.java +++ b/src/test/org/apache/commons/collections/set/TestMapBackedSet2.java @@ -32,7 +32,7 @@ import org.apache.commons.collections.map.LinkedMap; * * @author Stephen Colebourne */ -public class TestMapBackedSet2 extends AbstractTestSet { +public class TestMapBackedSet2 extends AbstractTestSet { public TestMapBackedSet2(String testName) { super(testName); @@ -47,22 +47,24 @@ public class TestMapBackedSet2 extends AbstractTestSet { junit.textui.TestRunner.main(testCaseName); } - public Set makeEmptySet() { - return MapBackedSet.decorate(new LinkedMap()); + public Set makeObject() { + return MapBackedSet.decorate(new LinkedMap()); } - protected Set setupSet() { - Set set = makeEmptySet(); + @SuppressWarnings("unchecked") + protected Set setupSet() { + Set set = makeObject(); for (int i = 0; i < 10; i++) { - set.add(Integer.toString(i)); + set.add((E) Integer.toString(i)); } return set; } + @SuppressWarnings("unchecked") public void testOrdering() { - Set set = setupSet(); - Iterator it = set.iterator(); + Set set = setupSet(); + Iterator it = set.iterator(); for (int i = 0; i < 10; i++) { assertEquals("Sequence is wrong", Integer.toString(i), it.next()); @@ -78,7 +80,7 @@ public class TestMapBackedSet2 extends AbstractTestSet { } for (int i = 0; i < 10; i++) { - set.add(Integer.toString(i)); + set.add((E) Integer.toString(i)); } assertEquals("Size of set is wrong!", 10, set.size()); diff --git a/src/test/org/apache/commons/collections/set/TestSynchronizedSet.java b/src/test/org/apache/commons/collections/set/TestSynchronizedSet.java index 43fc52bdf..98dc26bd0 100644 --- a/src/test/org/apache/commons/collections/set/TestSynchronizedSet.java +++ b/src/test/org/apache/commons/collections/set/TestSynchronizedSet.java @@ -24,7 +24,7 @@ import junit.framework.Test; import org.apache.commons.collections.BulkTest; /** - * Extension of {@link AbstractTestSet} for exercising the + * Extension of {@link AbstractTestSet} for exercising the * {@link SynchronizedSet} implementation. * * @since Commons Collections 3.1 @@ -32,24 +32,24 @@ import org.apache.commons.collections.BulkTest; * * @author Stephen Colebourne */ -public class TestSynchronizedSet extends AbstractTestSet{ - +public class TestSynchronizedSet extends AbstractTestSet { + public TestSynchronizedSet(String testName) { super(testName); } - + public static Test suite() { return BulkTest.makeSuite(TestSynchronizedSet.class); } - + public static void main(String args[]) { String[] testCaseName = { TestSynchronizedSet.class.getName()}; junit.textui.TestRunner.main(testCaseName); } - - //------------------------------------------------------------------- - public Set makeEmptySet() { - return SynchronizedSet.decorate(new HashSet()); + + //------------------------------------------------------------------- + public Set makeObject() { + return SynchronizedSet.decorate(new HashSet()); } public String getCompatibilityVersion() { diff --git a/src/test/org/apache/commons/collections/set/TestSynchronizedSortedSet.java b/src/test/org/apache/commons/collections/set/TestSynchronizedSortedSet.java index 94e98784e..282b0dd88 100644 --- a/src/test/org/apache/commons/collections/set/TestSynchronizedSortedSet.java +++ b/src/test/org/apache/commons/collections/set/TestSynchronizedSortedSet.java @@ -16,7 +16,7 @@ */ package org.apache.commons.collections.set; -import java.util.Set; +import java.util.SortedSet; import java.util.TreeSet; import junit.framework.Test; @@ -24,7 +24,7 @@ import junit.framework.Test; import org.apache.commons.collections.BulkTest; /** - * Extension of {@link AbstractTestSet} for exercising the + * Extension of {@link AbstractTestSet} for exercising the * {@link SynchronizedSortedSet} implementation. * * @since Commons Collections 3.1 @@ -32,24 +32,24 @@ import org.apache.commons.collections.BulkTest; * * @author Stephen Colebourne */ -public class TestSynchronizedSortedSet extends AbstractTestSortedSet{ - +public class TestSynchronizedSortedSet extends AbstractTestSortedSet { + public TestSynchronizedSortedSet(String testName) { super(testName); } - + public static Test suite() { return BulkTest.makeSuite(TestSynchronizedSortedSet.class); } - + public static void main(String args[]) { String[] testCaseName = { TestSynchronizedSortedSet.class.getName()}; junit.textui.TestRunner.main(testCaseName); } - - //------------------------------------------------------------------- - public Set makeEmptySet() { - return SynchronizedSortedSet.decorate(new TreeSet()); + + //------------------------------------------------------------------- + public SortedSet makeObject() { + return SynchronizedSortedSet.decorate(new TreeSet()); } public String getCompatibilityVersion() { diff --git a/src/test/org/apache/commons/collections/set/TestTransformedSet.java b/src/test/org/apache/commons/collections/set/TestTransformedSet.java index b7cf05269..6b72f91c6 100644 --- a/src/test/org/apache/commons/collections/set/TestTransformedSet.java +++ b/src/test/org/apache/commons/collections/set/TestTransformedSet.java @@ -17,13 +17,13 @@ package org.apache.commons.collections.set; import java.util.Arrays; -import java.util.Collection; import java.util.HashSet; import java.util.Set; import junit.framework.Test; import junit.framework.TestSuite; +import org.apache.commons.collections.Transformer; import org.apache.commons.collections.collection.TestTransformedCollection; /** @@ -35,8 +35,8 @@ import org.apache.commons.collections.collection.TestTransformedCollection; * * @author Stephen Colebourne */ -public class TestTransformedSet extends AbstractTestSet { - +public class TestTransformedSet extends AbstractTestSet { + public TestTransformedSet(String testName) { super(testName); } @@ -50,40 +50,46 @@ public class TestTransformedSet extends AbstractTestSet { junit.textui.TestRunner.main(testCaseName); } - public Collection makeConfirmedCollection() { - return new HashSet(); + public Set makeConfirmedCollection() { + return new HashSet(); } - public Collection makeConfirmedFullCollection() { - Set set = new HashSet(); + public Set makeConfirmedFullCollection() { + Set set = new HashSet(); set.addAll(Arrays.asList(getFullElements())); return set; } - - public Set makeEmptySet() { - return TransformedSet.decorate(new HashSet(), TestTransformedCollection.NOOP_TRANSFORMER); + + @SuppressWarnings("unchecked") + public Set makeObject() { + return TransformedSet.decorate(new HashSet(), + (Transformer) TestTransformedCollection.NOOP_TRANSFORMER); } - public Set makeFullSet() { - Set list = new HashSet(); + @SuppressWarnings("unchecked") + public Set makeFullCollection() { + Set list = new HashSet(); list.addAll(Arrays.asList(getFullElements())); - return TransformedSet.decorate(list, TestTransformedCollection.NOOP_TRANSFORMER); + return TransformedSet.decorate(list, + (Transformer) TestTransformedCollection.NOOP_TRANSFORMER); } - + + @SuppressWarnings("unchecked") public void testTransformedSet() { - Set set = TransformedSet.decorate(new HashSet(), TestTransformedCollection.STRING_TO_INTEGER_TRANSFORMER); + Set set = TransformedSet.decorate(new HashSet(), + (Transformer) TestTransformedCollection.STRING_TO_INTEGER_TRANSFORMER); assertEquals(0, set.size()); - Object[] els = new Object[] {"1", "3", "5", "7", "2", "4", "6"}; + E[] els = (E[]) new Object[] { "1", "3", "5", "7", "2", "4", "6" }; for (int i = 0; i < els.length; i++) { set.add(els[i]); assertEquals(i + 1, set.size()); assertEquals(true, set.contains(new Integer((String) els[i]))); assertEquals(false, set.contains(els[i])); } - + assertEquals(false, set.remove(els[0])); assertEquals(true, set.remove(new Integer((String) els[0]))); - + } public void testTransformedSet_decorateTransform() { diff --git a/src/test/org/apache/commons/collections/set/TestTransformedSortedSet.java b/src/test/org/apache/commons/collections/set/TestTransformedSortedSet.java index 6699c1423..e650476c5 100644 --- a/src/test/org/apache/commons/collections/set/TestTransformedSortedSet.java +++ b/src/test/org/apache/commons/collections/set/TestTransformedSortedSet.java @@ -24,6 +24,7 @@ import java.util.SortedSet; import junit.framework.Test; import org.apache.commons.collections.BulkTest; +import org.apache.commons.collections.Transformer; import org.apache.commons.collections.collection.TestTransformedCollection; /** @@ -35,8 +36,8 @@ import org.apache.commons.collections.collection.TestTransformedCollection; * * @author Stephen Colebourne */ -public class TestTransformedSortedSet extends AbstractTestSortedSet { - +public class TestTransformedSortedSet extends AbstractTestSortedSet { + public TestTransformedSortedSet(String testName) { super(testName); } @@ -51,30 +52,33 @@ public class TestTransformedSortedSet extends AbstractTestSortedSet { } //----------------------------------------------------------------------- - public Set makeEmptySet() { - return TransformedSortedSet.decorate(new TreeSet(), TestTransformedCollection.NOOP_TRANSFORMER); + @SuppressWarnings("unchecked") + public SortedSet makeObject() { + return TransformedSortedSet.decorate(new TreeSet(), (Transformer) TestTransformedCollection.NOOP_TRANSFORMER); } - public Set makeFullSet() { - SortedSet set = new TreeSet(); + @SuppressWarnings("unchecked") + public SortedSet makeFullCollection() { + SortedSet set = new TreeSet(); set.addAll(Arrays.asList(getFullElements())); - return TransformedSortedSet.decorate(set, TestTransformedCollection.NOOP_TRANSFORMER); + return TransformedSortedSet.decorate(set, (Transformer) TestTransformedCollection.NOOP_TRANSFORMER); } - - //----------------------------------------------------------------------- + + //----------------------------------------------------------------------- + @SuppressWarnings("unchecked") public void testTransformedSet() { - Set set = TransformedSortedSet.decorate(new TreeSet(), TestTransformedCollection.STRING_TO_INTEGER_TRANSFORMER); + SortedSet set = TransformedSortedSet.decorate(new TreeSet(), + (Transformer) TestTransformedCollection.STRING_TO_INTEGER_TRANSFORMER); assertEquals(0, set.size()); - Object[] els = new Object[] {"1", "3", "5", "7", "2", "4", "6"}; + E[] els = (E[]) new Object[] { "1", "3", "5", "7", "2", "4", "6" }; for (int i = 0; i < els.length; i++) { set.add(els[i]); assertEquals(i + 1, set.size()); assertEquals(true, set.contains(new Integer((String) els[i]))); } - + assertEquals(true, set.remove(new Integer((String) els[0]))); - - } + } public void testTransformedSet_decorateTransform() { Set originalSet = new TreeSet(); diff --git a/src/test/org/apache/commons/collections/set/TestUnmodifiableSet.java b/src/test/org/apache/commons/collections/set/TestUnmodifiableSet.java index d92a49929..3ab61855c 100644 --- a/src/test/org/apache/commons/collections/set/TestUnmodifiableSet.java +++ b/src/test/org/apache/commons/collections/set/TestUnmodifiableSet.java @@ -25,7 +25,7 @@ import junit.framework.Test; import org.apache.commons.collections.BulkTest; /** - * Extension of {@link AbstractTestSet} for exercising the + * Extension of {@link AbstractTestSet} for exercising the * {@link UnmodifiableSet} implementation. * * @since Commons Collections 3.0 @@ -33,36 +33,36 @@ import org.apache.commons.collections.BulkTest; * * @author Phil Steitz */ -public class TestUnmodifiableSet extends AbstractTestSet{ - +public class TestUnmodifiableSet extends AbstractTestSet { + public TestUnmodifiableSet(String testName) { super(testName); } - + public static Test suite() { return BulkTest.makeSuite(TestUnmodifiableSet.class); } - + public static void main(String args[]) { String[] testCaseName = { TestUnmodifiableSet.class.getName()}; junit.textui.TestRunner.main(testCaseName); } - - //------------------------------------------------------------------- - public Set makeEmptySet() { - return UnmodifiableSet.decorate(new HashSet()); + + //------------------------------------------------------------------- + public Set makeObject() { + return UnmodifiableSet.decorate(new HashSet()); } - - public Set makeFullSet() { - HashSet set = new HashSet(); + + public Set makeFullCollection() { + HashSet set = new HashSet(); set.addAll(Arrays.asList(getFullElements())); return UnmodifiableSet.decorate(set); } - + public boolean isAddSupported() { return false; } - + public boolean isRemoveSupported() { return false; } diff --git a/src/test/org/apache/commons/collections/set/TestUnmodifiableSortedSet.java b/src/test/org/apache/commons/collections/set/TestUnmodifiableSortedSet.java index c37a287d4..174d4f3a9 100644 --- a/src/test/org/apache/commons/collections/set/TestUnmodifiableSortedSet.java +++ b/src/test/org/apache/commons/collections/set/TestUnmodifiableSortedSet.java @@ -20,6 +20,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.Set; +import java.util.SortedSet; import java.util.TreeSet; import junit.framework.Test; @@ -27,7 +28,7 @@ import junit.framework.Test; import org.apache.commons.collections.BulkTest; /** - * Extension of {@link AbstractTestSortedSet} for exercising the + * Extension of {@link AbstractTestSortedSet} for exercising the * {@link UnmodifiableSortedSet} implementation. * * @since Commons Collections 3.0 @@ -35,73 +36,75 @@ import org.apache.commons.collections.BulkTest; * * @author Phil Steitz */ -public class TestUnmodifiableSortedSet extends AbstractTestSortedSet{ - +public class TestUnmodifiableSortedSet extends AbstractTestSortedSet { + protected UnmodifiableSortedSet set = null; + protected ArrayList array = null; + public TestUnmodifiableSortedSet(String testName) { super(testName); } - + public static Test suite() { return BulkTest.makeSuite(TestUnmodifiableSortedSet.class); } - + public static void main(String args[]) { String[] testCaseName = { TestUnmodifiableSortedSet.class.getName()}; junit.textui.TestRunner.main(testCaseName); } - - //------------------------------------------------------------------- - public Set makeEmptySet() { - return UnmodifiableSortedSet.decorate(new TreeSet()); + + //------------------------------------------------------------------- + public SortedSet makeObject() { + return UnmodifiableSortedSet.decorate(new TreeSet()); } - - public Set makeFullSet() { - TreeSet set = new TreeSet(); + + public UnmodifiableSortedSet makeFullCollection() { + TreeSet set = new TreeSet(); set.addAll(Arrays.asList(getFullElements())); - return UnmodifiableSortedSet.decorate(set); + return (UnmodifiableSortedSet) UnmodifiableSortedSet.decorate(set); } - + public boolean isAddSupported() { return false; } - + public boolean isRemoveSupported() { return false; } - + //-------------------------------------------------------------------- - protected UnmodifiableSortedSet set = null; - protected ArrayList array = null; - + @SuppressWarnings("unchecked") protected void setupSet() { - set = (UnmodifiableSortedSet) makeFullSet(); - array = new ArrayList(); - array.add(new Integer(1)); + set = makeFullCollection(); + array = new ArrayList(); + array.add((E) new Integer(1)); } - - /** + + /** * Verify that base set and subsets are not modifiable */ + @SuppressWarnings("unchecked") public void testUnmodifiable() { setupSet(); verifyUnmodifiable(set); - verifyUnmodifiable(set.headSet(new Integer(1))); - verifyUnmodifiable(set.tailSet(new Integer(1))); - verifyUnmodifiable(set.subSet(new Integer(1), new Integer(3))); + verifyUnmodifiable(set.headSet((E) new Integer(1))); + verifyUnmodifiable(set.tailSet((E) new Integer(1))); + verifyUnmodifiable(set.subSet((E) new Integer(1), (E) new Integer(3))); } - + /** * Verifies that a set is not modifiable */ - public void verifyUnmodifiable(Set set) { + @SuppressWarnings("unchecked") + public void verifyUnmodifiable(Set set) { try { - set.add("value"); + set.add((E) "value"); fail("Expecting UnsupportedOperationException."); } catch (UnsupportedOperationException e) { - // expected + // expected } try { - set.addAll(new TreeSet()); + set.addAll(new TreeSet()); fail("Expecting UnsupportedOperationException."); } catch (UnsupportedOperationException e) { // expected @@ -131,10 +134,10 @@ public class TestUnmodifiableSortedSet extends AbstractTestSortedSet{ // expected } } - + public void testComparator() { setupSet(); - Comparator c = set.comparator(); + Comparator c = set.comparator(); assertTrue("natural order, so comparator should be null", c == null); }