Make sure that CacheSimple uses equals, not ==
diff --git a/jena-base/src/test/java/org/apache/jena/atlas/lib/cache/CacheSimpleTest.java b/jena-base/src/test/java/org/apache/jena/atlas/lib/cache/CacheSimpleTest.java
index f59274d..03ad44b 100644
--- a/jena-base/src/test/java/org/apache/jena/atlas/lib/cache/CacheSimpleTest.java
+++ b/jena-base/src/test/java/org/apache/jena/atlas/lib/cache/CacheSimpleTest.java
@@ -18,13 +18,13 @@
package org.apache.jena.atlas.lib.cache;
+import org.apache.jena.atlas.lib.Cache;
+import org.junit.Test;
+
import static java.util.stream.Collectors.toMap;
import static java.util.stream.IntStream.rangeClosed;
import static org.junit.Assert.*;
-import org.apache.jena.atlas.lib.Cache;
-import org.junit.Test;
-
/**
* Simple test to ensure that {@link CacheSimple} evidences the fixed-size
* behavior we desire.
@@ -43,17 +43,47 @@
@Test
public void testSameHash() {
- Object key1 = new Object() {
- @Override public int hashCode() { return 1; }
- };
- Object key2 = new Object() {
- @Override public int hashCode() { return 1; }
- };
+ CompoundKey key1 = new CompoundKey(1, 1);
+ CompoundKey key2 = new CompoundKey(1, 2);
assertEquals(key1.hashCode(), key2.hashCode());
assertNotEquals(key1, key2);
- Cache<Object, Integer> cache = new CacheSimple<>(10);
+ Cache<CompoundKey, Integer> cache = new CacheSimple<>(10);
cache.put(key1, 1);
- assertTrue("Same key, expected in cache", cache.containsKey(key1));
+ assertTrue("Same key, expected to be in cache", cache.containsKey(key1));
assertFalse("Keys with same hash code should not be considered equal", cache.containsKey(key2));
}
+
+ @Test
+ public void testKeyEquality() {
+ CompoundKey key1 = new CompoundKey(1, 1);
+ CompoundKey key2 = new CompoundKey(1, 1);
+ assertNotSame(key1, key2);
+ assertEquals(key1, key2);
+ Cache<CompoundKey, Integer> cache = new CacheSimple<>(10);
+ cache.put(key1, 1);
+ assertTrue("Equal key, expected to be found", cache.containsKey(key2));
+ }
+
+ private static final class CompoundKey {
+ private final int a;
+ private final int b;
+
+ private CompoundKey(int a, int b) {
+ this.a = a;
+ this.b = b;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ CompoundKey that = (CompoundKey) o;
+ return a == that.a && b == that.b; // Checks both "a" and "b"
+ }
+
+ @Override
+ public int hashCode() {
+ return a; // Doesn't depend on "b"
+ }
+ }
}