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