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 com.google.common.collect.Maps.indexMap;
023import static java.lang.System.arraycopy;
024import static java.util.Collections.emptyMap;
025
026import com.google.common.annotations.GwtCompatible;
027import com.google.common.annotations.GwtIncompatible;
028import com.google.common.annotations.J2ktIncompatible;
029import com.google.common.collect.Maps.IteratorBasedAbstractMap;
030import com.google.errorprone.annotations.CanIgnoreReturnValue;
031import com.google.errorprone.annotations.DoNotCall;
032import java.io.Serializable;
033import java.lang.reflect.Array;
034import java.util.Arrays;
035import java.util.Collection;
036import java.util.Iterator;
037import java.util.Map;
038import java.util.Objects;
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// We explicitly list `implements Table<...>` so that its `@Nullable V` appears in Javadoc.
093@SuppressWarnings("RedundancyRemover")
094@GwtCompatible
095public final class ArrayTable<R, C, V> extends AbstractTable<R, C, @Nullable V>
096    implements Table<R, C, @Nullable V>, Serializable {
097
098  /**
099   * Creates an {@code ArrayTable} filled with {@code null}.
100   *
101   * @param rowKeys row keys that may be stored in the generated table
102   * @param columnKeys column keys that may be stored in the generated table
103   * @throws NullPointerException if any of the provided keys is null
104   * @throws IllegalArgumentException if {@code rowKeys} or {@code columnKeys} contains duplicates
105   *     or if exactly one of {@code rowKeys} or {@code columnKeys} is empty.
106   */
107  public static <R, C, V> ArrayTable<R, C, V> create(
108      Iterable<? extends R> rowKeys, Iterable<? extends C> columnKeys) {
109    return new ArrayTable<>(rowKeys, columnKeys);
110  }
111
112  /*
113   * TODO(jlevy): Add factory methods taking an Enum class, instead of an
114   * iterable, to specify the allowed row keys and/or column keys. Note that
115   * custom serialization logic is needed to support different enum sizes during
116   * serialization and deserialization.
117   */
118
119  /**
120   * Creates an {@code ArrayTable} with the mappings in the provided table.
121   *
122   * <p>If {@code table} includes a mapping with row key {@code r} and a separate mapping with
123   * column key {@code c}, the returned table contains a mapping with row key {@code r} and column
124   * key {@code c}. If that row key / column key pair in not in {@code table}, the pair maps to
125   * {@code null} in the generated table.
126   *
127   * <p>The returned table allows subsequent {@code put} calls with the row keys in {@code
128   * table.rowKeySet()} and the column keys in {@code table.columnKeySet()}. Calling {@link #put}
129   * with other keys leads to an {@code IllegalArgumentException}.
130   *
131   * <p>The ordering of {@code table.rowKeySet()} and {@code table.columnKeySet()} determines the
132   * row and column iteration ordering of the returned table.
133   *
134   * @throws NullPointerException if {@code table} has a null key
135   */
136  @SuppressWarnings("unchecked") // TODO(cpovirk): Make constructor accept wildcard types?
137  public static <R, C, V> ArrayTable<R, C, V> create(Table<R, C, ? extends @Nullable V> table) {
138    return (table instanceof ArrayTable)
139        ? new ArrayTable<R, C, V>((ArrayTable<R, C, V>) table)
140        : new ArrayTable<R, C, V>(table);
141  }
142
143  private final ImmutableList<R> rowList;
144  private final ImmutableList<C> columnList;
145
146  // TODO(jlevy): Add getters returning rowKeyToIndex and columnKeyToIndex?
147  private final ImmutableMap<R, Integer> rowKeyToIndex;
148  private final ImmutableMap<C, Integer> columnKeyToIndex;
149  private final @Nullable V[][] array;
150
151  private ArrayTable(Iterable<? extends R> rowKeys, Iterable<? extends C> columnKeys) {
152    this.rowList = ImmutableList.copyOf(rowKeys);
153    this.columnList = ImmutableList.copyOf(columnKeys);
154    checkArgument(rowList.isEmpty() == columnList.isEmpty());
155
156    /*
157     * TODO(jlevy): Support only one of rowKey / columnKey being empty? If we
158     * do, when columnKeys is empty but rowKeys isn't, rowKeyList() can contain
159     * elements but rowKeySet() will be empty and containsRow() won't
160     * acknowledge them.
161     */
162    rowKeyToIndex = indexMap(rowList);
163    columnKeyToIndex = indexMap(columnList);
164
165    @SuppressWarnings("unchecked")
166    @Nullable V[][] tmpArray = (@Nullable V[][]) new Object[rowList.size()][columnList.size()];
167    array = tmpArray;
168    // Necessary because in GWT the arrays are initialized with "undefined" instead of null.
169    eraseAll();
170  }
171
172  private ArrayTable(Table<R, C, ? extends @Nullable V> table) {
173    this(table.rowKeySet(), table.columnKeySet());
174    putAll(table);
175  }
176
177  private ArrayTable(ArrayTable<R, C, V> table) {
178    rowList = table.rowList;
179    columnList = table.columnList;
180    rowKeyToIndex = table.rowKeyToIndex;
181    columnKeyToIndex = table.columnKeyToIndex;
182    @SuppressWarnings("unchecked")
183    @Nullable V[][] copy = (@Nullable V[][]) new Object[rowList.size()][columnList.size()];
184    array = copy;
185    for (int i = 0; i < rowList.size(); i++) {
186      arraycopy(table.array[i], 0, copy[i], 0, table.array[i].length);
187    }
188  }
189
190  private abstract static class ArrayMap<K, V extends @Nullable Object>
191      extends IteratorBasedAbstractMap<K, V> {
192    private final ImmutableMap<K, Integer> keyIndex;
193
194    private ArrayMap(ImmutableMap<K, Integer> keyIndex) {
195      this.keyIndex = keyIndex;
196    }
197
198    @Override
199    public final Set<K> keySet() {
200      return keyIndex.keySet();
201    }
202
203    final K getKey(int index) {
204      return keyIndex.keySet().asList().get(index);
205    }
206
207    abstract String getKeyRole();
208
209    @ParametricNullness
210    abstract V getValue(int index);
211
212    @ParametricNullness
213    abstract V setValue(int index, @ParametricNullness V newValue);
214
215    @Override
216    public final int size() {
217      return keyIndex.size();
218    }
219
220    @Override
221    public final boolean isEmpty() {
222      return keyIndex.isEmpty();
223    }
224
225    final Entry<K, V> getEntry(int index) {
226      checkElementIndex(index, size());
227      return new AbstractMapEntry<K, V>() {
228        @Override
229        public K getKey() {
230          return ArrayMap.this.getKey(index);
231        }
232
233        @Override
234        @ParametricNullness
235        public V getValue() {
236          return ArrayMap.this.getValue(index);
237        }
238
239        @Override
240        @ParametricNullness
241        public V setValue(@ParametricNullness V value) {
242          return ArrayMap.this.setValue(index, value);
243        }
244      };
245    }
246
247    @Override
248    Iterator<Entry<K, V>> entryIterator() {
249      return new AbstractIndexedListIterator<Entry<K, V>>(size()) {
250        @Override
251        Entry<K, V> get(int index) {
252          return getEntry(index);
253        }
254      };
255    }
256
257    @Override
258    @GwtIncompatible // Spliterator
259    Spliterator<Entry<K, V>> entrySpliterator() {
260      return CollectSpliterators.indexed(
261          size(), Spliterator.ORDERED | Spliterator.DISTINCT | Spliterator.NONNULL, this::getEntry);
262    }
263
264    // TODO(lowasser): consider an optimized values() implementation
265
266    @Override
267    public final boolean containsKey(@Nullable Object key) {
268      return keyIndex.containsKey(key);
269    }
270
271    @Override
272    public final @Nullable V get(@Nullable Object key) {
273      Integer index = keyIndex.get(key);
274      if (index == null) {
275        return null;
276      } else {
277        return getValue(index);
278      }
279    }
280
281    @Override
282    public @Nullable V put(K key, @ParametricNullness V value) {
283      Integer index = keyIndex.get(key);
284      if (index == null) {
285        throw new IllegalArgumentException(
286            getKeyRole() + " " + key + " not in " + keyIndex.keySet());
287      }
288      return setValue(index, value);
289    }
290
291    @Override
292    public final @Nullable V remove(@Nullable Object key) {
293      throw new UnsupportedOperationException();
294    }
295
296    @Override
297    public final void clear() {
298      throw new UnsupportedOperationException();
299    }
300  }
301
302  /**
303   * Returns, as an immutable list, the row keys provided when the table was constructed, including
304   * those that are mapped to null values only.
305   */
306  public ImmutableList<R> rowKeyList() {
307    return rowList;
308  }
309
310  /**
311   * Returns, as an immutable list, the column keys provided when the table was constructed,
312   * including those that are mapped to null values only.
313   */
314  public ImmutableList<C> columnKeyList() {
315    return columnList;
316  }
317
318  /**
319   * Returns the value corresponding to the specified row and column indices. The same value is
320   * returned by {@code get(rowKeyList().get(rowIndex), columnKeyList().get(columnIndex))}, but this
321   * method runs more quickly.
322   *
323   * @param rowIndex position of the row key in {@link #rowKeyList()}
324   * @param columnIndex position of the row key in {@link #columnKeyList()}
325   * @return the value with the specified row and column
326   * @throws IndexOutOfBoundsException if either index is negative, {@code rowIndex} is greater than
327   *     or equal to the number of allowed row keys, or {@code columnIndex} is greater than or equal
328   *     to the number of allowed column keys
329   */
330  public @Nullable V at(int rowIndex, int columnIndex) {
331    // In GWT array access never throws IndexOutOfBoundsException.
332    checkElementIndex(rowIndex, rowList.size());
333    checkElementIndex(columnIndex, columnList.size());
334    return array[rowIndex][columnIndex];
335  }
336
337  /**
338   * Associates {@code value} with the specified row and column indices. The logic {@code
339   * put(rowKeyList().get(rowIndex), columnKeyList().get(columnIndex), value)} has the same
340   * behavior, but this method runs more quickly.
341   *
342   * @param rowIndex position of the row key in {@link #rowKeyList()}
343   * @param columnIndex position of the row key in {@link #columnKeyList()}
344   * @param value value to store in the table
345   * @return the previous value with the specified row and column
346   * @throws IndexOutOfBoundsException if either index is negative, {@code rowIndex} is greater than
347   *     or equal to the number of allowed row keys, or {@code columnIndex} is greater than or equal
348   *     to the number of allowed column keys
349   */
350  @CanIgnoreReturnValue
351  public @Nullable V set(int rowIndex, int columnIndex, @Nullable V value) {
352    // In GWT array access never throws IndexOutOfBoundsException.
353    checkElementIndex(rowIndex, rowList.size());
354    checkElementIndex(columnIndex, columnList.size());
355    V oldValue = array[rowIndex][columnIndex];
356    array[rowIndex][columnIndex] = value;
357    return oldValue;
358  }
359
360  /**
361   * Returns a two-dimensional array with the table contents. The row and column indices correspond
362   * to the positions of the row and column in the iterables provided during table construction. If
363   * the table lacks a mapping for a given row and column, the corresponding array element is null.
364   *
365   * <p>Subsequent table changes will not modify the array, and vice versa.
366   *
367   * @param valueClass class of values stored in the returned array
368   */
369  @GwtIncompatible // reflection
370  public @Nullable V[][] toArray(Class<V> valueClass) {
371    @SuppressWarnings("unchecked") // TODO: safe?
372    @Nullable V[][] copy =
373        (@Nullable V[][]) Array.newInstance(valueClass, rowList.size(), columnList.size());
374    for (int i = 0; i < rowList.size(); i++) {
375      arraycopy(array[i], 0, copy[i], 0, array[i].length);
376    }
377    return copy;
378  }
379
380  /**
381   * Not supported. Use {@link #eraseAll} instead.
382   *
383   * @throws UnsupportedOperationException always
384   * @deprecated Use {@link #eraseAll}
385   */
386  @DoNotCall("Always throws UnsupportedOperationException")
387  @Override
388  @Deprecated
389  public void clear() {
390    throw new UnsupportedOperationException();
391  }
392
393  /** Associates the value {@code null} with every pair of allowed row and column keys. */
394  public void eraseAll() {
395    for (@Nullable V[] row : array) {
396      Arrays.fill(row, null);
397    }
398  }
399
400  /**
401   * Returns {@code true} if the provided keys are among the keys provided when the table was
402   * constructed.
403   */
404  @Override
405  public boolean contains(@Nullable Object rowKey, @Nullable Object columnKey) {
406    return containsRow(rowKey) && containsColumn(columnKey);
407  }
408
409  /**
410   * Returns {@code true} if the provided column key is among the column keys provided when the
411   * table was constructed.
412   */
413  @Override
414  public boolean containsColumn(@Nullable Object columnKey) {
415    return columnKeyToIndex.containsKey(columnKey);
416  }
417
418  /**
419   * Returns {@code true} if the provided row key is among the row keys provided when the table was
420   * constructed.
421   */
422  @Override
423  public boolean containsRow(@Nullable Object rowKey) {
424    return rowKeyToIndex.containsKey(rowKey);
425  }
426
427  @Override
428  public boolean containsValue(@Nullable Object value) {
429    for (@Nullable V[] row : array) {
430      for (V element : row) {
431        if (Objects.equals(value, element)) {
432          return true;
433        }
434      }
435    }
436    return false;
437  }
438
439  @Override
440  public @Nullable V get(@Nullable Object rowKey, @Nullable Object columnKey) {
441    Integer rowIndex = rowKeyToIndex.get(rowKey);
442    Integer columnIndex = columnKeyToIndex.get(columnKey);
443    return (rowIndex == null || columnIndex == null) ? null : at(rowIndex, columnIndex);
444  }
445
446  /**
447   * Returns {@code true} if {@code rowKeyList().size == 0} or {@code columnKeyList().size() == 0}.
448   */
449  @Override
450  public boolean isEmpty() {
451    return rowList.isEmpty() || columnList.isEmpty();
452  }
453
454  /**
455   * {@inheritDoc}
456   *
457   * @throws IllegalArgumentException if {@code rowKey} is not in {@link #rowKeySet()} or {@code
458   *     columnKey} is not in {@link #columnKeySet()}.
459   */
460  @CanIgnoreReturnValue
461  @Override
462  public @Nullable V put(R rowKey, C columnKey, @Nullable V value) {
463    checkNotNull(rowKey);
464    checkNotNull(columnKey);
465    Integer rowIndex = rowKeyToIndex.get(rowKey);
466    checkArgument(rowIndex != null, "Row %s not in %s", rowKey, rowList);
467    Integer columnIndex = columnKeyToIndex.get(columnKey);
468    checkArgument(columnIndex != null, "Column %s not in %s", columnKey, columnList);
469    return set(rowIndex, columnIndex, value);
470  }
471
472  /*
473   * TODO(jlevy): Consider creating a merge() method, similar to putAll() but
474   * copying non-null values only.
475   */
476
477  /**
478   * {@inheritDoc}
479   *
480   * <p>If {@code table} is an {@code ArrayTable}, its null values will be stored in this table,
481   * possibly replacing values that were previously non-null.
482   *
483   * @throws NullPointerException if {@code table} has a null key
484   * @throws IllegalArgumentException if any of the provided table's row keys or column keys is not
485   *     in {@link #rowKeySet()} or {@link #columnKeySet()}
486   */
487  @Override
488  public void putAll(Table<? extends R, ? extends C, ? extends @Nullable V> table) {
489    super.putAll(table);
490  }
491
492  /**
493   * Not supported. Use {@link #erase} instead.
494   *
495   * @throws UnsupportedOperationException always
496   * @deprecated Use {@link #erase}
497   */
498  @DoNotCall("Always throws UnsupportedOperationException")
499  @CanIgnoreReturnValue
500  @Override
501  @Deprecated
502  public @Nullable V remove(@Nullable Object rowKey, @Nullable Object columnKey) {
503    throw new UnsupportedOperationException();
504  }
505
506  /**
507   * Associates the value {@code null} with the specified keys, assuming both keys are valid. If
508   * either key is null or isn't among the keys provided during construction, this method has no
509   * effect.
510   *
511   * <p>This method is equivalent to {@code put(rowKey, columnKey, null)} when both provided keys
512   * are valid.
513   *
514   * @param rowKey row key of mapping to be erased
515   * @param columnKey column key of mapping to be erased
516   * @return the value previously associated with the keys, or {@code null} if no mapping existed
517   *     for the keys
518   */
519  @CanIgnoreReturnValue
520  public @Nullable V erase(@Nullable Object rowKey, @Nullable Object columnKey) {
521    Integer rowIndex = rowKeyToIndex.get(rowKey);
522    Integer columnIndex = columnKeyToIndex.get(columnKey);
523    if (rowIndex == null || columnIndex == null) {
524      return null;
525    }
526    return set(rowIndex, columnIndex, null);
527  }
528
529  // TODO(jlevy): Add eraseRow and eraseColumn methods?
530
531  @Override
532  public int size() {
533    return rowList.size() * columnList.size();
534  }
535
536  /**
537   * Returns an unmodifiable set of all row key / column key / value triplets. Changes to the table
538   * will update the returned set.
539   *
540   * <p>The returned set's iterator traverses the mappings with the first row key, the mappings with
541   * the second row key, and so on.
542   *
543   * <p>The value in the returned cells may change if the table subsequently changes.
544   *
545   * @return set of table cells consisting of row key / column key / value triplets
546   */
547  @Override
548  public Set<Cell<R, C, @Nullable V>> cellSet() {
549    return super.cellSet();
550  }
551
552  @Override
553  Iterator<Cell<R, C, @Nullable V>> cellIterator() {
554    return new AbstractIndexedListIterator<Cell<R, C, @Nullable V>>(size()) {
555      @Override
556      Cell<R, C, @Nullable V> get(int index) {
557        return getCell(index);
558      }
559    };
560  }
561
562  @Override
563  Spliterator<Cell<R, C, @Nullable V>> cellSpliterator() {
564    return CollectSpliterators.indexed(
565        size(), Spliterator.ORDERED | Spliterator.NONNULL | Spliterator.DISTINCT, this::getCell);
566  }
567
568  private Cell<R, C, @Nullable V> getCell(int index) {
569    return new Tables.AbstractCell<R, C, @Nullable V>() {
570      final int rowIndex = index / columnList.size();
571      final int columnIndex = index % columnList.size();
572
573      @Override
574      public R getRowKey() {
575        return rowList.get(rowIndex);
576      }
577
578      @Override
579      public C getColumnKey() {
580        return columnList.get(columnIndex);
581      }
582
583      @Override
584      public @Nullable V getValue() {
585        return at(rowIndex, columnIndex);
586      }
587    };
588  }
589
590  private @Nullable V getValue(int index) {
591    int rowIndex = index / columnList.size();
592    int columnIndex = index % columnList.size();
593    return at(rowIndex, columnIndex);
594  }
595
596  /**
597   * Returns a view of all mappings that have the given column key. If the column key isn't in
598   * {@link #columnKeySet()}, an empty immutable map is returned.
599   *
600   * <p>Otherwise, for each row key in {@link #rowKeySet()}, the returned map associates the row key
601   * with the corresponding value in the table. Changes to the returned map will update the
602   * underlying table, and vice versa.
603   *
604   * @param columnKey key of column to search for in the table
605   * @return the corresponding map from row keys to values
606   */
607  @Override
608  public Map<R, @Nullable V> column(C columnKey) {
609    checkNotNull(columnKey);
610    Integer columnIndex = columnKeyToIndex.get(columnKey);
611    if (columnIndex == null) {
612      return emptyMap();
613    } else {
614      return new Column(columnIndex);
615    }
616  }
617
618  private final class Column extends ArrayMap<R, @Nullable V> {
619    final int columnIndex;
620
621    Column(int columnIndex) {
622      super(rowKeyToIndex);
623      this.columnIndex = columnIndex;
624    }
625
626    @Override
627    String getKeyRole() {
628      return "Row";
629    }
630
631    @Override
632    @Nullable V getValue(int index) {
633      return at(index, columnIndex);
634    }
635
636    @Override
637    @Nullable V setValue(int index, @Nullable V newValue) {
638      return set(index, columnIndex, newValue);
639    }
640  }
641
642  /**
643   * Returns an immutable set of the valid column keys, including those that are associated with
644   * null values only.
645   *
646   * @return immutable set of column keys
647   */
648  @Override
649  public ImmutableSet<C> columnKeySet() {
650    return columnKeyToIndex.keySet();
651  }
652
653  @Override
654  public Map<C, Map<R, @Nullable V>> columnMap() {
655    return new ColumnMap();
656  }
657
658  private final 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 final 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  @Override
742  public Map<R, Map<C, @Nullable V>> rowMap() {
743    return new RowMap();
744  }
745
746  private final class RowMap extends ArrayMap<R, Map<C, @Nullable V>> {
747    private RowMap() {
748      super(rowKeyToIndex);
749    }
750
751    @Override
752    String getKeyRole() {
753      return "Row";
754    }
755
756    @Override
757    Map<C, @Nullable V> getValue(int index) {
758      return new Row(index);
759    }
760
761    @Override
762    Map<C, @Nullable V> setValue(int index, Map<C, @Nullable V> newValue) {
763      throw new UnsupportedOperationException();
764    }
765
766    @Override
767    public @Nullable Map<C, @Nullable V> put(R key, Map<C, @Nullable V> value) {
768      throw new UnsupportedOperationException();
769    }
770  }
771
772  /**
773   * Returns an unmodifiable collection of all values, which may contain duplicates. Changes to the
774   * table will update the returned collection.
775   *
776   * <p>The returned collection's iterator traverses the values of the first row key, the values of
777   * the second row key, and so on.
778   *
779   * @return collection of values
780   */
781  @Override
782  public Collection<@Nullable V> values() {
783    return super.values();
784  }
785
786  @Override
787  Iterator<@Nullable V> valuesIterator() {
788    return new AbstractIndexedListIterator<@Nullable V>(size()) {
789      @Override
790      @Nullable V get(int index) {
791        return getValue(index);
792      }
793    };
794  }
795
796  @Override
797  @GwtIncompatible // Spliterator
798  Spliterator<@Nullable V> valuesSpliterator() {
799    return CollectSpliterators.<@Nullable V>indexed(size(), Spliterator.ORDERED, this::getValue);
800  }
801
802  @GwtIncompatible @J2ktIncompatible private static final long serialVersionUID = 0;
803}