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 com.google.common.annotations.Beta;
020import com.google.common.annotations.GwtCompatible;
021
022import java.util.Comparator;
023import java.util.Iterator;
024import java.util.NoSuchElementException;
025import java.util.SortedSet;
026
027import 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><i>Warning:</i> The methods of {@code ForwardingSortedSet} forward
036 * <i>indiscriminately</i> to the methods of the delegate. For example,
037 * overriding {@link #add} alone <i>will not</i> 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.0 (imported from Google Collections Library)
055 */
056@GwtCompatible
057public 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  @Override
066  public Comparator<? super E> comparator() {
067    return delegate().comparator();
068  }
069
070  @Override
071  public E first() {
072    return delegate().first();
073  }
074
075  @Override
076  public SortedSet<E> headSet(E toElement) {
077    return delegate().headSet(toElement);
078  }
079
080  @Override
081  public E last() {
082    return delegate().last();
083  }
084
085  @Override
086  public SortedSet<E> subSet(E fromElement, E toElement) {
087    return delegate().subSet(fromElement, toElement);
088  }
089
090  @Override
091  public SortedSet<E> tailSet(E fromElement) {
092    return delegate().tailSet(fromElement);
093  }
094
095  // unsafe, but worst case is a CCE is thrown, which callers will be expecting
096  @SuppressWarnings("unchecked")
097  private int unsafeCompare(Object o1, Object o2) {
098    Comparator<? super E> comparator = comparator();
099    return (comparator == null)
100        ? ((Comparable<Object>) o1).compareTo(o2)
101        : ((Comparator<Object>) comparator).compare(o1, o2);
102  }
103
104  /**
105   * A sensible definition of {@link #contains} in terms of the {@code first()}
106   * method of {@link #tailSet}. If you override {@link #tailSet}, you may wish
107   * to override {@link #contains} to forward to this implementation.
108   *
109   * @since 7.0
110   */
111  @Override @Beta protected boolean standardContains(@Nullable Object object) {
112    try {
113      // any ClassCastExceptions are caught
114      @SuppressWarnings("unchecked")
115      SortedSet<Object> self = (SortedSet<Object>) this;
116      Object ceiling = self.tailSet(object).first();
117      return unsafeCompare(ceiling, object) == 0;
118    } catch (ClassCastException e) {
119      return false;
120    } catch (NoSuchElementException e) {
121      return false;
122    } catch (NullPointerException e) {
123      return false;
124    }
125  }
126
127  /**
128   * A sensible definition of {@link #remove} in terms of the {@code iterator()}
129   * method of {@link #tailSet}. If you override {@link #tailSet}, you may wish
130   * to override {@link #remove} to forward to this implementation.
131   *
132   * @since 7.0
133   */
134  @Override @Beta protected boolean standardRemove(@Nullable Object object) {
135    try {
136      // any ClassCastExceptions are caught
137      @SuppressWarnings("unchecked")
138      SortedSet<Object> self = (SortedSet<Object>) this;
139      Iterator<Object> iterator = self.tailSet(object).iterator();
140      if (iterator.hasNext()) {
141        Object ceiling = iterator.next();
142        if (unsafeCompare(ceiling, object) == 0) {
143          iterator.remove();
144          return true;
145        }
146      }
147    } catch (ClassCastException e) {
148      return false;
149    } catch (NullPointerException e) {
150      return false;
151    }
152    return false;
153  }
154
155  /**
156   * A sensible default implementation of {@link #subSet(Object, Object)} in
157   * terms of {@link #headSet(Object)} and {@link #tailSet(Object)}. In some
158   * situations, you may wish to override {@link #subSet(Object, Object)} to
159   * forward to this implementation.
160   *
161   * @since 7.0
162   */
163  @Beta protected SortedSet<E> standardSubSet(E fromElement, E toElement) {
164    return tailSet(fromElement).headSet(toElement);
165  }
166}