You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@commons.apache.org by Christopher Elkins <ch...@scardini.com> on 2002/02/25 08:31:41 UTC
[collections] PATCH: unmodifiableIterator method to CollectionUtils
Hi, all.
The patch attached below adds an unmodifiableIterator method to
CollectionUtils. This is meant to parallel the unmodifiable* methods in
Java 2's util.Collections class.
--
Christopher Elkins
Index: src/java/org/apache/commons/collections/CollectionUtils.java
===================================================================
RCS file: /home/cvspublic/jakarta-commons/collections/src/java/org/apache/commons/collections/CollectionUtils.java,v
retrieving revision 1.7
diff -u -r1.7 CollectionUtils.java
--- src/java/org/apache/commons/collections/CollectionUtils.java 10 Feb 2002 08:07:42 -0000 1.7
+++ src/java/org/apache/commons/collections/CollectionUtils.java 25 Feb 2002 07:28:03 -0000
@@ -106,6 +106,39 @@
}
/**
+ * Returns an unmodifiable view of the specified iterator. Attempts to
+ * modify the returned iterator result in an UnsupportedOperationException.
+ *
+ * @param iterator the iterator for which an unmodifiable view is to be
+ * returned
+ * @return an unmodifiable view of the specified iterator
+ */
+ public static Iterator unmodifiableIterator(Iterator iterator) {
+ return (iterator != null) ? new ImmutableIterator(iterator) :
+ CollectionUtils.EMPTY_ITERATOR;
+ }
+
+ private static class ImmutableIterator implements Iterator {
+ private final Iterator iterator;
+
+ public ImmutableIterator(Iterator iterator) {
+ this.iterator = iterator;
+ }
+
+ public boolean hasNext() {
+ return iterator.hasNext();
+ }
+
+ public Object next() {
+ return iterator.next();
+ }
+
+ public void remove() {
+ throw new UnsupportedOperationException();
+ }
+ }
+
+ /**
* Returns a {@link Collection} containing the union
* of the given {@link Collection}s.
* <p>
Index: src/test/org/apache/commons/collections/TestCollectionUtils.java
===================================================================
RCS file: /home/cvspublic/jakarta-commons/collections/src/test/org/apache/commons/collections/TestCollectionUtils.java,v
retrieving revision 1.2
diff -u -r1.2 TestCollectionUtils.java
--- src/test/org/apache/commons/collections/TestCollectionUtils.java 14 Jul 2001 23:33:27 -0000 1.2
+++ src/test/org/apache/commons/collections/TestCollectionUtils.java 25 Feb 2002 07:28:03 -0000
@@ -310,4 +310,12 @@
assertTrue(CollectionUtils.isEqualCollection(a,b));
assertTrue(CollectionUtils.isEqualCollection(b,a));
}
+
+ public void testUnmodifiableIterator() {
+ Iterator iterator = CollectionUtils.unmodifiableIterator(CollectionUtils.EMPTY_ITERATOR);
+ try {
+ iterator.remove();
+ fail("Should raise an UnsupportedOperationException");
+ } catch (UnsupportedOperationException e) {}
+ }
}
--
To unsubscribe, e-mail: <ma...@jakarta.apache.org>
For additional commands, e-mail: <ma...@jakarta.apache.org>