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