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