001/*
002 * Copyright (C) 2008 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.checkArgument;
020import static com.google.common.base.Preconditions.checkNotNull;
021import static com.google.common.collect.NullnessCasts.uncheckedCastNullableTToT;
022
023import com.google.common.annotations.GwtCompatible;
024import com.google.common.annotations.J2ktIncompatible;
025import com.google.common.base.Function;
026import com.google.common.base.Objects;
027import com.google.common.base.Supplier;
028import com.google.common.collect.Table.Cell;
029import java.io.Serializable;
030import java.util.Collection;
031import java.util.Collections;
032import java.util.Iterator;
033import java.util.Map;
034import java.util.Set;
035import java.util.SortedMap;
036import java.util.SortedSet;
037import java.util.Spliterator;
038import java.util.function.BinaryOperator;
039import java.util.stream.Collector;
040import javax.annotation.CheckForNull;
041import org.checkerframework.checker.nullness.qual.Nullable;
042
043/**
044 * Provides static methods that involve a {@code Table}.
045 *
046 * <p>See the Guava User Guide article on <a href=
047 * "https://github.com/google/guava/wiki/CollectionUtilitiesExplained#tables">{@code Tables}</a>.
048 *
049 * @author Jared Levy
050 * @author Louis Wasserman
051 * @since 7.0
052 */
053@GwtCompatible
054@ElementTypesAreNonnullByDefault
055public final class Tables {
056  private Tables() {}
057
058  /**
059   * Returns a {@link Collector} that accumulates elements into a {@code Table} created using the
060   * specified supplier, whose cells are generated by applying the provided mapping functions to the
061   * input elements. Cells are inserted into the generated {@code Table} in encounter order.
062   *
063   * <p>If multiple input elements map to the same row and column, an {@code IllegalStateException}
064   * is thrown when the collection operation is performed.
065   *
066   * <p>To collect to an {@link ImmutableTable}, use {@link ImmutableTable#toImmutableTable}.
067   *
068   * @since 21.0
069   */
070  public static <
071          T extends @Nullable Object,
072          R extends @Nullable Object,
073          C extends @Nullable Object,
074          V,
075          I extends Table<R, C, V>>
076      Collector<T, ?, I> toTable(
077          java.util.function.Function<? super T, ? extends R> rowFunction,
078          java.util.function.Function<? super T, ? extends C> columnFunction,
079          java.util.function.Function<? super T, ? extends V> valueFunction,
080          java.util.function.Supplier<I> tableSupplier) {
081    return TableCollectors.<T, R, C, V, I>toTable(
082        rowFunction, columnFunction, valueFunction, tableSupplier);
083  }
084
085  /**
086   * Returns a {@link Collector} that accumulates elements into a {@code Table} created using the
087   * specified supplier, whose cells are generated by applying the provided mapping functions to the
088   * input elements. Cells are inserted into the generated {@code Table} in encounter order.
089   *
090   * <p>If multiple input elements map to the same row and column, the specified merging function is
091   * used to combine the values. Like {@link
092   * java.util.stream.Collectors#toMap(java.util.function.Function, java.util.function.Function,
093   * BinaryOperator, java.util.function.Supplier)}, this Collector throws a {@code
094   * NullPointerException} on null values returned from {@code valueFunction}, and treats nulls
095   * returned from {@code mergeFunction} as removals of that row/column pair.
096   *
097   * @since 21.0
098   */
099  public static <
100          T extends @Nullable Object,
101          R extends @Nullable Object,
102          C extends @Nullable Object,
103          V,
104          I extends Table<R, C, V>>
105      Collector<T, ?, I> toTable(
106          java.util.function.Function<? super T, ? extends R> rowFunction,
107          java.util.function.Function<? super T, ? extends C> columnFunction,
108          java.util.function.Function<? super T, ? extends V> valueFunction,
109          BinaryOperator<V> mergeFunction,
110          java.util.function.Supplier<I> tableSupplier) {
111    return TableCollectors.<T, R, C, V, I>toTable(
112        rowFunction, columnFunction, valueFunction, mergeFunction, tableSupplier);
113  }
114
115  /**
116   * Returns an immutable cell with the specified row key, column key, and value.
117   *
118   * <p>The returned cell is serializable.
119   *
120   * @param rowKey the row key to be associated with the returned cell
121   * @param columnKey the column key to be associated with the returned cell
122   * @param value the value to be associated with the returned cell
123   */
124  public static <R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object>
125      Cell<R, C, V> immutableCell(
126          @ParametricNullness R rowKey,
127          @ParametricNullness C columnKey,
128          @ParametricNullness V value) {
129    return new ImmutableCell<>(rowKey, columnKey, value);
130  }
131
132  static final class ImmutableCell<
133          R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object>
134      extends AbstractCell<R, C, V> implements Serializable {
135    @ParametricNullness private final R rowKey;
136    @ParametricNullness private final C columnKey;
137    @ParametricNullness private final V value;
138
139    ImmutableCell(
140        @ParametricNullness R rowKey,
141        @ParametricNullness C columnKey,
142        @ParametricNullness V value) {
143      this.rowKey = rowKey;
144      this.columnKey = columnKey;
145      this.value = value;
146    }
147
148    @Override
149    @ParametricNullness
150    public R getRowKey() {
151      return rowKey;
152    }
153
154    @Override
155    @ParametricNullness
156    public C getColumnKey() {
157      return columnKey;
158    }
159
160    @Override
161    @ParametricNullness
162    public V getValue() {
163      return value;
164    }
165
166    private static final long serialVersionUID = 0;
167  }
168
169  abstract static class AbstractCell<
170          R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object>
171      implements Cell<R, C, V> {
172    // needed for serialization
173    AbstractCell() {}
174
175    @Override
176    public boolean equals(@CheckForNull Object obj) {
177      if (obj == this) {
178        return true;
179      }
180      if (obj instanceof Cell) {
181        Cell<?, ?, ?> other = (Cell<?, ?, ?>) obj;
182        return Objects.equal(getRowKey(), other.getRowKey())
183            && Objects.equal(getColumnKey(), other.getColumnKey())
184            && Objects.equal(getValue(), other.getValue());
185      }
186      return false;
187    }
188
189    @Override
190    public int hashCode() {
191      return Objects.hashCode(getRowKey(), getColumnKey(), getValue());
192    }
193
194    @Override
195    public String toString() {
196      return "(" + getRowKey() + "," + getColumnKey() + ")=" + getValue();
197    }
198  }
199
200  /**
201   * Creates a transposed view of a given table that flips its row and column keys. In other words,
202   * calling {@code get(columnKey, rowKey)} on the generated table always returns the same value as
203   * calling {@code get(rowKey, columnKey)} on the original table. Updating the original table
204   * changes the contents of the transposed table and vice versa.
205   *
206   * <p>The returned table supports update operations as long as the input table supports the
207   * analogous operation with swapped rows and columns. For example, in a {@link HashBasedTable}
208   * instance, {@code rowKeySet().iterator()} supports {@code remove()} but {@code
209   * columnKeySet().iterator()} doesn't. With a transposed {@link HashBasedTable}, it's the other
210   * way around.
211   */
212  public static <R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object>
213      Table<C, R, V> transpose(Table<R, C, V> table) {
214    return (table instanceof TransposeTable)
215        ? ((TransposeTable<R, C, V>) table).original
216        : new TransposeTable<C, R, V>(table);
217  }
218
219  private static class TransposeTable<
220          C extends @Nullable Object, R extends @Nullable Object, V extends @Nullable Object>
221      extends AbstractTable<C, R, V> {
222    final Table<R, C, V> original;
223
224    TransposeTable(Table<R, C, V> original) {
225      this.original = checkNotNull(original);
226    }
227
228    @Override
229    public void clear() {
230      original.clear();
231    }
232
233    @Override
234    public Map<C, V> column(@ParametricNullness R columnKey) {
235      return original.row(columnKey);
236    }
237
238    @Override
239    public Set<R> columnKeySet() {
240      return original.rowKeySet();
241    }
242
243    @Override
244    public Map<R, Map<C, V>> columnMap() {
245      return original.rowMap();
246    }
247
248    @Override
249    public boolean contains(@CheckForNull Object rowKey, @CheckForNull Object columnKey) {
250      return original.contains(columnKey, rowKey);
251    }
252
253    @Override
254    public boolean containsColumn(@CheckForNull Object columnKey) {
255      return original.containsRow(columnKey);
256    }
257
258    @Override
259    public boolean containsRow(@CheckForNull Object rowKey) {
260      return original.containsColumn(rowKey);
261    }
262
263    @Override
264    public boolean containsValue(@CheckForNull Object value) {
265      return original.containsValue(value);
266    }
267
268    @Override
269    @CheckForNull
270    public V get(@CheckForNull Object rowKey, @CheckForNull Object columnKey) {
271      return original.get(columnKey, rowKey);
272    }
273
274    @Override
275    @CheckForNull
276    public V put(
277        @ParametricNullness C rowKey,
278        @ParametricNullness R columnKey,
279        @ParametricNullness V value) {
280      return original.put(columnKey, rowKey, value);
281    }
282
283    @Override
284    public void putAll(Table<? extends C, ? extends R, ? extends V> table) {
285      original.putAll(transpose(table));
286    }
287
288    @Override
289    @CheckForNull
290    public V remove(@CheckForNull Object rowKey, @CheckForNull Object columnKey) {
291      return original.remove(columnKey, rowKey);
292    }
293
294    @Override
295    public Map<R, V> row(@ParametricNullness C rowKey) {
296      return original.column(rowKey);
297    }
298
299    @Override
300    public Set<C> rowKeySet() {
301      return original.columnKeySet();
302    }
303
304    @Override
305    public Map<C, Map<R, V>> rowMap() {
306      return original.columnMap();
307    }
308
309    @Override
310    public int size() {
311      return original.size();
312    }
313
314    @Override
315    public Collection<V> values() {
316      return original.values();
317    }
318
319    @Override
320    Iterator<Cell<C, R, V>> cellIterator() {
321      return Iterators.transform(original.cellSet().iterator(), Tables::transposeCell);
322    }
323
324    @Override
325    Spliterator<Cell<C, R, V>> cellSpliterator() {
326      return CollectSpliterators.map(original.cellSet().spliterator(), Tables::transposeCell);
327    }
328  }
329
330  private static <
331          R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object>
332      Cell<C, R, V> transposeCell(Cell<R, C, V> cell) {
333    return immutableCell(cell.getColumnKey(), cell.getRowKey(), cell.getValue());
334  }
335
336  /**
337   * Creates a table that uses the specified backing map and factory. It can generate a table based
338   * on arbitrary {@link Map} classes.
339   *
340   * <p>The {@code factory}-generated and {@code backingMap} classes determine the table iteration
341   * order. However, the table's {@code row()} method returns instances of a different class than
342   * {@code factory.get()} does.
343   *
344   * <p>Call this method only when the simpler factory methods in classes like {@link
345   * HashBasedTable} and {@link TreeBasedTable} won't suffice.
346   *
347   * <p>The views returned by the {@code Table} methods {@link Table#column}, {@link
348   * Table#columnKeySet}, and {@link Table#columnMap} have iterators that don't support {@code
349   * remove()}. Otherwise, all optional operations are supported. Null row keys, columns keys, and
350   * values are not supported.
351   *
352   * <p>Lookups by row key are often faster than lookups by column key, because the data is stored
353   * in a {@code Map<R, Map<C, V>>}. A method call like {@code column(columnKey).get(rowKey)} still
354   * runs quickly, since the row key is provided. However, {@code column(columnKey).size()} takes
355   * longer, since an iteration across all row keys occurs.
356   *
357   * <p>Note that this implementation is not synchronized. If multiple threads access this table
358   * concurrently and one of the threads modifies the table, it must be synchronized externally.
359   *
360   * <p>The table is serializable if {@code backingMap}, {@code factory}, the maps generated by
361   * {@code factory}, and the table contents are all serializable.
362   *
363   * <p>Note: the table assumes complete ownership over of {@code backingMap} and the maps returned
364   * by {@code factory}. Those objects should not be manually updated and they should not use soft,
365   * weak, or phantom references.
366   *
367   * @param backingMap place to store the mapping from each row key to its corresponding column key
368   *     / value map
369   * @param factory supplier of new, empty maps that will each hold all column key / value mappings
370   *     for a given row key
371   * @throws IllegalArgumentException if {@code backingMap} is not empty
372   * @since 10.0
373   */
374  public static <R, C, V> Table<R, C, V> newCustomTable(
375      Map<R, Map<C, V>> backingMap, Supplier<? extends Map<C, V>> factory) {
376    checkArgument(backingMap.isEmpty());
377    checkNotNull(factory);
378    // TODO(jlevy): Wrap factory to validate that the supplied maps are empty?
379    return new StandardTable<>(backingMap, factory);
380  }
381
382  /**
383   * Returns a view of a table where each value is transformed by a function. All other properties
384   * of the table, such as iteration order, are left intact.
385   *
386   * <p>Changes in the underlying table are reflected in this view. Conversely, this view supports
387   * removal operations, and these are reflected in the underlying table.
388   *
389   * <p>It's acceptable for the underlying table to contain null keys, and even null values provided
390   * that the function is capable of accepting null input. The transformed table might contain null
391   * values, if the function sometimes gives a null result.
392   *
393   * <p>The returned table is not thread-safe or serializable, even if the underlying table is.
394   *
395   * <p>The function is applied lazily, invoked when needed. This is necessary for the returned
396   * table to be a view, but it means that the function will be applied many times for bulk
397   * operations like {@link Table#containsValue} and {@code Table.toString()}. For this to perform
398   * well, {@code function} should be fast. To avoid lazy evaluation when the returned table doesn't
399   * need to be a view, copy the returned table into a new table of your choosing.
400   *
401   * @since 10.0
402   */
403  public static <
404          R extends @Nullable Object,
405          C extends @Nullable Object,
406          V1 extends @Nullable Object,
407          V2 extends @Nullable Object>
408      Table<R, C, V2> transformValues(
409          Table<R, C, V1> fromTable, Function<? super V1, V2> function) {
410    return new TransformedTable<>(fromTable, function);
411  }
412
413  private static class TransformedTable<
414          R extends @Nullable Object,
415          C extends @Nullable Object,
416          V1 extends @Nullable Object,
417          V2 extends @Nullable Object>
418      extends AbstractTable<R, C, V2> {
419    final Table<R, C, V1> fromTable;
420    final Function<? super V1, V2> function;
421
422    TransformedTable(Table<R, C, V1> fromTable, Function<? super V1, V2> function) {
423      this.fromTable = checkNotNull(fromTable);
424      this.function = checkNotNull(function);
425    }
426
427    @Override
428    public boolean contains(@CheckForNull Object rowKey, @CheckForNull Object columnKey) {
429      return fromTable.contains(rowKey, columnKey);
430    }
431
432    @Override
433    @CheckForNull
434    public V2 get(@CheckForNull Object rowKey, @CheckForNull Object columnKey) {
435      // The function is passed a null input only when the table contains a null
436      // value.
437      // The cast is safe because of the contains() check.
438      return contains(rowKey, columnKey)
439          ? function.apply(uncheckedCastNullableTToT(fromTable.get(rowKey, columnKey)))
440          : null;
441    }
442
443    @Override
444    public int size() {
445      return fromTable.size();
446    }
447
448    @Override
449    public void clear() {
450      fromTable.clear();
451    }
452
453    @Override
454    @CheckForNull
455    public V2 put(
456        @ParametricNullness R rowKey,
457        @ParametricNullness C columnKey,
458        @ParametricNullness V2 value) {
459      throw new UnsupportedOperationException();
460    }
461
462    @Override
463    public void putAll(Table<? extends R, ? extends C, ? extends V2> table) {
464      throw new UnsupportedOperationException();
465    }
466
467    @Override
468    @CheckForNull
469    public V2 remove(@CheckForNull Object rowKey, @CheckForNull Object columnKey) {
470      return contains(rowKey, columnKey)
471          // The cast is safe because of the contains() check.
472          ? function.apply(uncheckedCastNullableTToT(fromTable.remove(rowKey, columnKey)))
473          : null;
474    }
475
476    @Override
477    public Map<C, V2> row(@ParametricNullness R rowKey) {
478      return Maps.transformValues(fromTable.row(rowKey), function);
479    }
480
481    @Override
482    public Map<R, V2> column(@ParametricNullness C columnKey) {
483      return Maps.transformValues(fromTable.column(columnKey), function);
484    }
485
486    Function<Cell<R, C, V1>, Cell<R, C, V2>> cellFunction() {
487      return new Function<Cell<R, C, V1>, Cell<R, C, V2>>() {
488        @Override
489        public Cell<R, C, V2> apply(Cell<R, C, V1> cell) {
490          return immutableCell(
491              cell.getRowKey(), cell.getColumnKey(), function.apply(cell.getValue()));
492        }
493      };
494    }
495
496    @Override
497    Iterator<Cell<R, C, V2>> cellIterator() {
498      return Iterators.transform(fromTable.cellSet().iterator(), cellFunction());
499    }
500
501    @Override
502    Spliterator<Cell<R, C, V2>> cellSpliterator() {
503      return CollectSpliterators.map(fromTable.cellSet().spliterator(), cellFunction());
504    }
505
506    @Override
507    public Set<R> rowKeySet() {
508      return fromTable.rowKeySet();
509    }
510
511    @Override
512    public Set<C> columnKeySet() {
513      return fromTable.columnKeySet();
514    }
515
516    @Override
517    Collection<V2> createValues() {
518      return Collections2.transform(fromTable.values(), function);
519    }
520
521    @Override
522    public Map<R, Map<C, V2>> rowMap() {
523      Function<Map<C, V1>, Map<C, V2>> rowFunction =
524          new Function<Map<C, V1>, Map<C, V2>>() {
525            @Override
526            public Map<C, V2> apply(Map<C, V1> row) {
527              return Maps.transformValues(row, function);
528            }
529          };
530      return Maps.transformValues(fromTable.rowMap(), rowFunction);
531    }
532
533    @Override
534    public Map<C, Map<R, V2>> columnMap() {
535      Function<Map<R, V1>, Map<R, V2>> columnFunction =
536          new Function<Map<R, V1>, Map<R, V2>>() {
537            @Override
538            public Map<R, V2> apply(Map<R, V1> column) {
539              return Maps.transformValues(column, function);
540            }
541          };
542      return Maps.transformValues(fromTable.columnMap(), columnFunction);
543    }
544  }
545
546  /**
547   * Returns an unmodifiable view of the specified table. This method allows modules to provide
548   * users with "read-only" access to internal tables. Query operations on the returned table "read
549   * through" to the specified table, and attempts to modify the returned table, whether direct or
550   * via its collection views, result in an {@code UnsupportedOperationException}.
551   *
552   * <p>The returned table will be serializable if the specified table is serializable.
553   *
554   * <p>Consider using an {@link ImmutableTable}, which is guaranteed never to change.
555   *
556   * @since 11.0
557   */
558  public static <R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object>
559      Table<R, C, V> unmodifiableTable(Table<? extends R, ? extends C, ? extends V> table) {
560    return new UnmodifiableTable<>(table);
561  }
562
563  private static class UnmodifiableTable<
564          R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object>
565      extends ForwardingTable<R, C, V> implements Serializable {
566    final Table<? extends R, ? extends C, ? extends V> delegate;
567
568    UnmodifiableTable(Table<? extends R, ? extends C, ? extends V> delegate) {
569      this.delegate = checkNotNull(delegate);
570    }
571
572    @SuppressWarnings("unchecked") // safe, covariant cast
573    @Override
574    protected Table<R, C, V> delegate() {
575      return (Table<R, C, V>) delegate;
576    }
577
578    @Override
579    public Set<Cell<R, C, V>> cellSet() {
580      return Collections.unmodifiableSet(super.cellSet());
581    }
582
583    @Override
584    public void clear() {
585      throw new UnsupportedOperationException();
586    }
587
588    @Override
589    public Map<R, V> column(@ParametricNullness C columnKey) {
590      return Collections.unmodifiableMap(super.column(columnKey));
591    }
592
593    @Override
594    public Set<C> columnKeySet() {
595      return Collections.unmodifiableSet(super.columnKeySet());
596    }
597
598    @Override
599    public Map<C, Map<R, V>> columnMap() {
600      Function<Map<R, V>, Map<R, V>> wrapper = unmodifiableWrapper();
601      return Collections.unmodifiableMap(Maps.transformValues(super.columnMap(), wrapper));
602    }
603
604    @Override
605    @CheckForNull
606    public V put(
607        @ParametricNullness R rowKey,
608        @ParametricNullness C columnKey,
609        @ParametricNullness V value) {
610      throw new UnsupportedOperationException();
611    }
612
613    @Override
614    public void putAll(Table<? extends R, ? extends C, ? extends V> table) {
615      throw new UnsupportedOperationException();
616    }
617
618    @Override
619    @CheckForNull
620    public V remove(@CheckForNull Object rowKey, @CheckForNull Object columnKey) {
621      throw new UnsupportedOperationException();
622    }
623
624    @Override
625    public Map<C, V> row(@ParametricNullness R rowKey) {
626      return Collections.unmodifiableMap(super.row(rowKey));
627    }
628
629    @Override
630    public Set<R> rowKeySet() {
631      return Collections.unmodifiableSet(super.rowKeySet());
632    }
633
634    @Override
635    public Map<R, Map<C, V>> rowMap() {
636      Function<Map<C, V>, Map<C, V>> wrapper = unmodifiableWrapper();
637      return Collections.unmodifiableMap(Maps.transformValues(super.rowMap(), wrapper));
638    }
639
640    @Override
641    public Collection<V> values() {
642      return Collections.unmodifiableCollection(super.values());
643    }
644
645    private static final long serialVersionUID = 0;
646  }
647
648  /**
649   * Returns an unmodifiable view of the specified row-sorted table. This method allows modules to
650   * provide users with "read-only" access to internal tables. Query operations on the returned
651   * table "read through" to the specified table, and attempts to modify the returned table, whether
652   * direct or via its collection views, result in an {@code UnsupportedOperationException}.
653   *
654   * <p>The returned table will be serializable if the specified table is serializable.
655   *
656   * @param table the row-sorted table for which an unmodifiable view is to be returned
657   * @return an unmodifiable view of the specified table
658   * @since 11.0
659   */
660  public static <R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object>
661      RowSortedTable<R, C, V> unmodifiableRowSortedTable(
662          RowSortedTable<R, ? extends C, ? extends V> table) {
663    /*
664     * It's not ? extends R, because it's technically not covariant in R. Specifically,
665     * table.rowMap().comparator() could return a comparator that only works for the ? extends R.
666     * Collections.unmodifiableSortedMap makes the same distinction.
667     */
668    return new UnmodifiableRowSortedMap<>(table);
669  }
670
671  private static final class UnmodifiableRowSortedMap<
672          R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object>
673      extends UnmodifiableTable<R, C, V> implements RowSortedTable<R, C, V> {
674
675    public UnmodifiableRowSortedMap(RowSortedTable<R, ? extends C, ? extends V> delegate) {
676      super(delegate);
677    }
678
679    @Override
680    protected RowSortedTable<R, C, V> delegate() {
681      return (RowSortedTable<R, C, V>) super.delegate();
682    }
683
684    @Override
685    public SortedMap<R, Map<C, V>> rowMap() {
686      Function<Map<C, V>, Map<C, V>> wrapper = unmodifiableWrapper();
687      return Collections.unmodifiableSortedMap(Maps.transformValues(delegate().rowMap(), wrapper));
688    }
689
690    @Override
691    public SortedSet<R> rowKeySet() {
692      return Collections.unmodifiableSortedSet(delegate().rowKeySet());
693    }
694
695    private static final long serialVersionUID = 0;
696  }
697
698  @SuppressWarnings("unchecked")
699  private static <K extends @Nullable Object, V extends @Nullable Object>
700      Function<Map<K, V>, Map<K, V>> unmodifiableWrapper() {
701    return (Function) UNMODIFIABLE_WRAPPER;
702  }
703
704  private static final Function<? extends Map<?, ?>, ? extends Map<?, ?>> UNMODIFIABLE_WRAPPER =
705      new Function<Map<Object, Object>, Map<Object, Object>>() {
706        @Override
707        public Map<Object, Object> apply(Map<Object, Object> input) {
708          return Collections.unmodifiableMap(input);
709        }
710      };
711
712  /**
713   * Returns a synchronized (thread-safe) table backed by the specified table. In order to guarantee
714   * serial access, it is critical that <b>all</b> access to the backing table is accomplished
715   * through the returned table.
716   *
717   * <p>It is imperative that the user manually synchronize on the returned table when accessing any
718   * of its collection views:
719   *
720   * <pre>{@code
721   * Table<R, C, V> table = Tables.synchronizedTable(HashBasedTable.<R, C, V>create());
722   * ...
723   * Map<C, V> row = table.row(rowKey);  // Needn't be in synchronized block
724   * ...
725   * synchronized (table) {  // Synchronizing on table, not row!
726   *   Iterator<Entry<C, V>> i = row.entrySet().iterator(); // Must be in synchronized block
727   *   while (i.hasNext()) {
728   *     foo(i.next());
729   *   }
730   * }
731   * }</pre>
732   *
733   * <p>Failure to follow this advice may result in non-deterministic behavior.
734   *
735   * <p>The returned table will be serializable if the specified table is serializable.
736   *
737   * @param table the table to be wrapped in a synchronized view
738   * @return a synchronized view of the specified table
739   * @since 22.0
740   */
741  @J2ktIncompatible // Synchronized
742  public static <R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object>
743      Table<R, C, V> synchronizedTable(Table<R, C, V> table) {
744    return Synchronized.table(table, null);
745  }
746
747  static boolean equalsImpl(Table<?, ?, ?> table, @CheckForNull Object obj) {
748    if (obj == table) {
749      return true;
750    } else if (obj instanceof Table) {
751      Table<?, ?, ?> that = (Table<?, ?, ?>) obj;
752      return table.cellSet().equals(that.cellSet());
753    } else {
754      return false;
755    }
756  }
757}