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