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