ppkarwasz commented on code in PR #628:
URL: 
https://github.com/apache/commons-collections/pull/628#discussion_r2265412468


##########
src/main/java/org/apache/commons/collections4/iterators/IteratorChain.java:
##########
@@ -163,7 +163,29 @@ public IteratorChain(final Iterator<? extends E> first, 
final Iterator<? extends
      */
     public void addIterator(final Iterator<? extends E> iterator) {
         checkLocked();
-        iteratorQueue.add(Objects.requireNonNull(iterator, "iterator"));
+        Objects.requireNonNull(iterator, "iterator");
+        if (iterator instanceof UnmodifiableIterator) {
+            final Iterator<? extends E> underlyingIterator = 
((UnmodifiableIterator) iterator).unwrap();
+            if (underlyingIterator instanceof IteratorChain) {
+                // in case it is an IteratorChain, wrap every underlying 
iterators as unmodifiable
+                // multiple rechainings would otherwise lead to exponential 
growing number of function calls
+                // when the iteratorChain gets used.
+                for (Iterator<? extends E> nestedIterator : ((IteratorChain<? 
extends E>) underlyingIterator).iteratorQueue) {
+                    
iteratorQueue.add(UnmodifiableIterator.unmodifiableIterator(nestedIterator));
+                }
+            } else {
+                // we don't know anything about the underlying iterator, 
simply add it here
+                iteratorQueue.add(iterator);
+            }

Review Comment:
   Your PR matches what I had in mind, but I agree with you that this is 
**not** the right approach to merge as-is.
   
   One way to preserve the idea while still returning an `Unmodifiable` 
implementation from `unmodifiableIterator()` would be to introduce a dedicated 
subclass of `IteratorChain` that:
   
   * **Implements** `Unmodifiable`.
   * **Accepts** all iterators up front via the constructor (no additions 
allowed afterward).
   * **Throws** `UnsupportedOperationException` for `remove()`.
   
   With this design, `IteratorChain` itself doesn’t need to worry about its 
modifiable/unmodifiable state, and there’s no need to wrap nested iterators in 
`unmodifiableIterator()`: the external iterator is guaranteed to be 
unmodifiable from the start.
   
   What do you think of this approach?
   
   If you’d rather go in another direction, I’ve got plenty of other ideas 
(though, as you’ve seen, not all of them are winners :wink:), but not much time 
to test them myself, so I really appreciate you doing the hands-on 
experimenting :100:.
   
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to