/** * If the delegate collection is empty, but the multimap has values for the key, replace the * delegate with the new collection for the key. * * <p>For a subcollection, refresh its ancestor and validate that the ancestor delegate hasn't * changed. */ void refreshIfEmpty() { if (ancestor != null) { ancestor.refreshIfEmpty(); if (ancestor.getDelegate() != ancestorDelegate) { throw new ConcurrentModificationException(); } } else if (delegate.isEmpty()) { Collection<V> newDelegate = map.get(key); if (newDelegate != null) { delegate = newDelegate; } } }
/** * Add the delegate to the map. Other {@code WrappedCollection} methods should call this method * after adding elements to a previously empty collection. * * <p>Subcollection add the ancestor's delegate instead. */ void addToMap() { if (ancestor != null) { ancestor.addToMap(); } else { map.put(key, delegate); } }
/** * If collection is empty, remove it from {@code map}. For subcollections, check whether the * ancestor collection is empty. */ void removeIfEmpty() { if (ancestor != null) { ancestor.removeIfEmpty(); } else if (delegate.isEmpty()) { map.remove(key); } }
WrappedCollection( @Nullable K key, Collection<V> delegate, @Nullable WrappedCollection ancestor) { this.key = key; this.delegate = delegate; this.ancestor = ancestor; this.ancestorDelegate = (ancestor == null) ? null : ancestor.getDelegate(); }