AbstractCollectionCacheKeyGenerator extends AbstractCacheKeyGenerator { public ICacheKeyGenerator combine(ICacheKeyGenerator otherKeyGen) { if (this.equals(otherKeyGen)) { return this; } @SuppressWarnings("unchecked") AbstractCollectionCacheKeyGenerator<T> other = (AbstractCollectionCacheKeyGenerator<T>)otherKeyGen; if (isProvisional() && other.isProvisional()) { throw new IllegalStateException(); } if (isProvisional()) { return other; } else if (other.isProvisional()) { return this; } if (getCollection() == null) { return this; } if (other.getCollection() == null) { return other; } int size = getCollection().size(), otherSize = other.getCollection().size(); if (size > otherSize && getCollection().containsAll(other.getCollection())) { return this; } if (otherSize > size && other.getCollection().containsAll(getCollection())) { return other; } Set<T> combined = new HashSet<T>(); combined.addAll(getCollection()); combined.addAll(other.getCollection()); return newKeyGen(combined, false); }  ICacheKeyGenerator combine(ICacheKeyGenerator otherKeyGen); @Override boolean equals(Object other); @Override int hashCode();  }
@Test public void testCombine() { TestCollectionCacheKeyGenerator gen1 = new TestCollectionCacheKeyGenerator(new HashSet<String>(Arrays.asList("a", "b", "c")), false); Assert.assertSame(gen1, gen1.combine(gen1)); TestCollectionCacheKeyGenerator prov1 = new TestCollectionCacheKeyGenerator(new HashSet<String>(Arrays.asList("p1")), true); TestCollectionCacheKeyGenerator prov2 = new TestCollectionCacheKeyGenerator(new HashSet<String>(Arrays.asList("p2")), true); Assert.assertSame(gen1, gen1.combine(prov1)); Assert.assertSame(gen1, prov1.combine(gen1)); boolean exceptionThrown = false; try { prov1.combine(prov2); } catch (IllegalStateException ex) { exceptionThrown = true; } Assert.assertTrue(exceptionThrown); TestCollectionCacheKeyGenerator gen2 = new TestCollectionCacheKeyGenerator(new HashSet<String>(Arrays.asList("a", "b")), false); Assert.assertSame(gen1, gen1.combine(gen2)); Assert.assertSame(gen1, gen2.combine(gen1)); TestCollectionCacheKeyGenerator gen3 = new TestCollectionCacheKeyGenerator(new HashSet<String>(Arrays.asList("c", "d")), false); ICacheKeyGenerator combined = gen1.combine(gen3); Assert.assertEquals(new HashSet<String>(Arrays.asList("a", "b", "c", "d")), new HashSet<String>(((TestCollectionCacheKeyGenerator)combined).getCollection())); combined = gen3.combine(gen1); Assert.assertEquals(new HashSet<String>(Arrays.asList("a", "b", "c", "d")), new HashSet<String>(((TestCollectionCacheKeyGenerator)combined).getCollection())); TestCollectionCacheKeyGenerator nullCol = new TestCollectionCacheKeyGenerator(null, false); Assert.assertSame(nullCol, gen1.combine(nullCol)); Assert.assertSame(nullCol, nullCol.combine(gen1)); Assert.assertSame(nullCol, nullCol.combine(nullCol)); }