001    /*
002     * Copyright (C) 2007 Google Inc.
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><em>Warning</em>: The methods of {@code ForwardingSortedMap} forward
036     * <em>indiscriminately</em> to the methods of the delegate. For example,
037     * overriding {@link #put} alone <em>will not</em> 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 (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      public Comparator<? super K> comparator() {
065        return delegate().comparator();
066      }
067    
068      public K firstKey() {
069        return delegate().firstKey();
070      }
071    
072      public SortedMap<K, V> headMap(K toKey) {
073        return delegate().headMap(toKey);
074      }
075    
076      public K lastKey() {
077        return delegate().lastKey();
078      }
079    
080      public SortedMap<K, V> subMap(K fromKey, K toKey) {
081        return delegate().subMap(fromKey, toKey);
082      }
083    
084      public SortedMap<K, V> tailMap(K fromKey) {
085        return delegate().tailMap(fromKey);
086      }
087    
088      // unsafe, but worst case is a CCE is thrown, which callers will be expecting
089      @SuppressWarnings("unchecked")
090      private int unsafeCompare(Object k1, Object k2) {
091        Comparator<? super K> comparator = comparator();
092        if (comparator == null) {
093          return ((Comparable) k1).compareTo(k2);
094        } else {
095          return ((Comparator) comparator).compare(k1, k2);
096        }
097      }
098    
099      /**
100       * A sensible definition of {@link #containsKey} in terms of the {@code
101       * firstKey()} method of {@link #tailMap}. If you override {@link #tailMap},
102       * you may wish to override {@link #containsKey} to forward to this
103       * implementation.
104       *
105       * @since 7
106       */
107      @Override @Beta protected boolean standardContainsKey(@Nullable Object key) {
108        try {
109          // any CCE will be caught
110          @SuppressWarnings("unchecked")
111          SortedMap<Object, V> self = (SortedMap) this;
112          Object ceilingKey = self.tailMap(key).firstKey();
113          return unsafeCompare(ceilingKey, key) == 0;
114        } catch (ClassCastException e) {
115          return false;
116        } catch (NoSuchElementException e) {
117          return false;
118        } catch (NullPointerException e) {
119          return false;
120        }
121      }
122    
123      /**
124       * A sensible definition of {@link #remove} in terms of the {@code
125       * iterator()} of the {@code entrySet()} of {@link #tailMap}. If you override
126       * {@link #tailMap}, you may wish to override {@link #remove} to forward
127       * to this implementation.
128       *
129       * @since 7
130       */
131      @Override @Beta protected V standardRemove(@Nullable Object key) {
132        try {
133          // any CCE will be caught
134          @SuppressWarnings("unchecked")
135          SortedMap<Object, V> self = (SortedMap) this;
136          Iterator<Entry<Object, V>> entryIterator =
137              self.tailMap(key).entrySet().iterator();
138          if (entryIterator.hasNext()) {
139            Entry<Object, V> ceilingEntry = entryIterator.next();
140            if (unsafeCompare(ceilingEntry.getKey(), key) == 0) {
141              V value = ceilingEntry.getValue();
142              entryIterator.remove();
143              return value;
144            }
145          }
146        } catch (ClassCastException e) {
147          return null;
148        } catch (NullPointerException e) {
149          return null;
150        }
151        return null;
152      }
153    
154      /**
155       * A sensible default implementation of {@link #subMap(Object, Object)} in
156       * terms of {@link #headMap(Object)} and {@link #tailMap(Object)}. In some
157       * situations, you may wish to override {@link #subMap(Object, Object)} to
158       * forward to this implementation.
159       *
160       * @since 7
161       */
162      @Beta protected SortedMap<K, V> standardSubMap(K fromKey, K toKey) {
163        return tailMap(fromKey).headMap(toKey);
164      }
165    }