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