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
055 */
056@GwtCompatible
057public abstract class ForwardingSortedSet<E> extends ForwardingSet<E> implements SortedSet<E> {
058
059  /** Constructor for use by subclasses. */
060  protected ForwardingSortedSet() {}
061
062  @Override
063  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
112  @Beta
113  protected boolean standardContains(@Nullable Object object) {
114    try {
115      // any ClassCastExceptions are caught
116      @SuppressWarnings("unchecked")
117      SortedSet<Object> self = (SortedSet<Object>) this;
118      Object ceiling = self.tailSet(object).first();
119      return unsafeCompare(ceiling, object) == 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 iterator()}
131   * method of {@link #tailSet}. If you override {@link #tailSet}, you may wish
132   * to override {@link #remove} to forward to this implementation.
133   *
134   * @since 7.0
135   */
136  @Override
137  @Beta
138  protected boolean standardRemove(@Nullable Object object) {
139    try {
140      // any ClassCastExceptions are caught
141      @SuppressWarnings("unchecked")
142      SortedSet<Object> self = (SortedSet<Object>) this;
143      Iterator<Object> iterator = self.tailSet(object).iterator();
144      if (iterator.hasNext()) {
145        Object ceiling = iterator.next();
146        if (unsafeCompare(ceiling, object) == 0) {
147          iterator.remove();
148          return true;
149        }
150      }
151    } catch (ClassCastException e) {
152      return false;
153    } catch (NullPointerException e) {
154      return false;
155    }
156    return false;
157  }
158
159  /**
160   * A sensible default implementation of {@link #subSet(Object, Object)} in
161   * terms of {@link #headSet(Object)} and {@link #tailSet(Object)}. In some
162   * situations, you may wish to override {@link #subSet(Object, Object)} to
163   * forward to this implementation.
164   *
165   * @since 7.0
166   */
167  @Beta
168  protected SortedSet<E> standardSubSet(E fromElement, E toElement) {
169    return tailSet(fromElement).headSet(toElement);
170  }
171}