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