001/*
002 * Copyright (C) 2007 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.base.Preconditions.checkArgument;
020
021import com.google.common.annotations.Beta;
022import com.google.common.annotations.GwtCompatible;
023import java.util.Comparator;
024import java.util.NoSuchElementException;
025import java.util.SortedMap;
026import javax.annotation.Nullable;
027
028/**
029 * A sorted map which forwards all its method calls to another sorted map.
030 * Subclasses should override one or more methods to modify the behavior of
031 * the backing sorted map as desired per the <a
032 * href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>.
033 *
034 * <p><b>Warning:</b> The methods of {@code ForwardingSortedMap} forward
035 * <i>indiscriminately</i> to the methods of the delegate. For example,
036 * overriding {@link #put} alone <i>will not</i> change the behavior of {@link
037 * #putAll}, which can lead to unexpected behavior. In this case, you should
038 * override {@code putAll} as well, either providing your own implementation, or
039 * delegating 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 ForwardingSortedMap}.
044 *
045 * <p>Each of the {@code standard} methods, where appropriate, use the
046 * comparator of the map to test equality for both keys and values, unlike
047 * {@code ForwardingMap}.
048 *
049 * <p>The {@code standard} methods and the collection views they return are not
050 * guaranteed to be thread-safe, even when all of the methods that they depend
051 * on are thread-safe.
052 *
053 * @author Mike Bostock
054 * @author Louis Wasserman
055 * @since 2.0
056 */
057@GwtCompatible
058public abstract class ForwardingSortedMap<K, V> extends ForwardingMap<K, V>
059    implements SortedMap<K, V> {
060  // TODO(lowasser): identify places where thread safety is actually lost
061
062  /** Constructor for use by subclasses. */
063  protected ForwardingSortedMap() {}
064
065  @Override
066  protected abstract SortedMap<K, V> delegate();
067
068  @Override
069  public Comparator<? super K> comparator() {
070    return delegate().comparator();
071  }
072
073  @Override
074  public K firstKey() {
075    return delegate().firstKey();
076  }
077
078  @Override
079  public SortedMap<K, V> headMap(K toKey) {
080    return delegate().headMap(toKey);
081  }
082
083  @Override
084  public K lastKey() {
085    return delegate().lastKey();
086  }
087
088  @Override
089  public SortedMap<K, V> subMap(K fromKey, K toKey) {
090    return delegate().subMap(fromKey, toKey);
091  }
092
093  @Override
094  public SortedMap<K, V> tailMap(K fromKey) {
095    return delegate().tailMap(fromKey);
096  }
097
098  /**
099   * A sensible implementation of {@link SortedMap#keySet} in terms of the methods of
100   * {@code ForwardingSortedMap}. In many cases, you may wish to override
101   * {@link ForwardingSortedMap#keySet} to forward to this implementation or a subclass thereof.
102   *
103   * @since 15.0
104   */
105  @Beta
106  protected class StandardKeySet extends Maps.SortedKeySet<K, V> {
107    /** Constructor for use by subclasses. */
108    public StandardKeySet() {
109      super(ForwardingSortedMap.this);
110    }
111  }
112
113  // unsafe, but worst case is a CCE is thrown, which callers will be expecting
114  @SuppressWarnings("unchecked")
115  private int unsafeCompare(Object k1, Object k2) {
116    Comparator<? super K> comparator = comparator();
117    if (comparator == null) {
118      return ((Comparable<Object>) k1).compareTo(k2);
119    } else {
120      return ((Comparator<Object>) comparator).compare(k1, k2);
121    }
122  }
123
124  /**
125   * A sensible definition of {@link #containsKey} in terms of the {@code
126   * firstKey()} method of {@link #tailMap}. If you override {@link #tailMap},
127   * you may wish to override {@link #containsKey} to forward to this
128   * implementation.
129   *
130   * @since 7.0
131   */
132  @Override
133  @Beta
134  protected boolean standardContainsKey(@Nullable Object key) {
135    try {
136      // any CCE will be caught
137      @SuppressWarnings("unchecked")
138      SortedMap<Object, V> self = (SortedMap<Object, V>) this;
139      Object ceilingKey = self.tailMap(key).firstKey();
140      return unsafeCompare(ceilingKey, key) == 0;
141    } catch (ClassCastException e) {
142      return false;
143    } catch (NoSuchElementException e) {
144      return false;
145    } catch (NullPointerException e) {
146      return false;
147    }
148  }
149
150  /**
151   * A sensible default implementation of {@link #subMap(Object, Object)} in
152   * terms of {@link #headMap(Object)} and {@link #tailMap(Object)}. In some
153   * situations, you may wish to override {@link #subMap(Object, Object)} to
154   * forward to this implementation.
155   *
156   * @since 7.0
157   */
158  @Beta
159  protected SortedMap<K, V> standardSubMap(K fromKey, K toKey) {
160    checkArgument(unsafeCompare(fromKey, toKey) <= 0, "fromKey must be <= toKey");
161    return tailMap(fromKey).headMap(toKey);
162  }
163}