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