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 static com.google.common.base.Preconditions.checkNotNull;
020import static com.google.common.collect.Collections2.containsAllImpl;
021import static com.google.common.collect.Collections2.toStringImpl;
022
023import com.google.common.annotations.GwtCompatible;
024import com.google.errorprone.annotations.CanIgnoreReturnValue;
025import java.util.Collection;
026import java.util.Iterator;
027import java.util.Objects;
028import org.jspecify.annotations.Nullable;
029
030/**
031 * A collection which forwards all its method calls to another collection. Subclasses should
032 * override one or more methods to modify the behavior of the backing collection as desired per the
033 * <a href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>.
034 *
035 * <p><b>Warning:</b> The methods of {@code ForwardingCollection} forward <b>indiscriminately</b> to
036 * the methods of the delegate. For example, overriding {@link #add} alone <b>will not</b> change
037 * the behavior of {@link #addAll}, which can lead to unexpected behavior. In this case, you should
038 * override {@code addAll} as well, either providing your own implementation, or delegating to the
039 * provided {@code standardAddAll} method.
040 *
041 * <p><b>{@code default} method warning:</b> This class does <i>not</i> forward calls to {@code
042 * default} methods. Instead, it inherits their default implementations. When those implementations
043 * invoke methods, they invoke methods on the {@code ForwardingCollection}.
044 *
045 * <p>The {@code standard} methods are not guaranteed to be thread-safe, even when all of the
046 * methods that they depend on are thread-safe.
047 *
048 * @author Kevin Bourrillion
049 * @author Louis Wasserman
050 * @since 2.0
051 */
052@GwtCompatible
053public abstract class ForwardingCollection<E extends @Nullable Object> extends ForwardingObject
054    implements Collection<E> {
055  // TODO(lowasser): identify places where thread safety is actually lost
056
057  /** Constructor for use by subclasses. */
058  protected ForwardingCollection() {}
059
060  @Override
061  protected abstract Collection<E> delegate();
062
063  @Override
064  public Iterator<E> iterator() {
065    return delegate().iterator();
066  }
067
068  @Override
069  public int size() {
070    return delegate().size();
071  }
072
073  @CanIgnoreReturnValue
074  @Override
075  public boolean removeAll(Collection<?> collection) {
076    return delegate().removeAll(collection);
077  }
078
079  @Override
080  public boolean isEmpty() {
081    return delegate().isEmpty();
082  }
083
084  @Override
085  public boolean contains(@Nullable Object object) {
086    return delegate().contains(object);
087  }
088
089  @CanIgnoreReturnValue
090  @Override
091  public boolean add(@ParametricNullness E element) {
092    return delegate().add(element);
093  }
094
095  @CanIgnoreReturnValue
096  @Override
097  public boolean remove(@Nullable Object object) {
098    return delegate().remove(object);
099  }
100
101  @Override
102  public boolean containsAll(Collection<?> collection) {
103    return delegate().containsAll(collection);
104  }
105
106  @CanIgnoreReturnValue
107  @Override
108  public boolean addAll(Collection<? extends E> collection) {
109    return delegate().addAll(collection);
110  }
111
112  @CanIgnoreReturnValue
113  @Override
114  public boolean retainAll(Collection<?> collection) {
115    return delegate().retainAll(collection);
116  }
117
118  @Override
119  public void clear() {
120    delegate().clear();
121  }
122
123  @Override
124  public @Nullable Object[] toArray() {
125    return delegate().toArray();
126  }
127
128  @CanIgnoreReturnValue
129  @Override
130  @SuppressWarnings("nullness") // b/192354773 in our checker affects toArray declarations
131  public <T extends @Nullable Object> T[] toArray(T[] array) {
132    return delegate().toArray(array);
133  }
134
135  /**
136   * A sensible definition of {@link #contains} in terms of {@link #iterator}. If you override
137   * {@link #iterator}, you may wish to override {@link #contains} to forward to this
138   * implementation.
139   *
140   * @since 7.0
141   */
142  protected boolean standardContains(@Nullable Object object) {
143    return Iterators.contains(iterator(), object);
144  }
145
146  /**
147   * A sensible definition of {@link #containsAll} in terms of {@link #contains} . If you override
148   * {@link #contains}, you may wish to override {@link #containsAll} to forward to this
149   * implementation.
150   *
151   * @since 7.0
152   */
153  protected boolean standardContainsAll(Collection<?> collection) {
154    return containsAllImpl(this, collection);
155  }
156
157  /**
158   * A sensible definition of {@link #addAll} in terms of {@link #add}. If you override {@link
159   * #add}, you may wish to override {@link #addAll} to forward to this implementation.
160   *
161   * @since 7.0
162   */
163  protected boolean standardAddAll(Collection<? extends E> collection) {
164    return Iterators.addAll(this, collection.iterator());
165  }
166
167  /**
168   * A sensible definition of {@link #remove} in terms of {@link #iterator}, using the iterator's
169   * {@code remove} method. If you override {@link #iterator}, you may wish to override {@link
170   * #remove} to forward to this implementation.
171   *
172   * @since 7.0
173   */
174  protected boolean standardRemove(@Nullable Object object) {
175    Iterator<E> iterator = iterator();
176    while (iterator.hasNext()) {
177      if (Objects.equals(iterator.next(), object)) {
178        iterator.remove();
179        return true;
180      }
181    }
182    return false;
183  }
184
185  /**
186   * A sensible definition of {@link #removeAll} in terms of {@link #iterator}, using the iterator's
187   * {@code remove} method. If you override {@link #iterator}, you may wish to override {@link
188   * #removeAll} to forward to this implementation.
189   *
190   * @since 7.0
191   */
192  protected boolean standardRemoveAll(Collection<?> collection) {
193    return Iterators.removeAll(iterator(), collection);
194  }
195
196  /**
197   * A sensible definition of {@link #retainAll} in terms of {@link #iterator}, using the iterator's
198   * {@code remove} method. If you override {@link #iterator}, you may wish to override {@link
199   * #retainAll} to forward to this implementation.
200   *
201   * @since 7.0
202   */
203  protected boolean standardRetainAll(Collection<?> collection) {
204    return Iterators.retainAll(iterator(), collection);
205  }
206
207  /**
208   * A sensible definition of {@link #clear} in terms of {@link #iterator}, using the iterator's
209   * {@code remove} method. If you override {@link #iterator}, you may wish to override {@link
210   * #clear} to forward to this implementation.
211   *
212   * @since 7.0
213   */
214  protected void standardClear() {
215    Iterators.clear(iterator());
216  }
217
218  /**
219   * A sensible definition of {@link #isEmpty} as {@code !iterator().hasNext}. If you override
220   * {@link #isEmpty}, you may wish to override {@link #isEmpty} to forward to this implementation.
221   * Alternately, it may be more efficient to implement {@code isEmpty} as {@code size() == 0}.
222   *
223   * @since 7.0
224   */
225  protected boolean standardIsEmpty() {
226    return !iterator().hasNext();
227  }
228
229  /**
230   * A sensible definition of {@link #toString} in terms of {@link #iterator}. If you override
231   * {@link #iterator}, you may wish to override {@link #toString} to forward to this
232   * implementation.
233   *
234   * @since 7.0
235   */
236  protected String standardToString() {
237    return toStringImpl(this);
238  }
239
240  /**
241   * A sensible definition of {@link #toArray()} in terms of {@link #toArray(Object[])}. If you
242   * override {@link #toArray(Object[])}, you may wish to override {@link #toArray} to forward to
243   * this implementation.
244   *
245   * @since 7.0
246   */
247  protected @Nullable Object[] standardToArray() {
248    @Nullable Object[] newArray = new @Nullable Object[size()];
249    return toArray(newArray);
250  }
251
252  /**
253   * A sensible definition of {@link #toArray(Object[])} in terms of {@link #size} and {@link
254   * #iterator}. If you override either of these methods, you may wish to override {@link #toArray}
255   * to forward to this implementation.
256   *
257   * @since 7.0
258   */
259  protected <T extends @Nullable Object> T[] standardToArray(T[] array) {
260    return ObjectArrays.toArrayImpl(this, array);
261  }
262
263  /**
264   * A simplified version of {@link ForwardingCollection} where subclasses can pass in an already
265   * constructed {@link Collection} as the delegate.
266   *
267   * <p>TODO(b/3417232): Consider making this public, but take into consideration whether it would
268   * then appear as a user-visible supertype for any classes.
269   */
270  abstract static class SimpleForwardingCollection<E extends @Nullable Object>
271      extends ForwardingCollection<E> {
272    private final Collection<E> delegate;
273
274    /** Constructor for use by subclasses. */
275    SimpleForwardingCollection(Collection<E> delegate) {
276      this.delegate = checkNotNull(delegate);
277    }
278
279    @Override
280    protected final Collection<E> delegate() {
281      return delegate;
282    }
283  }
284}