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