diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 1db10ee3fc..8e3dc2e768 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -52,6 +52,7 @@ Re-validate entries in PredicatedMap/PredicatedCollection readObject (#682). IndexedCollection.remove(Object) removes all values for a non-unique index key. TransformIterator throws NullPointerException when its transformer is null. + IndexedCollection.contains(Object) can return true for objects that were never added. IndexedCollection.add(Object) mutates unique indexed collections before rejecting duplicate keys. MapUtils.invertMap() improves HashMap construction (#652). Validate order and uniqueness invariants in decorator readObject() (#684). 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 976951bdb9..250191c060 100644 --- a/src/main/java/org/apache/commons/collections4/collection/IndexedCollection.java +++ b/src/main/java/org/apache/commons/collections4/collection/IndexedCollection.java @@ -156,7 +156,8 @@ public void clear() { @SuppressWarnings("unchecked") @Override public boolean contains(final Object object) { - return index.containsKey(keyTransformer.apply((C) object)); + final Collection values = (Collection) index.get(keyTransformer.apply((C) object)); + return values != null && values.contains(object); } /** diff --git a/src/test/java/org/apache/commons/collections4/collection/IndexedCollectionTest.java b/src/test/java/org/apache/commons/collections4/collection/IndexedCollectionTest.java index c79810f17a..43d6c98ae4 100644 --- a/src/test/java/org/apache/commons/collections4/collection/IndexedCollectionTest.java +++ b/src/test/java/org/apache/commons/collections4/collection/IndexedCollectionTest.java @@ -18,6 +18,7 @@ import static java.util.Arrays.asList; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -116,6 +117,22 @@ void testAddedObjectsCanBeRetrievedByKey() throws Exception { assertEquals("4", indexed.get(4)); } + @Test + void testContainsUsesObjectEqualityNotOnlyTransformedKey() { + final Collection coll = makeUniqueTestCollection(); + coll.add("01"); + + assertFalse(coll.contains("1")); + } + + @Test + void testContainsUsesObjectEqualityWithNonUniqueIndex() { + final Collection coll = makeTestCollection(); + coll.add("01"); + + assertFalse(coll.contains("1")); + } + @Test void testDecoratedCollectionIsIndexedOnCreation() throws Exception { final Collection original = makeFullCollection();