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