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