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