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.checkArgument;
020import static com.google.common.base.Preconditions.checkElementIndex;
021import static com.google.common.base.Preconditions.checkNotNull;
022import static java.lang.System.arraycopy;
023import static java.util.Collections.emptyMap;
024
025import com.google.common.annotations.GwtCompatible;
026import com.google.common.annotations.GwtIncompatible;
027import com.google.common.base.Objects;
028import com.google.common.collect.Maps.IteratorBasedAbstractMap;
029import com.google.errorprone.annotations.CanIgnoreReturnValue;
030import com.google.errorprone.annotations.DoNotCall;
031import com.google.errorprone.annotations.concurrent.LazyInit;
032import com.google.j2objc.annotations.WeakOuter;
033import java.io.Serializable;
034import java.lang.reflect.Array;
035import java.util.Arrays;
036import java.util.Collection;
037import java.util.Iterator;
038import java.util.Map;
039import java.util.Set;
040import java.util.Spliterator;
041import org.jspecify.annotations.Nullable;
042
043/**
044 * Fixed-size {@link Table} implementation backed by a two-dimensional array.
045 *
046 * <p><b>Warning:</b> {@code ArrayTable} is rarely the {@link Table} implementation you want. First,
047 * it requires that the complete universe of rows and columns be specified at construction time.
048 * Second, it is always backed by an array large enough to hold a value for every possible
049 * combination of row and column keys. (This is rarely optimal unless the table is extremely dense.)
050 * Finally, every possible combination of row and column keys is always considered to have a value
051 * associated with it: It is not possible to "remove" a value, only to replace it with {@code null},
052 * which will still appear when iterating over the table's contents in a foreach loop or a call to a
053 * null-hostile method like {@link ImmutableTable#copyOf}. For alternatives, please see <a
054 * href="https://github.com/google/guava/wiki/NewCollectionTypesExplained#table">the wiki</a>.
055 *
056 * <p>The allowed row and column keys must be supplied when the table is created. The table always
057 * contains a mapping for every row key / column pair. The value corresponding to a given row and
058 * column is null unless another value is provided.
059 *
060 * <p>The table's size is constant: the product of the number of supplied row keys and the number of
061 * supplied column keys. The {@code remove} and {@code clear} methods are not supported by the table
062 * or its views. The {@link #erase} and {@link #eraseAll} methods may be used instead.
063 *
064 * <p>The ordering of the row and column keys provided when the table is constructed determines the
065 * iteration ordering across rows and columns in the table's views. None of the view iterators
066 * support {@link Iterator#remove}. If the table is modified after an iterator is created, the
067 * iterator remains valid.
068 *
069 * <p>This class requires less memory than the {@link HashBasedTable} and {@link TreeBasedTable}
070 * implementations, except when the table is sparse.
071 *
072 * <p>Null row keys or column keys are not permitted.
073 *
074 * <p>This class provides methods involving the underlying array structure, where the array indices
075 * correspond to the position of a row or column in the lists of allowed keys and values. See the
076 * {@link #at}, {@link #set}, {@link #toArray}, {@link #rowKeyList}, and {@link #columnKeyList}
077 * methods for more details.
078 *
079 * <p>Note that this implementation is not synchronized. If multiple threads access the same cell of
080 * an {@code ArrayTable} concurrently and one of the threads modifies its value, there is no
081 * guarantee that the new value will be fully visible to the other threads. To guarantee that
082 * modifications are visible, synchronize access to the table. Unlike other {@code Table}
083 * implementations, synchronization is unnecessary between a thread that writes to one cell and a
084 * thread that reads from another.
085 *
086 * <p>See the Guava User Guide article on <a href=
087 * "https://github.com/google/guava/wiki/NewCollectionTypesExplained#table">{@code Table}</a>.
088 *
089 * @author Jared Levy
090 * @since 10.0
091 */
092@GwtCompatible(emulated = true)
093public final class ArrayTable<R, C, V> extends AbstractTable<R, C, @Nullable V>
094    implements Serializable {
095
096  /**
097   * Creates an {@code ArrayTable} filled with {@code null}.
098   *
099   * @param rowKeys row keys that may be stored in the generated table
100   * @param columnKeys column keys that may be stored in the generated table
101   * @throws NullPointerException if any of the provided keys is null
102   * @throws IllegalArgumentException if {@code rowKeys} or {@code columnKeys} contains duplicates
103   *     or if exactly one of {@code rowKeys} or {@code columnKeys} is empty.
104   */
105  public static <R, C, V> ArrayTable<R, C, V> create(
106      Iterable<? extends R> rowKeys, Iterable<? extends C> columnKeys) {
107    return new ArrayTable<>(rowKeys, columnKeys);
108  }
109
110  /*
111   * TODO(jlevy): Add factory methods taking an Enum class, instead of an
112   * iterable, to specify the allowed row keys and/or column keys. Note that
113   * custom serialization logic is needed to support different enum sizes during
114   * serialization and deserialization.
115   */
116
117  /**
118   * Creates an {@code ArrayTable} with the mappings in the provided table.
119   *
120   * <p>If {@code table} includes a mapping with row key {@code r} and a separate mapping with
121   * column key {@code c}, the returned table contains a mapping with row key {@code r} and column
122   * key {@code c}. If that row key / column key pair in not in {@code table}, the pair maps to
123   * {@code null} in the generated table.
124   *
125   * <p>The returned table allows subsequent {@code put} calls with the row keys in {@code
126   * table.rowKeySet()} and the column keys in {@code table.columnKeySet()}. Calling {@link #put}
127   * with other keys leads to an {@code IllegalArgumentException}.
128   *
129   * <p>The ordering of {@code table.rowKeySet()} and {@code table.columnKeySet()} determines the
130   * row and column iteration ordering of the returned table.
131   *
132   * @throws NullPointerException if {@code table} has a null key
133   */
134  @SuppressWarnings("unchecked") // TODO(cpovirk): Make constructor accept wildcard types?
135  public static <R, C, V> ArrayTable<R, C, V> create(Table<R, C, ? extends @Nullable V> table) {
136    return (table instanceof ArrayTable)
137        ? new ArrayTable<R, C, V>((ArrayTable<R, C, V>) table)
138        : new ArrayTable<R, C, V>(table);
139  }
140
141  private final ImmutableList<R> rowList;
142  private final ImmutableList<C> columnList;
143
144  // TODO(jlevy): Add getters returning rowKeyToIndex and columnKeyToIndex?
145  private final ImmutableMap<R, Integer> rowKeyToIndex;
146  private final ImmutableMap<C, Integer> columnKeyToIndex;
147  private final @Nullable V[][] array;
148
149  private ArrayTable(Iterable<? extends R> rowKeys, Iterable<? extends C> columnKeys) {
150    this.rowList = ImmutableList.copyOf(rowKeys);
151    this.columnList = ImmutableList.copyOf(columnKeys);
152    checkArgument(rowList.isEmpty() == columnList.isEmpty());
153
154    /*
155     * TODO(jlevy): Support only one of rowKey / columnKey being empty? If we
156     * do, when columnKeys is empty but rowKeys isn't, rowKeyList() can contain
157     * elements but rowKeySet() will be empty and containsRow() won't
158     * acknowledge them.
159     */
160    rowKeyToIndex = Maps.indexMap(rowList);
161    columnKeyToIndex = Maps.indexMap(columnList);
162
163    @SuppressWarnings("unchecked")
164    @Nullable V[][] tmpArray = (@Nullable V[][]) new Object[rowList.size()][columnList.size()];
165    array = tmpArray;
166    // Necessary because in GWT the arrays are initialized with "undefined" instead of null.
167    eraseAll();
168  }
169
170  private ArrayTable(Table<R, C, ? extends @Nullable V> table) {
171    this(table.rowKeySet(), table.columnKeySet());
172    putAll(table);
173  }
174
175  private ArrayTable(ArrayTable<R, C, V> table) {
176    rowList = table.rowList;
177    columnList = table.columnList;
178    rowKeyToIndex = table.rowKeyToIndex;
179    columnKeyToIndex = table.columnKeyToIndex;
180    @SuppressWarnings("unchecked")
181    @Nullable V[][] copy = (@Nullable V[][]) new Object[rowList.size()][columnList.size()];
182    array = copy;
183    for (int i = 0; i < rowList.size(); i++) {
184      arraycopy(table.array[i], 0, copy[i], 0, table.array[i].length);
185    }
186  }
187
188  private abstract static class ArrayMap<K, V extends @Nullable Object>
189      extends IteratorBasedAbstractMap<K, V> {
190    private final ImmutableMap<K, Integer> keyIndex;
191
192    private ArrayMap(ImmutableMap<K, Integer> keyIndex) {
193      this.keyIndex = keyIndex;
194    }
195
196    @Override
197    public Set<K> keySet() {
198      return keyIndex.keySet();
199    }
200
201    K getKey(int index) {
202      return keyIndex.keySet().asList().get(index);
203    }
204
205    abstract String getKeyRole();
206
207    @ParametricNullness
208    abstract V getValue(int index);
209
210    @ParametricNullness
211    abstract V setValue(int index, @ParametricNullness V newValue);
212
213    @Override
214    public int size() {
215      return keyIndex.size();
216    }
217
218    @Override
219    public boolean isEmpty() {
220      return keyIndex.isEmpty();
221    }
222
223    Entry<K, V> getEntry(final int index) {
224      checkElementIndex(index, size());
225      return new AbstractMapEntry<K, V>() {
226        @Override
227        public K getKey() {
228          return ArrayMap.this.getKey(index);
229        }
230
231        @Override
232        @ParametricNullness
233        public V getValue() {
234          return ArrayMap.this.getValue(index);
235        }
236
237        @Override
238        @ParametricNullness
239        public V setValue(@ParametricNullness V value) {
240          return ArrayMap.this.setValue(index, value);
241        }
242      };
243    }
244
245    @Override
246    Iterator<Entry<K, V>> entryIterator() {
247      return new AbstractIndexedListIterator<Entry<K, V>>(size()) {
248        @Override
249        protected Entry<K, V> get(final int index) {
250          return getEntry(index);
251        }
252      };
253    }
254
255    @Override
256    Spliterator<Entry<K, V>> entrySpliterator() {
257      return CollectSpliterators.indexed(size(), Spliterator.ORDERED, this::getEntry);
258    }
259
260    // TODO(lowasser): consider an optimized values() implementation
261
262    @Override
263    public boolean containsKey(@Nullable Object key) {
264      return keyIndex.containsKey(key);
265    }
266
267    @Override
268    public @Nullable V get(@Nullable Object key) {
269      Integer index = keyIndex.get(key);
270      if (index == null) {
271        return null;
272      } else {
273        return getValue(index);
274      }
275    }
276
277    @Override
278    public @Nullable V put(K key, @ParametricNullness V value) {
279      Integer index = keyIndex.get(key);
280      if (index == null) {
281        throw new IllegalArgumentException(
282            getKeyRole() + " " + key + " not in " + keyIndex.keySet());
283      }
284      return setValue(index, value);
285    }
286
287    @Override
288    public @Nullable V remove(@Nullable Object key) {
289      throw new UnsupportedOperationException();
290    }
291
292    @Override
293    public void clear() {
294      throw new UnsupportedOperationException();
295    }
296  }
297
298  /**
299   * Returns, as an immutable list, the row keys provided when the table was constructed, including
300   * those that are mapped to null values only.
301   */
302  public ImmutableList<R> rowKeyList() {
303    return rowList;
304  }
305
306  /**
307   * Returns, as an immutable list, the column keys provided when the table was constructed,
308   * including those that are mapped to null values only.
309   */
310  public ImmutableList<C> columnKeyList() {
311    return columnList;
312  }
313
314  /**
315   * Returns the value corresponding to the specified row and column indices. The same value is
316   * returned by {@code get(rowKeyList().get(rowIndex), columnKeyList().get(columnIndex))}, but this
317   * method runs more quickly.
318   *
319   * @param rowIndex position of the row key in {@link #rowKeyList()}
320   * @param columnIndex position of the row key in {@link #columnKeyList()}
321   * @return the value with the specified row and column
322   * @throws IndexOutOfBoundsException if either index is negative, {@code rowIndex} is greater than
323   *     or equal to the number of allowed row keys, or {@code columnIndex} is greater than or equal
324   *     to the number of allowed column keys
325   */
326  public @Nullable V at(int rowIndex, int columnIndex) {
327    // In GWT array access never throws IndexOutOfBoundsException.
328    checkElementIndex(rowIndex, rowList.size());
329    checkElementIndex(columnIndex, columnList.size());
330    return array[rowIndex][columnIndex];
331  }
332
333  /**
334   * Associates {@code value} with the specified row and column indices. The logic {@code
335   * put(rowKeyList().get(rowIndex), columnKeyList().get(columnIndex), value)} has the same
336   * behavior, but this method runs more quickly.
337   *
338   * @param rowIndex position of the row key in {@link #rowKeyList()}
339   * @param columnIndex position of the row key in {@link #columnKeyList()}
340   * @param value value to store in the table
341   * @return the previous value with the specified row and column
342   * @throws IndexOutOfBoundsException if either index is negative, {@code rowIndex} is greater than
343   *     or equal to the number of allowed row keys, or {@code columnIndex} is greater than or equal
344   *     to the number of allowed column keys
345   */
346  @CanIgnoreReturnValue
347  public @Nullable V set(int rowIndex, int columnIndex, @Nullable V value) {
348    // In GWT array access never throws IndexOutOfBoundsException.
349    checkElementIndex(rowIndex, rowList.size());
350    checkElementIndex(columnIndex, columnList.size());
351    V oldValue = array[rowIndex][columnIndex];
352    array[rowIndex][columnIndex] = value;
353    return oldValue;
354  }
355
356  /**
357   * Returns a two-dimensional array with the table contents. The row and column indices correspond
358   * to the positions of the row and column in the iterables provided during table construction. If
359   * the table lacks a mapping for a given row and column, the corresponding array element is null.
360   *
361   * <p>Subsequent table changes will not modify the array, and vice versa.
362   *
363   * @param valueClass class of values stored in the returned array
364   */
365  @GwtIncompatible // reflection
366  public @Nullable V[][] toArray(Class<V> valueClass) {
367    @SuppressWarnings("unchecked") // TODO: safe?
368    @Nullable V[][] copy =
369        (@Nullable V[][]) Array.newInstance(valueClass, rowList.size(), columnList.size());
370    for (int i = 0; i < rowList.size(); i++) {
371      arraycopy(array[i], 0, copy[i], 0, array[i].length);
372    }
373    return copy;
374  }
375
376  /**
377   * Not supported. Use {@link #eraseAll} instead.
378   *
379   * @throws UnsupportedOperationException always
380   * @deprecated Use {@link #eraseAll}
381   */
382  @DoNotCall("Always throws UnsupportedOperationException")
383  @Override
384  @Deprecated
385  public void clear() {
386    throw new UnsupportedOperationException();
387  }
388
389  /** Associates the value {@code null} with every pair of allowed row and column keys. */
390  public void eraseAll() {
391    for (@Nullable V[] row : array) {
392      Arrays.fill(row, null);
393    }
394  }
395
396  /**
397   * Returns {@code true} if the provided keys are among the keys provided when the table was
398   * constructed.
399   */
400  @Override
401  public boolean contains(@Nullable Object rowKey, @Nullable Object columnKey) {
402    return containsRow(rowKey) && containsColumn(columnKey);
403  }
404
405  /**
406   * Returns {@code true} if the provided column key is among the column keys provided when the
407   * table was constructed.
408   */
409  @Override
410  public boolean containsColumn(@Nullable Object columnKey) {
411    return columnKeyToIndex.containsKey(columnKey);
412  }
413
414  /**
415   * Returns {@code true} if the provided row key is among the row keys provided when the table was
416   * constructed.
417   */
418  @Override
419  public boolean containsRow(@Nullable Object rowKey) {
420    return rowKeyToIndex.containsKey(rowKey);
421  }
422
423  @Override
424  public boolean containsValue(@Nullable Object value) {
425    for (@Nullable V[] row : array) {
426      for (V element : row) {
427        if (Objects.equal(value, element)) {
428          return true;
429        }
430      }
431    }
432    return false;
433  }
434
435  @Override
436  public @Nullable V get(@Nullable Object rowKey, @Nullable Object columnKey) {
437    Integer rowIndex = rowKeyToIndex.get(rowKey);
438    Integer columnIndex = columnKeyToIndex.get(columnKey);
439    return (rowIndex == null || columnIndex == null) ? null : at(rowIndex, columnIndex);
440  }
441
442  /**
443   * Returns {@code true} if {@code rowKeyList().size == 0} or {@code columnKeyList().size() == 0}.
444   */
445  @Override
446  public boolean isEmpty() {
447    return rowList.isEmpty() || columnList.isEmpty();
448  }
449
450  /**
451   * {@inheritDoc}
452   *
453   * @throws IllegalArgumentException if {@code rowKey} is not in {@link #rowKeySet()} or {@code
454   *     columnKey} is not in {@link #columnKeySet()}.
455   */
456  @CanIgnoreReturnValue
457  @Override
458  public @Nullable V put(R rowKey, C columnKey, @Nullable V value) {
459    checkNotNull(rowKey);
460    checkNotNull(columnKey);
461    Integer rowIndex = rowKeyToIndex.get(rowKey);
462    checkArgument(rowIndex != null, "Row %s not in %s", rowKey, rowList);
463    Integer columnIndex = columnKeyToIndex.get(columnKey);
464    checkArgument(columnIndex != null, "Column %s not in %s", columnKey, columnList);
465    return set(rowIndex, columnIndex, value);
466  }
467
468  /*
469   * TODO(jlevy): Consider creating a merge() method, similar to putAll() but
470   * copying non-null values only.
471   */
472
473  /**
474   * {@inheritDoc}
475   *
476   * <p>If {@code table} is an {@code ArrayTable}, its null values will be stored in this table,
477   * possibly replacing values that were previously non-null.
478   *
479   * @throws NullPointerException if {@code table} has a null key
480   * @throws IllegalArgumentException if any of the provided table's row keys or column keys is not
481   *     in {@link #rowKeySet()} or {@link #columnKeySet()}
482   */
483  @Override
484  public void putAll(Table<? extends R, ? extends C, ? extends @Nullable V> table) {
485    super.putAll(table);
486  }
487
488  /**
489   * Not supported. Use {@link #erase} instead.
490   *
491   * @throws UnsupportedOperationException always
492   * @deprecated Use {@link #erase}
493   */
494  @DoNotCall("Always throws UnsupportedOperationException")
495  @CanIgnoreReturnValue
496  @Override
497  @Deprecated
498  public @Nullable V remove(@Nullable Object rowKey, @Nullable Object columnKey) {
499    throw new UnsupportedOperationException();
500  }
501
502  /**
503   * Associates the value {@code null} with the specified keys, assuming both keys are valid. If
504   * either key is null or isn't among the keys provided during construction, this method has no
505   * effect.
506   *
507   * <p>This method is equivalent to {@code put(rowKey, columnKey, null)} when both provided keys
508   * are valid.
509   *
510   * @param rowKey row key of mapping to be erased
511   * @param columnKey column key of mapping to be erased
512   * @return the value previously associated with the keys, or {@code null} if no mapping existed
513   *     for the keys
514   */
515  @CanIgnoreReturnValue
516  public @Nullable V erase(@Nullable Object rowKey, @Nullable Object columnKey) {
517    Integer rowIndex = rowKeyToIndex.get(rowKey);
518    Integer columnIndex = columnKeyToIndex.get(columnKey);
519    if (rowIndex == null || columnIndex == null) {
520      return null;
521    }
522    return set(rowIndex, columnIndex, null);
523  }
524
525  // TODO(jlevy): Add eraseRow and eraseColumn methods?
526
527  @Override
528  public int size() {
529    return rowList.size() * columnList.size();
530  }
531
532  /**
533   * Returns an unmodifiable set of all row key / column key / value triplets. Changes to the table
534   * will update the returned set.
535   *
536   * <p>The returned set's iterator traverses the mappings with the first row key, the mappings with
537   * the second row key, and so on.
538   *
539   * <p>The value in the returned cells may change if the table subsequently changes.
540   *
541   * @return set of table cells consisting of row key / column key / value triplets
542   */
543  @Override
544  public Set<Cell<R, C, @Nullable V>> cellSet() {
545    return super.cellSet();
546  }
547
548  @Override
549  Iterator<Cell<R, C, @Nullable V>> cellIterator() {
550    return new AbstractIndexedListIterator<Cell<R, C, @Nullable V>>(size()) {
551      @Override
552      protected Cell<R, C, @Nullable V> get(final int index) {
553        return getCell(index);
554      }
555    };
556  }
557
558  @Override
559  Spliterator<Cell<R, C, @Nullable V>> cellSpliterator() {
560    return CollectSpliterators.<Cell<R, C, @Nullable V>>indexed(
561        size(), Spliterator.ORDERED | Spliterator.NONNULL | Spliterator.DISTINCT, this::getCell);
562  }
563
564  private Cell<R, C, @Nullable V> getCell(final int index) {
565    return new Tables.AbstractCell<R, C, @Nullable V>() {
566      final int rowIndex = index / columnList.size();
567      final int columnIndex = index % columnList.size();
568
569      @Override
570      public R getRowKey() {
571        return rowList.get(rowIndex);
572      }
573
574      @Override
575      public C getColumnKey() {
576        return columnList.get(columnIndex);
577      }
578
579      @Override
580      public @Nullable V getValue() {
581        return at(rowIndex, columnIndex);
582      }
583    };
584  }
585
586  private @Nullable V getValue(int index) {
587    int rowIndex = index / columnList.size();
588    int columnIndex = index % columnList.size();
589    return at(rowIndex, columnIndex);
590  }
591
592  /**
593   * Returns a view of all mappings that have the given column key. If the column key isn't in
594   * {@link #columnKeySet()}, an empty immutable map is returned.
595   *
596   * <p>Otherwise, for each row key in {@link #rowKeySet()}, the returned map associates the row key
597   * with the corresponding value in the table. Changes to the returned map will update the
598   * underlying table, and vice versa.
599   *
600   * @param columnKey key of column to search for in the table
601   * @return the corresponding map from row keys to values
602   */
603  @Override
604  public Map<R, @Nullable V> column(C columnKey) {
605    checkNotNull(columnKey);
606    Integer columnIndex = columnKeyToIndex.get(columnKey);
607    if (columnIndex == null) {
608      return emptyMap();
609    } else {
610      return new Column(columnIndex);
611    }
612  }
613
614  private class Column extends ArrayMap<R, @Nullable V> {
615    final int columnIndex;
616
617    Column(int columnIndex) {
618      super(rowKeyToIndex);
619      this.columnIndex = columnIndex;
620    }
621
622    @Override
623    String getKeyRole() {
624      return "Row";
625    }
626
627    @Override
628    @Nullable V getValue(int index) {
629      return at(index, columnIndex);
630    }
631
632    @Override
633    @Nullable V setValue(int index, @Nullable V newValue) {
634      return set(index, columnIndex, newValue);
635    }
636  }
637
638  /**
639   * Returns an immutable set of the valid column keys, including those that are associated with
640   * null values only.
641   *
642   * @return immutable set of column keys
643   */
644  @Override
645  public ImmutableSet<C> columnKeySet() {
646    return columnKeyToIndex.keySet();
647  }
648
649  @LazyInit private transient @Nullable ColumnMap columnMap;
650
651  @Override
652  public Map<C, Map<R, @Nullable V>> columnMap() {
653    ColumnMap map = columnMap;
654    return (map == null) ? columnMap = new ColumnMap() : map;
655  }
656
657  @WeakOuter
658  private class ColumnMap extends ArrayMap<C, Map<R, @Nullable V>> {
659    private ColumnMap() {
660      super(columnKeyToIndex);
661    }
662
663    @Override
664    String getKeyRole() {
665      return "Column";
666    }
667
668    @Override
669    Map<R, @Nullable V> getValue(int index) {
670      return new Column(index);
671    }
672
673    @Override
674    Map<R, @Nullable V> setValue(int index, Map<R, @Nullable V> newValue) {
675      throw new UnsupportedOperationException();
676    }
677
678    @Override
679    public @Nullable Map<R, @Nullable V> put(C key, Map<R, @Nullable V> value) {
680      throw new UnsupportedOperationException();
681    }
682  }
683
684  /**
685   * Returns a view of all mappings that have the given row key. If the row key isn't in {@link
686   * #rowKeySet()}, an empty immutable map is returned.
687   *
688   * <p>Otherwise, for each column key in {@link #columnKeySet()}, the returned map associates the
689   * column key with the corresponding value in the table. Changes to the returned map will update
690   * the underlying table, and vice versa.
691   *
692   * @param rowKey key of row to search for in the table
693   * @return the corresponding map from column keys to values
694   */
695  @Override
696  public Map<C, @Nullable V> row(R rowKey) {
697    checkNotNull(rowKey);
698    Integer rowIndex = rowKeyToIndex.get(rowKey);
699    if (rowIndex == null) {
700      return emptyMap();
701    } else {
702      return new Row(rowIndex);
703    }
704  }
705
706  private class Row extends ArrayMap<C, @Nullable V> {
707    final int rowIndex;
708
709    Row(int rowIndex) {
710      super(columnKeyToIndex);
711      this.rowIndex = rowIndex;
712    }
713
714    @Override
715    String getKeyRole() {
716      return "Column";
717    }
718
719    @Override
720    @Nullable V getValue(int index) {
721      return at(rowIndex, index);
722    }
723
724    @Override
725    @Nullable V setValue(int index, @Nullable V newValue) {
726      return set(rowIndex, index, newValue);
727    }
728  }
729
730  /**
731   * Returns an immutable set of the valid row keys, including those that are associated with null
732   * values only.
733   *
734   * @return immutable set of row keys
735   */
736  @Override
737  public ImmutableSet<R> rowKeySet() {
738    return rowKeyToIndex.keySet();
739  }
740
741  @LazyInit private transient @Nullable RowMap rowMap;
742
743  @Override
744  public Map<R, Map<C, @Nullable V>> rowMap() {
745    RowMap map = rowMap;
746    return (map == null) ? rowMap = new RowMap() : map;
747  }
748
749  @WeakOuter
750  private class RowMap extends ArrayMap<R, Map<C, @Nullable V>> {
751    private RowMap() {
752      super(rowKeyToIndex);
753    }
754
755    @Override
756    String getKeyRole() {
757      return "Row";
758    }
759
760    @Override
761    Map<C, @Nullable V> getValue(int index) {
762      return new Row(index);
763    }
764
765    @Override
766    Map<C, @Nullable V> setValue(int index, Map<C, @Nullable V> newValue) {
767      throw new UnsupportedOperationException();
768    }
769
770    @Override
771    public @Nullable Map<C, @Nullable V> put(R key, Map<C, @Nullable V> value) {
772      throw new UnsupportedOperationException();
773    }
774  }
775
776  /**
777   * Returns an unmodifiable collection of all values, which may contain duplicates. Changes to the
778   * table will update the returned collection.
779   *
780   * <p>The returned collection's iterator traverses the values of the first row key, the values of
781   * the second row key, and so on.
782   *
783   * @return collection of values
784   */
785  @Override
786  public Collection<@Nullable V> values() {
787    return super.values();
788  }
789
790  @Override
791  Iterator<@Nullable V> valuesIterator() {
792    return new AbstractIndexedListIterator<@Nullable V>(size()) {
793      @Override
794      protected @Nullable V get(int index) {
795        return getValue(index);
796      }
797    };
798  }
799
800  @Override
801  Spliterator<@Nullable V> valuesSpliterator() {
802    return CollectSpliterators.<@Nullable V>indexed(size(), Spliterator.ORDERED, this::getValue);
803  }
804
805  private static final long serialVersionUID = 0;
806}