This is an automated email from the ASF dual-hosted git repository.

garydgregory pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-collections.git


The following commit(s) were added to refs/heads/master by this push:
     new 3cb647e7e [COLLECTIONS-892] Fix unique IndexedCollection add atomicity 
(#688)
3cb647e7e is described below

commit 3cb647e7eadba3f9d6dcb8a566d52f78134061e9
Author: Gary Gregory <[email protected]>
AuthorDate: Fri Jun 19 17:35:57 2026 +0000

    [COLLECTIONS-892] Fix unique IndexedCollection add atomicity (#688)
    
    Simplify verbose code from PR.
---
 .../collections4/collection/IndexedCollection.java | 28 +++++++++-------------
 1 file changed, 11 insertions(+), 17 deletions(-)

diff --git 
a/src/main/java/org/apache/commons/collections4/collection/IndexedCollection.java
 
b/src/main/java/org/apache/commons/collections4/collection/IndexedCollection.java
index 71d4b5ed3..976951bdb 100644
--- 
a/src/main/java/org/apache/commons/collections4/collection/IndexedCollection.java
+++ 
b/src/main/java/org/apache/commons/collections4/collection/IndexedCollection.java
@@ -113,20 +113,10 @@ public class IndexedCollection<K, C> extends 
AbstractCollectionDecorator<C> {
      */
     @Override
     public boolean add(final C object) {
-        if (uniqueIndex) {
-            final K key = keyTransformer.apply(object);
-            if (index.containsKey(key)) {
-                throw new IllegalArgumentException("Duplicate key in uniquely 
indexed collection.");
-            }
-            final boolean added = super.add(object);
-            if (added) {
-                index.put(key, object);
-            }
-            return added;
-        }
+        final K key = toValidKey(object);
         final boolean added = super.add(object);
         if (added) {
-            addToIndex(object);
+            index.put(key, object);
         }
         return added;
     }
@@ -148,11 +138,7 @@ public class IndexedCollection<K, C> extends 
AbstractCollectionDecorator<C> {
      *   enforces a uniqueness constraint.
      */
     private void addToIndex(final C object) {
-        final K key = keyTransformer.apply(object);
-        if (uniqueIndex && index.containsKey(key)) {
-            throw new IllegalArgumentException("Duplicate key in uniquely 
indexed collection.");
-        }
-        index.put(key, object);
+        index.put(toValidKey(object), object);
     }
 
     @Override
@@ -269,6 +255,14 @@ public class IndexedCollection<K, C> extends 
AbstractCollectionDecorator<C> {
         return changed;
     }
 
+    private K toValidKey(final C object) {
+        final K key = keyTransformer.apply(object);
+        if (uniqueIndex && index.containsKey(key)) {
+            throw new IllegalArgumentException("Duplicate key in uniquely 
indexed collection.");
+        }
+        return key;
+    }
+
     /**
      * Gets all elements associated with the given key.
      *

Reply via email to