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