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.util.Collections.emptyMap;
023
024import com.google.common.annotations.GwtCompatible;
025import com.google.common.annotations.GwtIncompatible;
026import com.google.common.base.Objects;
027import com.google.common.collect.Maps.IteratorBasedAbstractMap;
028import com.google.errorprone.annotations.CanIgnoreReturnValue;
029import com.google.errorprone.annotations.DoNotCall;
030import com.google.errorprone.annotations.concurrent.LazyInit;
031import com.google.j2objc.annotations.WeakOuter;
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.Set;
039import java.util.Spliterator;
040import javax.annotation.CheckForNull;
041import org.checkerframework.checker.nullness.qual.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)
093@ElementTypesAreNonnullByDefault
094public final class ArrayTable<R, C, V> extends AbstractTable<R, C, @Nullable V>
095    implements Serializable {
096
097  /**
098   * Creates an {@code ArrayTable} filled with {@code null}.
099   *
100   * @param rowKeys row keys that may be stored in the generated table
101   * @param columnKeys column keys that may be stored in the generated table
102   * @throws NullPointerException if any of the provided keys is null
103   * @throws IllegalArgumentException if {@code rowKeys} or {@code columnKeys} contains duplicates
104   *     or if exactly one of {@code rowKeys} or {@code columnKeys} is empty.
105   */
106  public static <R, C, V> ArrayTable<R, C, V> create(
107      Iterable<? extends R> rowKeys, Iterable<? extends C> columnKeys) {
108    return new ArrayTable<>(rowKeys, columnKeys);
109  }
110
111  /*
112   * TODO(jlevy): Add factory methods taking an Enum class, instead of an
113   * iterable, to specify the allowed row keys and/or column keys. Note that
114   * custom serialization logic is needed to support different enum sizes during
115   * serialization and deserialization.
116   */
117
118  /**
119   * Creates an {@code ArrayTable} with the mappings in the provided table.
120   *
121   * <p>If {@code table} includes a mapping with row key {@code r} and a separate mapping with
122   * column key {@code c}, the returned table contains a mapping with row key {@code r} and column
123   * key {@code c}. If that row key / column key pair in not in {@code table}, the pair maps to
124   * {@code null} in the generated table.
125   *
126   * <p>The returned table allows subsequent {@code put} calls with the row keys in {@code
127   * table.rowKeySet()} and the column keys in {@code table.columnKeySet()}. Calling {@link #put}
128   * with other keys leads to an {@code IllegalArgumentException}.
129   *
130   * <p>The ordering of {@code table.rowKeySet()} and {@code table.columnKeySet()} determines the
131   * row and column iteration ordering of the returned table.
132   *
133   * @throws NullPointerException if {@code table} has a null key
134   */
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
165    V[][] tmpArray = (@Nullable V[][]) new Object[rowList.size()][columnList.size()];
166    array = tmpArray;
167    // Necessary because in GWT the arrays are initialized with "undefined" instead of null.
168    eraseAll();
169  }
170
171  private ArrayTable(Table<R, C, ? extends @Nullable V> table) {
172    this(table.rowKeySet(), table.columnKeySet());
173    putAll(table);
174  }
175
176  private ArrayTable(ArrayTable<R, C, V> table) {
177    rowList = table.rowList;
178    columnList = table.columnList;
179    rowKeyToIndex = table.rowKeyToIndex;
180    columnKeyToIndex = table.columnKeyToIndex;
181    @SuppressWarnings("unchecked")
182    @Nullable
183    V[][] copy = (@Nullable V[][]) new Object[rowList.size()][columnList.size()];
184    array = copy;
185    for (int i = 0; i < rowList.size(); i++) {
186      System.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 Set<K> keySet() {
200      return keyIndex.keySet();
201    }
202
203    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 int size() {
217      return keyIndex.size();
218    }
219
220    @Override
221    public boolean isEmpty() {
222      return keyIndex.isEmpty();
223    }
224
225    Entry<K, V> getEntry(final 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        protected Entry<K, V> get(final int index) {
252          return getEntry(index);
253        }
254      };
255    }
256
257    @Override
258    Spliterator<Entry<K, V>> entrySpliterator() {
259      return CollectSpliterators.indexed(size(), Spliterator.ORDERED, this::getEntry);
260    }
261
262    // TODO(lowasser): consider an optimized values() implementation
263
264    @Override
265    public boolean containsKey(@CheckForNull Object key) {
266      return keyIndex.containsKey(key);
267    }
268
269    @CheckForNull
270    @Override
271    public V get(@CheckForNull Object key) {
272      Integer index = keyIndex.get(key);
273      if (index == null) {
274        return null;
275      } else {
276        return getValue(index);
277      }
278    }
279
280    @Override
281    @CheckForNull
282    public 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    @CheckForNull
293    public V remove(@CheckForNull Object key) {
294      throw new UnsupportedOperationException();
295    }
296
297    @Override
298    public void clear() {
299      throw new UnsupportedOperationException();
300    }
301  }
302
303  /**
304   * Returns, as an immutable list, the row keys provided when the table was constructed, including
305   * those that are mapped to null values only.
306   */
307  public ImmutableList<R> rowKeyList() {
308    return rowList;
309  }
310
311  /**
312   * Returns, as an immutable list, the column keys provided when the table was constructed,
313   * including those that are mapped to null values only.
314   */
315  public ImmutableList<C> columnKeyList() {
316    return columnList;
317  }
318
319  /**
320   * Returns the value corresponding to the specified row and column indices. The same value is
321   * returned by {@code get(rowKeyList().get(rowIndex), columnKeyList().get(columnIndex))}, but this
322   * method runs more quickly.
323   *
324   * @param rowIndex position of the row key in {@link #rowKeyList()}
325   * @param columnIndex position of the row key in {@link #columnKeyList()}
326   * @return the value with the specified row and column
327   * @throws IndexOutOfBoundsException if either index is negative, {@code rowIndex} is greater than
328   *     or equal to the number of allowed row keys, or {@code columnIndex} is greater than or equal
329   *     to the number of allowed column keys
330   */
331  @CheckForNull
332  public 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  @CheckForNull
354  public V set(int rowIndex, int columnIndex, @CheckForNull V value) {
355    // In GWT array access never throws IndexOutOfBoundsException.
356    checkElementIndex(rowIndex, rowList.size());
357    checkElementIndex(columnIndex, columnList.size());
358    V oldValue = array[rowIndex][columnIndex];
359    array[rowIndex][columnIndex] = value;
360    return oldValue;
361  }
362
363  /**
364   * Returns a two-dimensional array with the table contents. The row and column indices correspond
365   * to the positions of the row and column in the iterables provided during table construction. If
366   * the table lacks a mapping for a given row and column, the corresponding array element is null.
367   *
368   * <p>Subsequent table changes will not modify the array, and vice versa.
369   *
370   * @param valueClass class of values stored in the returned array
371   */
372  @GwtIncompatible // reflection
373  public @Nullable V[][] toArray(Class<V> valueClass) {
374    @SuppressWarnings("unchecked") // TODO: safe?
375    @Nullable
376    V[][] copy = (@Nullable V[][]) Array.newInstance(valueClass, rowList.size(), columnList.size());
377    for (int i = 0; i < rowList.size(); i++) {
378      System.arraycopy(array[i], 0, copy[i], 0, array[i].length);
379    }
380    return copy;
381  }
382
383  /**
384   * Not supported. Use {@link #eraseAll} instead.
385   *
386   * @throws UnsupportedOperationException always
387   * @deprecated Use {@link #eraseAll}
388   */
389  @DoNotCall("Always throws UnsupportedOperationException")
390  @Override
391  @Deprecated
392  public void clear() {
393    throw new UnsupportedOperationException();
394  }
395
396  /** Associates the value {@code null} with every pair of allowed row and column keys. */
397  public void eraseAll() {
398    for (@Nullable V[] row : array) {
399      Arrays.fill(row, null);
400    }
401  }
402
403  /**
404   * Returns {@code true} if the provided keys are among the keys provided when the table was
405   * constructed.
406   */
407  @Override
408  public boolean contains(@CheckForNull Object rowKey, @CheckForNull Object columnKey) {
409    return containsRow(rowKey) && containsColumn(columnKey);
410  }
411
412  /**
413   * Returns {@code true} if the provided column key is among the column keys provided when the
414   * table was constructed.
415   */
416  @Override
417  public boolean containsColumn(@CheckForNull Object columnKey) {
418    return columnKeyToIndex.containsKey(columnKey);
419  }
420
421  /**
422   * Returns {@code true} if the provided row key is among the row keys provided when the table was
423   * constructed.
424   */
425  @Override
426  public boolean containsRow(@CheckForNull Object rowKey) {
427    return rowKeyToIndex.containsKey(rowKey);
428  }
429
430  @Override
431  public boolean containsValue(@CheckForNull Object value) {
432    for (@Nullable V[] row : array) {
433      for (V element : row) {
434        if (Objects.equal(value, element)) {
435          return true;
436        }
437      }
438    }
439    return false;
440  }
441
442  @Override
443  @CheckForNull
444  public V get(@CheckForNull Object rowKey, @CheckForNull Object columnKey) {
445    Integer rowIndex = rowKeyToIndex.get(rowKey);
446    Integer columnIndex = columnKeyToIndex.get(columnKey);
447    return (rowIndex == null || columnIndex == null) ? null : at(rowIndex, columnIndex);
448  }
449
450  /**
451   * Returns {@code true} if {@code rowKeyList().size == 0} or {@code columnKeyList().size() == 0}.
452   */
453  @Override
454  public boolean isEmpty() {
455    return rowList.isEmpty() || columnList.isEmpty();
456  }
457
458  /**
459   * {@inheritDoc}
460   *
461   * @throws IllegalArgumentException if {@code rowKey} is not in {@link #rowKeySet()} or {@code
462   *     columnKey} is not in {@link #columnKeySet()}.
463   */
464  @CanIgnoreReturnValue
465  @Override
466  @CheckForNull
467  public V put(R rowKey, C columnKey, @CheckForNull V value) {
468    checkNotNull(rowKey);
469    checkNotNull(columnKey);
470    Integer rowIndex = rowKeyToIndex.get(rowKey);
471    checkArgument(rowIndex != null, "Row %s not in %s", rowKey, rowList);
472    Integer columnIndex = columnKeyToIndex.get(columnKey);
473    checkArgument(columnIndex != null, "Column %s not in %s", columnKey, columnList);
474    return set(rowIndex, columnIndex, value);
475  }
476
477  /*
478   * TODO(jlevy): Consider creating a merge() method, similar to putAll() but
479   * copying non-null values only.
480   */
481
482  /**
483   * {@inheritDoc}
484   *
485   * <p>If {@code table} is an {@code ArrayTable}, its null values will be stored in this table,
486   * possibly replacing values that were previously non-null.
487   *
488   * @throws NullPointerException if {@code table} has a null key
489   * @throws IllegalArgumentException if any of the provided table's row keys or column keys is not
490   *     in {@link #rowKeySet()} or {@link #columnKeySet()}
491   */
492  @Override
493  public void putAll(Table<? extends R, ? extends C, ? extends @Nullable V> table) {
494    super.putAll(table);
495  }
496
497  /**
498   * Not supported. Use {@link #erase} instead.
499   *
500   * @throws UnsupportedOperationException always
501   * @deprecated Use {@link #erase}
502   */
503  @DoNotCall("Always throws UnsupportedOperationException")
504  @CanIgnoreReturnValue
505  @Override
506  @Deprecated
507  @CheckForNull
508  public V remove(@CheckForNull Object rowKey, @CheckForNull Object columnKey) {
509    throw new UnsupportedOperationException();
510  }
511
512  /**
513   * Associates the value {@code null} with the specified keys, assuming both keys are valid. If
514   * either key is null or isn't among the keys provided during construction, this method has no
515   * effect.
516   *
517   * <p>This method is equivalent to {@code put(rowKey, columnKey, null)} when both provided keys
518   * are valid.
519   *
520   * @param rowKey row key of mapping to be erased
521   * @param columnKey column key of mapping to be erased
522   * @return the value previously associated with the keys, or {@code null} if no mapping existed
523   *     for the keys
524   */
525  @CanIgnoreReturnValue
526  @CheckForNull
527  public V erase(@CheckForNull Object rowKey, @CheckForNull Object columnKey) {
528    Integer rowIndex = rowKeyToIndex.get(rowKey);
529    Integer columnIndex = columnKeyToIndex.get(columnKey);
530    if (rowIndex == null || columnIndex == null) {
531      return null;
532    }
533    return set(rowIndex, columnIndex, null);
534  }
535
536  // TODO(jlevy): Add eraseRow and eraseColumn methods?
537
538  @Override
539  public int size() {
540    return rowList.size() * columnList.size();
541  }
542
543  /**
544   * Returns an unmodifiable set of all row key / column key / value triplets. Changes to the table
545   * will update the returned set.
546   *
547   * <p>The returned set's iterator traverses the mappings with the first row key, the mappings with
548   * the second row key, and so on.
549   *
550   * <p>The value in the returned cells may change if the table subsequently changes.
551   *
552   * @return set of table cells consisting of row key / column key / value triplets
553   */
554  @Override
555  public Set<Cell<R, C, @Nullable V>> cellSet() {
556    return super.cellSet();
557  }
558
559  @Override
560  Iterator<Cell<R, C, @Nullable V>> cellIterator() {
561    return new AbstractIndexedListIterator<Cell<R, C, @Nullable V>>(size()) {
562      @Override
563      protected Cell<R, C, @Nullable V> get(final int index) {
564        return getCell(index);
565      }
566    };
567  }
568
569  @Override
570  Spliterator<Cell<R, C, @Nullable V>> cellSpliterator() {
571    return CollectSpliterators.<Cell<R, C, @Nullable V>>indexed(
572        size(), Spliterator.ORDERED | Spliterator.NONNULL | Spliterator.DISTINCT, this::getCell);
573  }
574
575  private Cell<R, C, @Nullable V> getCell(final int index) {
576    return new Tables.AbstractCell<R, C, @Nullable V>() {
577      final int rowIndex = index / columnList.size();
578      final int columnIndex = index % columnList.size();
579
580      @Override
581      public R getRowKey() {
582        return rowList.get(rowIndex);
583      }
584
585      @Override
586      public C getColumnKey() {
587        return columnList.get(columnIndex);
588      }
589
590      @Override
591      @CheckForNull
592      public V getValue() {
593        return at(rowIndex, columnIndex);
594      }
595    };
596  }
597
598  @CheckForNull
599  private V getValue(int index) {
600    int rowIndex = index / columnList.size();
601    int columnIndex = index % columnList.size();
602    return at(rowIndex, columnIndex);
603  }
604
605  /**
606   * Returns a view of all mappings that have the given column key. If the column key isn't in
607   * {@link #columnKeySet()}, an empty immutable map is returned.
608   *
609   * <p>Otherwise, for each row key in {@link #rowKeySet()}, the returned map associates the row key
610   * with the corresponding value in the table. Changes to the returned map will update the
611   * underlying table, and vice versa.
612   *
613   * @param columnKey key of column to search for in the table
614   * @return the corresponding map from row keys to values
615   */
616  @Override
617  public Map<R, @Nullable V> column(C columnKey) {
618    checkNotNull(columnKey);
619    Integer columnIndex = columnKeyToIndex.get(columnKey);
620    if (columnIndex == null) {
621      return emptyMap();
622    } else {
623      return new Column(columnIndex);
624    }
625  }
626
627  private class Column extends ArrayMap<R, @Nullable V> {
628    final int columnIndex;
629
630    Column(int columnIndex) {
631      super(rowKeyToIndex);
632      this.columnIndex = columnIndex;
633    }
634
635    @Override
636    String getKeyRole() {
637      return "Row";
638    }
639
640    @Override
641    @CheckForNull
642    V getValue(int index) {
643      return at(index, columnIndex);
644    }
645
646    @Override
647    @CheckForNull
648    V setValue(int index, @CheckForNull V newValue) {
649      return set(index, columnIndex, newValue);
650    }
651  }
652
653  /**
654   * Returns an immutable set of the valid column keys, including those that are associated with
655   * null values only.
656   *
657   * @return immutable set of column keys
658   */
659  @Override
660  public ImmutableSet<C> columnKeySet() {
661    return columnKeyToIndex.keySet();
662  }
663
664  @LazyInit @CheckForNull private transient ColumnMap columnMap;
665
666  @Override
667  public Map<C, Map<R, @Nullable V>> columnMap() {
668    ColumnMap map = columnMap;
669    return (map == null) ? columnMap = new ColumnMap() : map;
670  }
671
672  @WeakOuter
673  private class ColumnMap extends ArrayMap<C, Map<R, @Nullable V>> {
674    private ColumnMap() {
675      super(columnKeyToIndex);
676    }
677
678    @Override
679    String getKeyRole() {
680      return "Column";
681    }
682
683    @Override
684    Map<R, @Nullable V> getValue(int index) {
685      return new Column(index);
686    }
687
688    @Override
689    Map<R, @Nullable V> setValue(int index, Map<R, @Nullable V> newValue) {
690      throw new UnsupportedOperationException();
691    }
692
693    @Override
694    @CheckForNull
695    public Map<R, @Nullable V> put(C key, Map<R, @Nullable V> value) {
696      throw new UnsupportedOperationException();
697    }
698  }
699
700  /**
701   * Returns a view of all mappings that have the given row key. If the row key isn't in {@link
702   * #rowKeySet()}, an empty immutable map is returned.
703   *
704   * <p>Otherwise, for each column key in {@link #columnKeySet()}, the returned map associates the
705   * column key with the corresponding value in the table. Changes to the returned map will update
706   * the underlying table, and vice versa.
707   *
708   * @param rowKey key of row to search for in the table
709   * @return the corresponding map from column keys to values
710   */
711  @Override
712  public Map<C, @Nullable V> row(R rowKey) {
713    checkNotNull(rowKey);
714    Integer rowIndex = rowKeyToIndex.get(rowKey);
715    if (rowIndex == null) {
716      return emptyMap();
717    } else {
718      return new Row(rowIndex);
719    }
720  }
721
722  private class Row extends ArrayMap<C, @Nullable V> {
723    final int rowIndex;
724
725    Row(int rowIndex) {
726      super(columnKeyToIndex);
727      this.rowIndex = rowIndex;
728    }
729
730    @Override
731    String getKeyRole() {
732      return "Column";
733    }
734
735    @Override
736    @CheckForNull
737    V getValue(int index) {
738      return at(rowIndex, index);
739    }
740
741    @Override
742    @CheckForNull
743    V setValue(int index, @CheckForNull V newValue) {
744      return set(rowIndex, index, newValue);
745    }
746  }
747
748  /**
749   * Returns an immutable set of the valid row keys, including those that are associated with null
750   * values only.
751   *
752   * @return immutable set of row keys
753   */
754  @Override
755  public ImmutableSet<R> rowKeySet() {
756    return rowKeyToIndex.keySet();
757  }
758
759  @LazyInit @CheckForNull private transient RowMap rowMap;
760
761  @Override
762  public Map<R, Map<C, @Nullable V>> rowMap() {
763    RowMap map = rowMap;
764    return (map == null) ? rowMap = new RowMap() : map;
765  }
766
767  @WeakOuter
768  private class RowMap extends ArrayMap<R, Map<C, @Nullable V>> {
769    private RowMap() {
770      super(rowKeyToIndex);
771    }
772
773    @Override
774    String getKeyRole() {
775      return "Row";
776    }
777
778    @Override
779    Map<C, @Nullable V> getValue(int index) {
780      return new Row(index);
781    }
782
783    @Override
784    Map<C, @Nullable V> setValue(int index, Map<C, @Nullable V> newValue) {
785      throw new UnsupportedOperationException();
786    }
787
788    @Override
789    @CheckForNull
790    public Map<C, @Nullable V> put(R key, Map<C, @Nullable V> value) {
791      throw new UnsupportedOperationException();
792    }
793  }
794
795  /**
796   * Returns an unmodifiable collection of all values, which may contain duplicates. Changes to the
797   * table will update the returned collection.
798   *
799   * <p>The returned collection's iterator traverses the values of the first row key, the values of
800   * the second row key, and so on.
801   *
802   * @return collection of values
803   */
804  @Override
805  public Collection<@Nullable V> values() {
806    return super.values();
807  }
808
809  @Override
810  Iterator<@Nullable V> valuesIterator() {
811    return new AbstractIndexedListIterator<@Nullable V>(size()) {
812      @Override
813      @CheckForNull
814      protected V get(int index) {
815        return getValue(index);
816      }
817    };
818  }
819
820  @Override
821  Spliterator<@Nullable V> valuesSpliterator() {
822    return CollectSpliterators.<@Nullable V>indexed(size(), Spliterator.ORDERED, this::getValue);
823  }
824
825  private static final long serialVersionUID = 0;
826}