001/*
002 * Copyright (C) 2009 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;
020
021import com.google.common.annotations.GwtCompatible;
022import com.google.common.annotations.GwtIncompatible;
023import com.google.common.annotations.J2ktIncompatible;
024import com.google.common.base.MoreObjects;
025import com.google.errorprone.annotations.CanIgnoreReturnValue;
026import com.google.errorprone.annotations.DoNotCall;
027import com.google.errorprone.annotations.DoNotMock;
028import java.io.InvalidObjectException;
029import java.io.ObjectInputStream;
030import java.io.Serializable;
031import java.util.Comparator;
032import java.util.Iterator;
033import java.util.List;
034import java.util.Map;
035import java.util.function.BinaryOperator;
036import java.util.function.Function;
037import java.util.stream.Collector;
038import javax.annotation.CheckForNull;
039import org.checkerframework.checker.nullness.qual.Nullable;
040
041/**
042 * A {@link Table} whose contents will never change, with many other important properties detailed
043 * at {@link ImmutableCollection}.
044 *
045 * <p>See the Guava User Guide article on <a href=
046 * "https://github.com/google/guava/wiki/ImmutableCollectionsExplained">immutable collections</a>.
047 *
048 * @author Gregory Kick
049 * @since 11.0
050 */
051@GwtCompatible
052@ElementTypesAreNonnullByDefault
053public abstract class ImmutableTable<R, C, V> extends AbstractTable<R, C, V>
054    implements Serializable {
055
056  /**
057   * Returns a {@code Collector} that accumulates elements into an {@code ImmutableTable}. Each
058   * input element is mapped to one cell in the returned table, with the rows, columns, and values
059   * generated by applying the specified functions.
060   *
061   * <p>The returned {@code Collector} will throw a {@code NullPointerException} at collection time
062   * if the row, column, or value functions return null on any input.
063   */
064  @SuppressWarnings({"AndroidJdkLibsChecker", "Java7ApiChecker"})
065  @IgnoreJRERequirement // Users will use this only if they're already using streams.
066  static <T extends @Nullable Object, R, C, V>
067      Collector<T, ?, ImmutableTable<R, C, V>> toImmutableTable(
068          Function<? super T, ? extends R> rowFunction,
069          Function<? super T, ? extends C> columnFunction,
070          Function<? super T, ? extends V> valueFunction) {
071    return TableCollectors.toImmutableTable(rowFunction, columnFunction, valueFunction);
072  }
073
074  /**
075   * Returns a {@code Collector} that accumulates elements into an {@code ImmutableTable}. Each
076   * input element is mapped to one cell in the returned table, with the rows, columns, and values
077   * generated by applying the specified functions. If multiple inputs are mapped to the same row
078   * and column pair, they will be combined with the specified merging function in encounter order.
079   *
080   * <p>The returned {@code Collector} will throw a {@code NullPointerException} at collection time
081   * if the row, column, value, or merging functions return null on any input.
082   */
083  @SuppressWarnings({"AndroidJdkLibsChecker", "Java7ApiChecker"})
084  @IgnoreJRERequirement // Users will use this only if they're already using streams.
085  static <T extends @Nullable Object, R, C, V>
086      Collector<T, ?, ImmutableTable<R, C, V>> toImmutableTable(
087          Function<? super T, ? extends R> rowFunction,
088          Function<? super T, ? extends C> columnFunction,
089          Function<? super T, ? extends V> valueFunction,
090          BinaryOperator<V> mergeFunction) {
091    return TableCollectors.toImmutableTable(
092        rowFunction, columnFunction, valueFunction, mergeFunction);
093  }
094
095  /**
096   * Returns an empty immutable table.
097   *
098   * <p><b>Performance note:</b> the instance returned is a singleton.
099   */
100  @SuppressWarnings("unchecked")
101  public static <R, C, V> ImmutableTable<R, C, V> of() {
102    return (ImmutableTable<R, C, V>) SparseImmutableTable.EMPTY;
103  }
104
105  /** Returns an immutable table containing a single cell. */
106  public static <R, C, V> ImmutableTable<R, C, V> of(R rowKey, C columnKey, V value) {
107    return new SingletonImmutableTable<>(rowKey, columnKey, value);
108  }
109
110  /**
111   * Returns an immutable copy of the provided table.
112   *
113   * <p>The {@link Table#cellSet()} iteration order of the provided table determines the iteration
114   * ordering of all views in the returned table. Note that some views of the original table and the
115   * copied table may have different iteration orders. For more control over the ordering, create a
116   * {@link Builder} and call {@link Builder#orderRowsBy}, {@link Builder#orderColumnsBy}, and
117   * {@link Builder#putAll}
118   *
119   * <p>Despite the method name, this method attempts to avoid actually copying the data when it is
120   * safe to do so. The exact circumstances under which a copy will or will not be performed are
121   * undocumented and subject to change.
122   */
123  public static <R, C, V> ImmutableTable<R, C, V> copyOf(
124      Table<? extends R, ? extends C, ? extends V> table) {
125    if (table instanceof ImmutableTable) {
126      @SuppressWarnings("unchecked")
127      ImmutableTable<R, C, V> parameterizedTable = (ImmutableTable<R, C, V>) table;
128      return parameterizedTable;
129    } else {
130      return copyOf(table.cellSet());
131    }
132  }
133
134  static <R, C, V> ImmutableTable<R, C, V> copyOf(
135      Iterable<? extends Cell<? extends R, ? extends C, ? extends V>> cells) {
136    ImmutableTable.Builder<R, C, V> builder = ImmutableTable.builder();
137    for (Cell<? extends R, ? extends C, ? extends V> cell : cells) {
138      builder.put(cell);
139    }
140    return builder.build();
141  }
142
143  /**
144   * Returns a new builder. The generated builder is equivalent to the builder created by the {@link
145   * Builder#Builder() ImmutableTable.Builder()} constructor.
146   */
147  public static <R, C, V> Builder<R, C, V> builder() {
148    return new Builder<>();
149  }
150
151  /**
152   * Verifies that {@code rowKey}, {@code columnKey} and {@code value} are non-null, and returns a
153   * new entry with those values.
154   */
155  static <R, C, V> Cell<R, C, V> cellOf(R rowKey, C columnKey, V value) {
156    return Tables.immutableCell(
157        checkNotNull(rowKey, "rowKey"),
158        checkNotNull(columnKey, "columnKey"),
159        checkNotNull(value, "value"));
160  }
161
162  /**
163   * A builder for creating immutable table instances, especially {@code public static final} tables
164   * ("constant tables"). Example:
165   *
166   * <pre>{@code
167   * static final ImmutableTable<Integer, Character, String> SPREADSHEET =
168   *     new ImmutableTable.Builder<Integer, Character, String>()
169   *         .put(1, 'A', "foo")
170   *         .put(1, 'B', "bar")
171   *         .put(2, 'A', "baz")
172   *         .buildOrThrow();
173   * }</pre>
174   *
175   * <p>By default, the order in which cells are added to the builder determines the iteration
176   * ordering of all views in the returned table, with {@link #putAll} following the {@link
177   * Table#cellSet()} iteration order. However, if {@link #orderRowsBy} or {@link #orderColumnsBy}
178   * is called, the views are sorted by the supplied comparators.
179   *
180   * <p>For empty or single-cell immutable tables, {@link #of()} and {@link #of(Object, Object,
181   * Object)} are even more convenient.
182   *
183   * <p>Builder instances can be reused - it is safe to call {@link #buildOrThrow} multiple times to
184   * build multiple tables in series. Each table is a superset of the tables created before it.
185   *
186   * @since 11.0
187   */
188  @DoNotMock
189  public static final class Builder<R, C, V> {
190    private final List<Cell<R, C, V>> cells = Lists.newArrayList();
191    @CheckForNull private Comparator<? super R> rowComparator;
192    @CheckForNull private Comparator<? super C> columnComparator;
193
194    /**
195     * Creates a new builder. The returned builder is equivalent to the builder generated by {@link
196     * ImmutableTable#builder}.
197     */
198    public Builder() {}
199
200    /** Specifies the ordering of the generated table's rows. */
201    @CanIgnoreReturnValue
202    public Builder<R, C, V> orderRowsBy(Comparator<? super R> rowComparator) {
203      this.rowComparator = checkNotNull(rowComparator, "rowComparator");
204      return this;
205    }
206
207    /** Specifies the ordering of the generated table's columns. */
208    @CanIgnoreReturnValue
209    public Builder<R, C, V> orderColumnsBy(Comparator<? super C> columnComparator) {
210      this.columnComparator = checkNotNull(columnComparator, "columnComparator");
211      return this;
212    }
213
214    /**
215     * Associates the ({@code rowKey}, {@code columnKey}) pair with {@code value} in the built
216     * table. Duplicate key pairs are not allowed and will cause {@link #build} to fail.
217     */
218    @CanIgnoreReturnValue
219    public Builder<R, C, V> put(R rowKey, C columnKey, V value) {
220      cells.add(cellOf(rowKey, columnKey, value));
221      return this;
222    }
223
224    /**
225     * Adds the given {@code cell} to the table, making it immutable if necessary. Duplicate key
226     * pairs are not allowed and will cause {@link #build} to fail.
227     */
228    @CanIgnoreReturnValue
229    public Builder<R, C, V> put(Cell<? extends R, ? extends C, ? extends V> cell) {
230      if (cell instanceof Tables.ImmutableCell) {
231        checkNotNull(cell.getRowKey(), "row");
232        checkNotNull(cell.getColumnKey(), "column");
233        checkNotNull(cell.getValue(), "value");
234        @SuppressWarnings("unchecked") // all supported methods are covariant
235        Cell<R, C, V> immutableCell = (Cell<R, C, V>) cell;
236        cells.add(immutableCell);
237      } else {
238        put(cell.getRowKey(), cell.getColumnKey(), cell.getValue());
239      }
240      return this;
241    }
242
243    /**
244     * Associates all of the given table's keys and values in the built table. Duplicate row key
245     * column key pairs are not allowed, and will cause {@link #build} to fail.
246     *
247     * @throws NullPointerException if any key or value in {@code table} is null
248     */
249    @CanIgnoreReturnValue
250    public Builder<R, C, V> putAll(Table<? extends R, ? extends C, ? extends V> table) {
251      for (Cell<? extends R, ? extends C, ? extends V> cell : table.cellSet()) {
252        put(cell);
253      }
254      return this;
255    }
256
257    @CanIgnoreReturnValue
258    Builder<R, C, V> combine(Builder<R, C, V> other) {
259      this.cells.addAll(other.cells);
260      return this;
261    }
262
263    /**
264     * Returns a newly-created immutable table.
265     *
266     * <p>Prefer the equivalent method {@link #buildOrThrow()} to make it explicit that the method
267     * will throw an exception if there are duplicate key pairs. The {@code build()} method will
268     * soon be deprecated.
269     *
270     * @throws IllegalArgumentException if duplicate key pairs were added
271     */
272    public ImmutableTable<R, C, V> build() {
273      return buildOrThrow();
274    }
275
276    /**
277     * Returns a newly-created immutable table, or throws an exception if duplicate key pairs were
278     * added.
279     *
280     * @throws IllegalArgumentException if duplicate key pairs were added
281     * @since 31.0
282     */
283    public ImmutableTable<R, C, V> buildOrThrow() {
284      int size = cells.size();
285      switch (size) {
286        case 0:
287          return of();
288        case 1:
289          return new SingletonImmutableTable<>(Iterables.getOnlyElement(cells));
290        default:
291          return RegularImmutableTable.forCells(cells, rowComparator, columnComparator);
292      }
293    }
294  }
295
296  ImmutableTable() {}
297
298  @Override
299  public ImmutableSet<Cell<R, C, V>> cellSet() {
300    return (ImmutableSet<Cell<R, C, V>>) super.cellSet();
301  }
302
303  @Override
304  abstract ImmutableSet<Cell<R, C, V>> createCellSet();
305
306  @Override
307  final UnmodifiableIterator<Cell<R, C, V>> cellIterator() {
308    throw new AssertionError("should never be called");
309  }
310
311  @Override
312  public ImmutableCollection<V> values() {
313    return (ImmutableCollection<V>) super.values();
314  }
315
316  @Override
317  abstract ImmutableCollection<V> createValues();
318
319  @Override
320  final Iterator<V> valuesIterator() {
321    throw new AssertionError("should never be called");
322  }
323
324  /**
325   * {@inheritDoc}
326   *
327   * @throws NullPointerException if {@code columnKey} is {@code null}
328   */
329  @Override
330  public ImmutableMap<R, V> column(C columnKey) {
331    checkNotNull(columnKey, "columnKey");
332    return MoreObjects.firstNonNull(
333        (ImmutableMap<R, V>) columnMap().get(columnKey), ImmutableMap.<R, V>of());
334  }
335
336  @Override
337  public ImmutableSet<C> columnKeySet() {
338    return columnMap().keySet();
339  }
340
341  /**
342   * {@inheritDoc}
343   *
344   * <p>The value {@code Map<R, V>} instances in the returned map are {@link ImmutableMap} instances
345   * as well.
346   */
347  @Override
348  public abstract ImmutableMap<C, Map<R, V>> columnMap();
349
350  /**
351   * {@inheritDoc}
352   *
353   * @throws NullPointerException if {@code rowKey} is {@code null}
354   */
355  @Override
356  public ImmutableMap<C, V> row(R rowKey) {
357    checkNotNull(rowKey, "rowKey");
358    return MoreObjects.firstNonNull(
359        (ImmutableMap<C, V>) rowMap().get(rowKey), ImmutableMap.<C, V>of());
360  }
361
362  @Override
363  public ImmutableSet<R> rowKeySet() {
364    return rowMap().keySet();
365  }
366
367  /**
368   * {@inheritDoc}
369   *
370   * <p>The value {@code Map<C, V>} instances in the returned map are {@link ImmutableMap} instances
371   * as well.
372   */
373  @Override
374  public abstract ImmutableMap<R, Map<C, V>> rowMap();
375
376  @Override
377  public boolean contains(@CheckForNull Object rowKey, @CheckForNull Object columnKey) {
378    return get(rowKey, columnKey) != null;
379  }
380
381  @Override
382  public boolean containsValue(@CheckForNull Object value) {
383    return values().contains(value);
384  }
385
386  /**
387   * Guaranteed to throw an exception and leave the table unmodified.
388   *
389   * @throws UnsupportedOperationException always
390   * @deprecated Unsupported operation.
391   */
392  @Deprecated
393  @Override
394  @DoNotCall("Always throws UnsupportedOperationException")
395  public final void clear() {
396    throw new UnsupportedOperationException();
397  }
398
399  /**
400   * Guaranteed to throw an exception and leave the table unmodified.
401   *
402   * @throws UnsupportedOperationException always
403   * @deprecated Unsupported operation.
404   */
405  @CanIgnoreReturnValue
406  @Deprecated
407  @Override
408  @DoNotCall("Always throws UnsupportedOperationException")
409  @CheckForNull
410  public final V put(R rowKey, C columnKey, V value) {
411    throw new UnsupportedOperationException();
412  }
413
414  /**
415   * Guaranteed to throw an exception and leave the table unmodified.
416   *
417   * @throws UnsupportedOperationException always
418   * @deprecated Unsupported operation.
419   */
420  @Deprecated
421  @Override
422  @DoNotCall("Always throws UnsupportedOperationException")
423  public final void putAll(Table<? extends R, ? extends C, ? extends V> table) {
424    throw new UnsupportedOperationException();
425  }
426
427  /**
428   * Guaranteed to throw an exception and leave the table unmodified.
429   *
430   * @throws UnsupportedOperationException always
431   * @deprecated Unsupported operation.
432   */
433  @CanIgnoreReturnValue
434  @Deprecated
435  @Override
436  @DoNotCall("Always throws UnsupportedOperationException")
437  @CheckForNull
438  public final V remove(@CheckForNull Object rowKey, @CheckForNull Object columnKey) {
439    throw new UnsupportedOperationException();
440  }
441
442  /**
443   * Serialized type for all ImmutableTable instances. It captures the logical contents and
444   * preserves iteration order of all views.
445   */
446  static final class SerializedForm implements Serializable {
447    private final Object[] rowKeys;
448    private final Object[] columnKeys;
449
450    private final Object[] cellValues;
451    private final int[] cellRowIndices;
452    private final int[] cellColumnIndices;
453
454    private SerializedForm(
455        Object[] rowKeys,
456        Object[] columnKeys,
457        Object[] cellValues,
458        int[] cellRowIndices,
459        int[] cellColumnIndices) {
460      this.rowKeys = rowKeys;
461      this.columnKeys = columnKeys;
462      this.cellValues = cellValues;
463      this.cellRowIndices = cellRowIndices;
464      this.cellColumnIndices = cellColumnIndices;
465    }
466
467    static SerializedForm create(
468        ImmutableTable<?, ?, ?> table, int[] cellRowIndices, int[] cellColumnIndices) {
469      return new SerializedForm(
470          table.rowKeySet().toArray(),
471          table.columnKeySet().toArray(),
472          table.values().toArray(),
473          cellRowIndices,
474          cellColumnIndices);
475    }
476
477    Object readResolve() {
478      if (cellValues.length == 0) {
479        return of();
480      }
481      if (cellValues.length == 1) {
482        return of(rowKeys[0], columnKeys[0], cellValues[0]);
483      }
484      ImmutableList.Builder<Cell<Object, Object, Object>> cellListBuilder =
485          new ImmutableList.Builder<>(cellValues.length);
486      for (int i = 0; i < cellValues.length; i++) {
487        cellListBuilder.add(
488            cellOf(rowKeys[cellRowIndices[i]], columnKeys[cellColumnIndices[i]], cellValues[i]));
489      }
490      return RegularImmutableTable.forOrderedComponents(
491          cellListBuilder.build(), ImmutableSet.copyOf(rowKeys), ImmutableSet.copyOf(columnKeys));
492    }
493
494    private static final long serialVersionUID = 0;
495  }
496
497  @J2ktIncompatible // serialization
498  @GwtIncompatible // serialization
499  abstract Object writeReplace();
500
501  @GwtIncompatible // serialization
502  @J2ktIncompatible
503  private void readObject(ObjectInputStream stream) throws InvalidObjectException {
504    throw new InvalidObjectException("Use SerializedForm");
505  }
506
507  private static final long serialVersionUID = 0xdecaf;
508}