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>
037 * change the behavior of {@link #putAll}, which can lead to unexpected behavior. In this case, you
038 * should override {@code putAll} as well, either providing your own implementation, or delegating
039 * to the 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
046 * the elements, if there is no comparator) to test element equality. As a result, if the comparator
047 * is 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
073   * {@link #headMap(Object, boolean)}. If you override {@code headMap}, you may wish to override
074   * {@code 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
101   * {@link #headMap(Object, boolean)}. If you override {@code headMap}, you may wish to override
102   * {@code 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
129   * {@link #tailMap(Object, boolean)}. If you override {@code tailMap}, you may wish to override
130   * {@code 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
157   * {@link #tailMap(Object, boolean)}. If you override {@code tailMap}, you may wish to override
158   * {@code 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
185   * {@link #entrySet}. If you override {@code entrySet}, you may wish to override
186   * {@code firstEntry} to 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
213   * {@link #entrySet} of {@link #descendingMap}. If you override {@code descendingMap}, you may
214   * wish to 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
222   * {@code 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
240   * {@code entrySet}. If you override {@code entrySet}, you may wish to override
241   * {@code pollFirstEntry} to 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
254   * {@code entrySet} of {@code descendingMap}. If you override {@code descendingMap}, you may wish
255   * to 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
268   * this {@code NavigableMap}. In many cases, you may wish to override
269   * {@link ForwardingNavigableMap#descendingMap} to forward to this implementation or a subclass
270   * thereof.
271   *
272   * <p>In particular, this map iterates over entries with repeated calls to
273   * {@link NavigableMap#lowerEntry}. If a more efficient means of iteration is available, you may
274   * wish to override the {@code entryIterator()} method of this class.
275   *
276   * @since 12.0
277   */
278  @Beta
279  protected class StandardDescendingMap extends Maps.DescendingMap<K, V> {
280    /** Constructor for use by subclasses. */
281    public StandardDescendingMap() {}
282
283    @Override
284    NavigableMap<K, V> forward() {
285      return ForwardingNavigableMap.this;
286    }
287
288    @Override
289    protected Iterator<Entry<K, V>> entryIterator() {
290      return new Iterator<Entry<K, V>>() {
291        private Entry<K, V> toRemove = null;
292        private Entry<K, V> nextOrNull = forward().lastEntry();
293
294        @Override
295        public boolean hasNext() {
296          return nextOrNull != null;
297        }
298
299        @Override
300        public java.util.Map.Entry<K, V> next() {
301          if (!hasNext()) {
302            throw new NoSuchElementException();
303          }
304          try {
305            return nextOrNull;
306          } finally {
307            toRemove = nextOrNull;
308            nextOrNull = forward().lowerEntry(nextOrNull.getKey());
309          }
310        }
311
312        @Override
313        public void remove() {
314          checkRemove(toRemove != null);
315          forward().remove(toRemove.getKey());
316          toRemove = null;
317        }
318      };
319    }
320  }
321
322  @Override
323  public NavigableSet<K> navigableKeySet() {
324    return delegate().navigableKeySet();
325  }
326
327  /**
328   * A sensible implementation of {@link NavigableMap#navigableKeySet} in terms of the methods of
329   * this {@code NavigableMap}. In many cases, you may wish to override
330   * {@link ForwardingNavigableMap#navigableKeySet} to forward to this implementation or a subclass
331   * thereof.
332   *
333   * @since 12.0
334   */
335  @Beta
336  protected class StandardNavigableKeySet extends Maps.NavigableKeySet<K, V> {
337    /** Constructor for use by subclasses. */
338    public StandardNavigableKeySet() {
339      super(ForwardingNavigableMap.this);
340    }
341  }
342
343  @Override
344  public NavigableSet<K> descendingKeySet() {
345    return delegate().descendingKeySet();
346  }
347
348  /**
349   * A sensible definition of {@link #descendingKeySet} as the {@code navigableKeySet} of
350   * {@link #descendingMap}. (The {@link StandardDescendingMap} implementation implements
351   * {@code navigableKeySet} on its own, so as not to cause an infinite loop.) If you override
352   * {@code descendingMap}, you may wish to override {@code descendingKeySet} to forward to this
353   * implementation.
354   */
355  @Beta
356  protected NavigableSet<K> standardDescendingKeySet() {
357    return descendingMap().navigableKeySet();
358  }
359
360  /**
361   * A sensible definition of {@link #subMap(Object, Object)} in terms of
362   * {@link #subMap(Object, boolean, Object, boolean)}. If you override
363   * {@code subMap(K, boolean, K, boolean)}, you may wish to override {@code subMap} to forward to
364   * this implementation.
365   */
366  @Override
367  protected SortedMap<K, V> standardSubMap(K fromKey, K toKey) {
368    return subMap(fromKey, true, toKey, false);
369  }
370
371  @Override
372  public NavigableMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) {
373    return delegate().subMap(fromKey, fromInclusive, toKey, toInclusive);
374  }
375
376  @Override
377  public NavigableMap<K, V> headMap(K toKey, boolean inclusive) {
378    return delegate().headMap(toKey, inclusive);
379  }
380
381  @Override
382  public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) {
383    return delegate().tailMap(fromKey, inclusive);
384  }
385
386  /**
387   * A sensible definition of {@link #headMap(Object)} in terms of
388   * {@link #headMap(Object, boolean)}. If you override {@code headMap(K, boolean)}, you may wish
389   * to override {@code headMap} to forward to this implementation.
390   */
391  protected SortedMap<K, V> standardHeadMap(K toKey) {
392    return headMap(toKey, false);
393  }
394
395  /**
396   * A sensible definition of {@link #tailMap(Object)} in terms of
397   * {@link #tailMap(Object, boolean)}. If you override {@code tailMap(K, boolean)}, you may wish
398   * to override {@code tailMap} to forward to this implementation.
399   */
400  protected SortedMap<K, V> standardTailMap(K fromKey) {
401    return tailMap(fromKey, true);
402  }
403}