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.SortedSet;
026    
027    import javax.annotation.Nullable;
028    
029    /**
030     * A sorted set which forwards all its method calls to another sorted set.
031     * Subclasses should override one or more methods to modify the behavior of the
032     * backing sorted set 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 ForwardingSortedSet} forward
036     * <em>indiscriminately</em> to the methods of the delegate. For example,
037     * overriding {@link #add} alone <em>will not</em> change the behavior of {@link
038     * #addAll}, which can lead to unexpected behavior. In this case, you should
039     * override {@code addAll} as well, either providing your own implementation, or
040     * delegating to the provided {@code standardAddAll} method.
041     *
042     * <p>Each of the {@code standard} methods, where appropriate, uses the set's
043     * comparator (or the natural ordering of the elements, if there is no
044     * comparator) to test element equality. As a result, if the comparator is not
045     * consistent with equals, some of the standard implementations may violate the
046     * {@code Set} contract.
047     *
048     * <p>The {@code standard} methods and the collection views they return are not
049     * guaranteed to be thread-safe, even when all of the methods that they depend
050     * on are thread-safe.
051     *
052     * @author Mike Bostock
053     * @author Louis Wasserman
054     * @since 2 (imported from Google Collections Library)
055     */
056    @GwtCompatible
057    public abstract class ForwardingSortedSet<E> extends ForwardingSet<E>
058        implements SortedSet<E> {
059    
060      /** Constructor for use by subclasses. */
061      protected ForwardingSortedSet() {}
062    
063      @Override protected abstract SortedSet<E> delegate();
064    
065      public Comparator<? super E> comparator() {
066        return delegate().comparator();
067      }
068    
069      public E first() {
070        return delegate().first();
071      }
072    
073      public SortedSet<E> headSet(E toElement) {
074        return delegate().headSet(toElement);
075      }
076    
077      public E last() {
078        return delegate().last();
079      }
080    
081      public SortedSet<E> subSet(E fromElement, E toElement) {
082        return delegate().subSet(fromElement, toElement);
083      }
084    
085      public SortedSet<E> tailSet(E fromElement) {
086        return delegate().tailSet(fromElement);
087      }
088    
089      // unsafe, but worst case is a CCE is thrown, which callers will be expecting
090      @SuppressWarnings("unchecked")
091      private int unsafeCompare(Object o1, Object o2) {
092        Comparator<? super E> comparator = comparator();
093        return (comparator == null) ? ((Comparable) o1).compareTo(o2)
094            : ((Comparator) comparator).compare(o1, o2);
095      }
096    
097      /**
098       * A sensible definition of {@link #contains} in terms of the {@code first()}
099       * method of {@link #tailSet}. If you override {@link #tailSet}, you may wish
100       * to override {@link #contains} to forward to this implementation.
101       *
102       * @since 7
103       */
104      @Override @Beta protected boolean standardContains(@Nullable Object object) {
105        try {
106          // any ClassCastExceptions are caught
107          @SuppressWarnings("unchecked")
108          SortedSet<Object> self = (SortedSet) this;
109          Object ceiling = self.tailSet(object).first();
110          return unsafeCompare(ceiling, object) == 0;
111        } catch (ClassCastException e) {
112          return false;
113        } catch (NoSuchElementException e) {
114          return false;
115        } catch (NullPointerException e) {
116          return false;
117        }
118      }
119    
120      /**
121       * A sensible definition of {@link #remove} in terms of the {@code iterator()}
122       * method of {@link #tailSet}. If you override {@link #tailSet}, you may wish
123       * to override {@link #remove} to forward to this implementation.
124       *
125       * @since 7
126       */
127      @Override @Beta protected boolean standardRemove(@Nullable Object object) {
128        try {
129          // any ClassCastExceptions are caught
130          @SuppressWarnings("unchecked")
131          SortedSet<Object> self = (SortedSet) this;
132          Iterator<Object> iterator = self.tailSet(object).iterator();
133          if (iterator.hasNext()) {
134            Object ceiling = iterator.next();
135            if (unsafeCompare(ceiling, object) == 0) {
136              iterator.remove();
137              return true;
138            }
139          }
140        } catch (ClassCastException e) {
141          return false;
142        } catch (NullPointerException e) {
143          return false;
144        }
145        return false;
146      }
147    
148      /**
149       * A sensible default implementation of {@link #subSet(Object, Object)} in
150       * terms of {@link #headSet(Object)} and {@link #tailSet(Object)}. In some
151       * situations, you may wish to override {@link #subSet(Object, Object)} to
152       * forward to this implementation.
153       *
154       * @since 7
155       */
156      @Beta protected SortedSet<E> standardSubSet(E fromElement, E toElement) {
157        return tailSet(fromElement).headSet(toElement);
158      }
159    }