001/*
002 * Copyright (C) 2012 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.google.common.collect;
018
019import static com.google.common.collect.CollectPreconditions.checkRemove;
020import static com.google.common.collect.Maps.keyOrNull;
021
022import com.google.common.annotations.Beta;
023import com.google.common.annotations.GwtIncompatible;
024import java.util.Iterator;
025import java.util.NavigableMap;
026import java.util.NavigableSet;
027import java.util.NoSuchElementException;
028import java.util.SortedMap;
029
030/**
031 * A navigable map which forwards all its method calls to another navigable map. Subclasses should
032 * override one or more methods to modify the behavior of the backing map as desired per the <a
033 * href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>.
034 *
035 * <p><b>Warning:</b> The methods of {@code ForwardingNavigableMap} forward <i>indiscriminately</i>
036 * to the methods of the delegate. For example, overriding {@link #put} alone <i>will not</i> change
037 * the behavior of {@link #putAll}, which can lead to unexpected behavior. In this case, you should
038 * override {@code putAll} as well, either providing your own implementation, or delegating to the
039 * provided {@code standardPutAll} method.
040 *
041 * <p><b>{@code default} method warning:</b> This class does <i>not</i> forward calls to {@code
042 * default} methods. Instead, it inherits their default implementations. When those implementations
043 * invoke methods, they invoke methods on the {@code ForwardingNavigableMap}.
044 *
045 * <p>Each of the {@code standard} methods uses the map's comparator (or the natural ordering of the
046 * elements, if there is no comparator) to test element equality. As a result, if the comparator is
047 * not consistent with equals, some of the standard implementations may violate the {@code Map}
048 * contract.
049 *
050 * <p>The {@code standard} methods and the collection views they return are not guaranteed to be
051 * thread-safe, even when all of the methods that they depend on are thread-safe.
052 *
053 * @author Louis Wasserman
054 * @since 12.0
055 */
056@GwtIncompatible
057public abstract class ForwardingNavigableMap<K, V> extends ForwardingSortedMap<K, V>
058    implements NavigableMap<K, V> {
059
060  /** Constructor for use by subclasses. */
061  protected ForwardingNavigableMap() {}
062
063  @Override
064  protected abstract NavigableMap<K, V> delegate();
065
066  @Override
067  public Entry<K, V> lowerEntry(K key) {
068    return delegate().lowerEntry(key);
069  }
070
071  /**
072   * A sensible definition of {@link #lowerEntry} in terms of the {@code lastEntry()} of {@link
073   * #headMap(Object, boolean)}. If you override {@code headMap}, you may wish to override {@code
074   * lowerEntry} to forward to this implementation.
075   */
076  protected Entry<K, V> standardLowerEntry(K key) {
077    return headMap(key, false).lastEntry();
078  }
079
080  @Override
081  public K lowerKey(K key) {
082    return delegate().lowerKey(key);
083  }
084
085  /**
086   * A sensible definition of {@link #lowerKey} in terms of {@code lowerEntry}. If you override
087   * {@link #lowerEntry}, you may wish to override {@code lowerKey} to forward to this
088   * implementation.
089   */
090  protected K standardLowerKey(K key) {
091    return keyOrNull(lowerEntry(key));
092  }
093
094  @Override
095  public Entry<K, V> floorEntry(K key) {
096    return delegate().floorEntry(key);
097  }
098
099  /**
100   * A sensible definition of {@link #floorEntry} in terms of the {@code lastEntry()} of {@link
101   * #headMap(Object, boolean)}. If you override {@code headMap}, you may wish to override {@code
102   * floorEntry} to forward to this implementation.
103   */
104  protected Entry<K, V> standardFloorEntry(K key) {
105    return headMap(key, true).lastEntry();
106  }
107
108  @Override
109  public K floorKey(K key) {
110    return delegate().floorKey(key);
111  }
112
113  /**
114   * A sensible definition of {@link #floorKey} in terms of {@code floorEntry}. If you override
115   * {@code floorEntry}, you may wish to override {@code floorKey} to forward to this
116   * implementation.
117   */
118  protected K standardFloorKey(K key) {
119    return keyOrNull(floorEntry(key));
120  }
121
122  @Override
123  public Entry<K, V> ceilingEntry(K key) {
124    return delegate().ceilingEntry(key);
125  }
126
127  /**
128   * A sensible definition of {@link #ceilingEntry} in terms of the {@code firstEntry()} of {@link
129   * #tailMap(Object, boolean)}. If you override {@code tailMap}, you may wish to override {@code
130   * ceilingEntry} to forward to this implementation.
131   */
132  protected Entry<K, V> standardCeilingEntry(K key) {
133    return tailMap(key, true).firstEntry();
134  }
135
136  @Override
137  public K ceilingKey(K key) {
138    return delegate().ceilingKey(key);
139  }
140
141  /**
142   * A sensible definition of {@link #ceilingKey} in terms of {@code ceilingEntry}. If you override
143   * {@code ceilingEntry}, you may wish to override {@code ceilingKey} to forward to this
144   * implementation.
145   */
146  protected K standardCeilingKey(K key) {
147    return keyOrNull(ceilingEntry(key));
148  }
149
150  @Override
151  public Entry<K, V> higherEntry(K key) {
152    return delegate().higherEntry(key);
153  }
154
155  /**
156   * A sensible definition of {@link #higherEntry} in terms of the {@code firstEntry()} of {@link
157   * #tailMap(Object, boolean)}. If you override {@code tailMap}, you may wish to override {@code
158   * higherEntry} to forward to this implementation.
159   */
160  protected Entry<K, V> standardHigherEntry(K key) {
161    return tailMap(key, false).firstEntry();
162  }
163
164  @Override
165  public K higherKey(K key) {
166    return delegate().higherKey(key);
167  }
168
169  /**
170   * A sensible definition of {@link #higherKey} in terms of {@code higherEntry}. If you override
171   * {@code higherEntry}, you may wish to override {@code higherKey} to forward to this
172   * implementation.
173   */
174  protected K standardHigherKey(K key) {
175    return keyOrNull(higherEntry(key));
176  }
177
178  @Override
179  public Entry<K, V> firstEntry() {
180    return delegate().firstEntry();
181  }
182
183  /**
184   * A sensible definition of {@link #firstEntry} in terms of the {@code iterator()} of {@link
185   * #entrySet}. If you override {@code entrySet}, you may wish to override {@code firstEntry} to
186   * forward to this implementation.
187   */
188  protected Entry<K, V> standardFirstEntry() {
189    return Iterables.getFirst(entrySet(), null);
190  }
191
192  /**
193   * A sensible definition of {@link #firstKey} in terms of {@code firstEntry}. If you override
194   * {@code firstEntry}, you may wish to override {@code firstKey} to forward to this
195   * implementation.
196   */
197  protected K standardFirstKey() {
198    Entry<K, V> entry = firstEntry();
199    if (entry == null) {
200      throw new NoSuchElementException();
201    } else {
202      return entry.getKey();
203    }
204  }
205
206  @Override
207  public Entry<K, V> lastEntry() {
208    return delegate().lastEntry();
209  }
210
211  /**
212   * A sensible definition of {@link #lastEntry} in terms of the {@code iterator()} of the {@link
213   * #entrySet} of {@link #descendingMap}. If you override {@code descendingMap}, you may wish to
214   * override {@code lastEntry} to forward to this implementation.
215   */
216  protected Entry<K, V> standardLastEntry() {
217    return Iterables.getFirst(descendingMap().entrySet(), null);
218  }
219
220  /**
221   * A sensible definition of {@link #lastKey} in terms of {@code lastEntry}. If you override {@code
222   * lastEntry}, you may wish to override {@code lastKey} to forward to this implementation.
223   */
224  protected K standardLastKey() {
225    Entry<K, V> entry = lastEntry();
226    if (entry == null) {
227      throw new NoSuchElementException();
228    } else {
229      return entry.getKey();
230    }
231  }
232
233  @Override
234  public Entry<K, V> pollFirstEntry() {
235    return delegate().pollFirstEntry();
236  }
237
238  /**
239   * A sensible definition of {@link #pollFirstEntry} in terms of the {@code iterator} of {@code
240   * entrySet}. If you override {@code entrySet}, you may wish to override {@code pollFirstEntry} to
241   * forward to this implementation.
242   */
243  protected Entry<K, V> standardPollFirstEntry() {
244    return Iterators.pollNext(entrySet().iterator());
245  }
246
247  @Override
248  public Entry<K, V> pollLastEntry() {
249    return delegate().pollLastEntry();
250  }
251
252  /**
253   * A sensible definition of {@link #pollFirstEntry} in terms of the {@code iterator} of the {@code
254   * entrySet} of {@code descendingMap}. If you override {@code descendingMap}, you may wish to
255   * override {@code pollFirstEntry} to forward to this implementation.
256   */
257  protected Entry<K, V> standardPollLastEntry() {
258    return Iterators.pollNext(descendingMap().entrySet().iterator());
259  }
260
261  @Override
262  public NavigableMap<K, V> descendingMap() {
263    return delegate().descendingMap();
264  }
265
266  /**
267   * A sensible implementation of {@link NavigableMap#descendingMap} in terms of the methods of this
268   * {@code NavigableMap}. In many cases, you may wish to override {@link
269   * ForwardingNavigableMap#descendingMap} to forward to this implementation or a subclass thereof.
270   *
271   * <p>In particular, this map iterates over entries with repeated calls to {@link
272   * NavigableMap#lowerEntry}. If a more efficient means of iteration is available, you may wish to
273   * override the {@code entryIterator()} method of this class.
274   *
275   * @since 12.0
276   */
277  @Beta
278  protected class StandardDescendingMap extends Maps.DescendingMap<K, V> {
279    /** Constructor for use by subclasses. */
280    public StandardDescendingMap() {}
281
282    @Override
283    NavigableMap<K, V> forward() {
284      return ForwardingNavigableMap.this;
285    }
286
287    @Override
288    protected Iterator<Entry<K, V>> entryIterator() {
289      return new Iterator<Entry<K, V>>() {
290        private Entry<K, V> toRemove = null;
291        private Entry<K, V> nextOrNull = forward().lastEntry();
292
293        @Override
294        public boolean hasNext() {
295          return nextOrNull != null;
296        }
297
298        @Override
299        public java.util.Map.Entry<K, V> next() {
300          if (!hasNext()) {
301            throw new NoSuchElementException();
302          }
303          try {
304            return nextOrNull;
305          } finally {
306            toRemove = nextOrNull;
307            nextOrNull = forward().lowerEntry(nextOrNull.getKey());
308          }
309        }
310
311        @Override
312        public void remove() {
313          checkRemove(toRemove != null);
314          forward().remove(toRemove.getKey());
315          toRemove = null;
316        }
317      };
318    }
319  }
320
321  @Override
322  public NavigableSet<K> navigableKeySet() {
323    return delegate().navigableKeySet();
324  }
325
326  /**
327   * A sensible implementation of {@link NavigableMap#navigableKeySet} in terms of the methods of
328   * this {@code NavigableMap}. In many cases, you may wish to override {@link
329   * ForwardingNavigableMap#navigableKeySet} to forward to this implementation or a subclass
330   * thereof.
331   *
332   * @since 12.0
333   */
334  @Beta
335  protected class StandardNavigableKeySet extends Maps.NavigableKeySet<K, V> {
336    /** Constructor for use by subclasses. */
337    public StandardNavigableKeySet() {
338      super(ForwardingNavigableMap.this);
339    }
340  }
341
342  @Override
343  public NavigableSet<K> descendingKeySet() {
344    return delegate().descendingKeySet();
345  }
346
347  /**
348   * A sensible definition of {@link #descendingKeySet} as the {@code navigableKeySet} of {@link
349   * #descendingMap}. (The {@link StandardDescendingMap} implementation implements {@code
350   * navigableKeySet} on its own, so as not to cause an infinite loop.) If you override {@code
351   * descendingMap}, you may wish to override {@code descendingKeySet} to forward to this
352   * implementation.
353   */
354  @Beta
355  protected NavigableSet<K> standardDescendingKeySet() {
356    return descendingMap().navigableKeySet();
357  }
358
359  /**
360   * A sensible definition of {@link #subMap(Object, Object)} in terms of {@link #subMap(Object,
361   * boolean, Object, boolean)}. If you override {@code subMap(K, boolean, K, boolean)}, you may
362   * wish to override {@code subMap} to forward to this implementation.
363   */
364  @Override
365  protected SortedMap<K, V> standardSubMap(K fromKey, K toKey) {
366    return subMap(fromKey, true, toKey, false);
367  }
368
369  @Override
370  public NavigableMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) {
371    return delegate().subMap(fromKey, fromInclusive, toKey, toInclusive);
372  }
373
374  @Override
375  public NavigableMap<K, V> headMap(K toKey, boolean inclusive) {
376    return delegate().headMap(toKey, inclusive);
377  }
378
379  @Override
380  public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) {
381    return delegate().tailMap(fromKey, inclusive);
382  }
383
384  /**
385   * A sensible definition of {@link #headMap(Object)} in terms of {@link #headMap(Object,
386   * boolean)}. If you override {@code headMap(K, boolean)}, you may wish to override {@code
387   * headMap} to forward to this implementation.
388   */
389  protected SortedMap<K, V> standardHeadMap(K toKey) {
390    return headMap(toKey, false);
391  }
392
393  /**
394   * A sensible definition of {@link #tailMap(Object)} in terms of {@link #tailMap(Object,
395   * boolean)}. If you override {@code tailMap(K, boolean)}, you may wish to override {@code
396   * tailMap} to forward to this implementation.
397   */
398  protected SortedMap<K, V> standardTailMap(K fromKey) {
399    return tailMap(fromKey, true);
400  }
401}