Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (C) 2009 The Guava Authors
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package com.google.common.collect;
 
 import static com.google.common.base.Preconditions.checkArgument;
 import static com.google.common.base.Preconditions.checkNotNull;
 
 
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
 import  javax.annotation.Nullable;

Fixed-size Table implementation backed by a two-dimensional array.

The allowed row and column keys must be supplied when the table is created. The table always contains a mapping for every row key / column pair. The value corresponding to a given row and column is null unless another value is provided.

The table's size is constant: the product of the number of supplied row keys and the number of supplied column keys. The remove and clear methods are not supported by the table or its views. The erase and eraseAll methods may be used instead.

The ordering of the row and column keys provided when the table is constructed determines the iteration ordering across rows and columns in the table's views. None of the view iterators support Iterator.remove. If the table is modified after an iterator is created, the iterator remains valid.

This class requires less memory than the HashBasedTable and TreeBasedTable implementations, except when the table is sparse.

Null row keys or column keys are not permitted.

This class provides methods involving the underlying array structure, where the array indices correspond to the position of a row or column in the lists of allowed keys and values. See the at, set, toArray, rowKeyList, and columnKeyList methods for more details.

Note that this implementation is not synchronized. If multiple threads access the same cell of an ArrayTable concurrently and one of the threads modifies its value, there is no guarantee that the new value will be fully visible to the other threads. To guarantee that modifications are visible, synchronize access to the table. Unlike other Table implementations, synchronization is unnecessary between a thread that writes to one cell and a thread that reads from another.

See the Guava User Guide article on Table.

Author(s):
Jared Levy
Since:
10.0
 
 public final class ArrayTable<R, C, V> implements Table<R, C, V>, Serializable {

  
Creates an empty ArrayTable.

Parameters:
rowKeys row keys that may be stored in the generated table
columnKeys column keys that may be stored in the generated table
Throws:
NullPointerException if any of the provided keys is null
IllegalArgumentException if rowKeys or columnKeys contains duplicates or is empty
 
   public static <R, C, V> ArrayTable<R, C, V> create(
       Iterable<? extends R> rowKeysIterable<? extends C> columnKeys) {
     return new ArrayTable<R, C, V>(rowKeyscolumnKeys);
   }
 
  /*
   * TODO(jlevy): Add factory methods taking an Enum class, instead of an
   * iterable, to specify the allowed row keys and/or column keys. Note that
   * custom serialization logic is needed to support different enum sizes during
   * serialization and deserialization.
   */

  
Creates an ArrayTable with the mappings in the provided table.

If table includes a mapping with row key r and a separate mapping with column key c, the returned table contains a mapping with row key r and column key c. If that row key / column key pair in not in table, the pair maps to null in the generated table.

The returned table allows subsequent put calls with the row keys in table.rowKeySet() and the column keys in table.columnKeySet(). Calling put with other keys leads to an IllegalArgumentException.

The ordering of table.rowKeySet() and table.columnKeySet() determines the row and column iteration ordering of the returned table.

Throws:
NullPointerException if table has a null key
IllegalArgumentException if the provided table is empty
  public static <R, C, V> ArrayTable<R, C, V> create(Table<R, C, V> table) {
    return new ArrayTable<R, C, V>(table);
  }

  
Creates an ArrayTable with the same mappings, allowed keys, and iteration ordering as the provided ArrayTable.
  public static <R, C, V> ArrayTable<R, C, V> create(
      ArrayTable<R, C, V> table) {
    return new ArrayTable<R, C, V>(table);
  }
  private final ImmutableList<R> rowList;
  private final ImmutableList<C> columnList;
  // TODO(jlevy): Add getters returning rowKeyToIndex and columnKeyToIndex?
  private final ImmutableMap<R, IntegerrowKeyToIndex;
  private final ImmutableMap<C, IntegercolumnKeyToIndex;
  private final V[][] array;
  private ArrayTable(Iterable<? extends R> rowKeys,
      Iterable<? extends C> columnKeys) {
    this. = ImmutableList.copyOf(rowKeys);
    this. = ImmutableList.copyOf(columnKeys);
    /*
     * TODO(jlevy): Support empty rowKeys or columnKeys? If we do, when
     * columnKeys is empty but rowKeys isn't, the table is empty but
     * containsRow() can return true and rowKeySet() isn't empty.
     */
    @SuppressWarnings("unchecked")
    V[][] tmpArray
        = (V[][]) new Object[.size()][.size()];
     = tmpArray;
  }
  private static <E> ImmutableMap<E, Integerindex(List<E> list) {
    ImmutableMap.Builder<E, IntegercolumnBuilder = ImmutableMap.builder();
    for (int i = 0; i < list.size(); i++) {
      columnBuilder.put(list.get(i), i);
    }
    return columnBuilder.build();
  }
  private ArrayTable(Table<R, C, V> table) {
    this(table.rowKeySet(), table.columnKeySet());
    putAll(table);
  }
  private ArrayTable(ArrayTable<R, C, V> table) {
     = table.rowList;
     = table.columnList;
     = table.rowKeyToIndex;
     = table.columnKeyToIndex;
    @SuppressWarnings("unchecked")
    V[][] copy = (V[][]) new Object[.size()][.size()];
     = copy;
    for (int i = 0; i < .size(); i++) {
      System.arraycopy(table.array[i], 0, copy[i], 0, table.array[i].length);
    }
  }
  private abstract static class ArrayMap<K, V> extends Maps.ImprovedAbstractMap<K, V> {
    private final ImmutableMap<K, IntegerkeyIndex;
    private ArrayMap(ImmutableMap<K, IntegerkeyIndex) {
      this. = keyIndex;
    }
    @Override
    public Set<K> keySet() {
      return .keySet();
    }
    K getKey(int index) {
      return .keySet().asList().get(index);
    }
    abstract String getKeyRole();
    @Nullable abstract V getValue(int index);
    @Nullable abstract V setValue(int index, V newValue);
    @Override
    public int size() {
      return .size();
    }
    @Override
    public boolean isEmpty() {
      return .isEmpty();
    }
    @Override
    protected Set<Entry<K, V>> createEntrySet() {
      return new Maps.EntrySet<K, V>() {
        @Override
        Map<K, V> map() {
          return ArrayMap.this;
        }
        @Override
        public Iterator<Entry<K, V>> iterator() {
          return new AbstractIndexedListIterator<Entry<K, V>>(size()) {
            @Override
            protected Entry<K, V> get(final int index) {
              return new AbstractMapEntry<K, V>() {
                @Override
                public K getKey() {
                  return ArrayMap.this.getKey(index);
                }
                @Override
                public V getValue() {
                  return ArrayMap.this.getValue(index);
                }
                @Override
                public V setValue(V value) {
                  return ArrayMap.this.setValue(indexvalue);
                }
              };
            }
          };
        }
      };
    }
    @Override
    public boolean containsKey(@Nullable Object key) {
      return .containsKey(key);
    }
    @Override
    public V get(@Nullable Object key) {
      Integer index = .get(key);
      if (index == null) {
        return null;
      } else {
        return getValue(index);
      }
    }
    @Override
    public V put(K key, V value) {
      Integer index = .get(key);
      if (index == null) {
        throw new IllegalArgumentException(
            getKeyRole() + " " + key + " not in " + .keySet());
      }
      return setValue(indexvalue);
    }
    @Override
    public V remove(Object key) {
      throw new UnsupportedOperationException();
    }
    @Override
    public void clear() {
      throw new UnsupportedOperationException();
    }
  }

  
Returns, as an immutable list, the row keys provided when the table was constructed, including those that are mapped to null values only.
  public ImmutableList<R> rowKeyList() {
    return ;
  }

  
Returns, as an immutable list, the column keys provided when the table was constructed, including those that are mapped to null values only.
  public ImmutableList<C> columnKeyList() {
    return ;
  }

  
Returns the value corresponding to the specified row and column indices. The same value is returned by get(rowKeyList().get(rowIndex), columnKeyList().get(columnIndex)), but this method runs more quickly.

Parameters:
rowIndex position of the row key in rowKeyList()
columnIndex position of the row key in columnKeyList()
Returns:
the value with the specified row and column
Throws:
IndexOutOfBoundsException if either index is negative, rowIndex is greater then or equal to the number of allowed row keys, or columnIndex is greater then or equal to the number of allowed column keys
  public V at(int rowIndexint columnIndex) {
    return [rowIndex][columnIndex];
  }

  
Associates value with the specified row and column indices. The logic put(rowKeyList().get(rowIndex), columnKeyList().get(columnIndex), value) has the same behavior, but this method runs more quickly.

Parameters:
rowIndex position of the row key in rowKeyList()
columnIndex position of the row key in columnKeyList()
value value to store in the table
Returns:
the previous value with the specified row and column
Throws:
IndexOutOfBoundsException if either index is negative, rowIndex is greater then or equal to the number of allowed row keys, or columnIndex is greater then or equal to the number of allowed column keys
  public V set(int rowIndexint columnIndex, @Nullable V value) {
    V oldValue = [rowIndex][columnIndex];
    [rowIndex][columnIndex] = value;
    return oldValue;
  }

  
Returns a two-dimensional array with the table contents. The row and column indices correspond to the positions of the row and column in the iterables provided during table construction. If the table lacks a mapping for a given row and column, the corresponding array element is null.

Subsequent table changes will not modify the array, and vice versa.

Parameters:
valueClass class of values stored in the returned array
  public V[][] toArray(Class<V> valueClass) {
    // Can change to use varargs in JDK 1.6 if we want
    @SuppressWarnings("unchecked"// TODO: safe?
    V[][] copy = (V[][]) Array.newInstance(
        valueClassnew int[] { .size(), .size() });
    for (int i = 0; i < .size(); i++) {
      System.arraycopy([i], 0, copy[i], 0, [i].length);
    }
    return copy;
  }

  
Not supported. Use eraseAll instead.

Deprecated:
Use eraseAll
Throws:
UnsupportedOperationException always
  @Deprecated public void clear() {
    throw new UnsupportedOperationException();
  }

  
Associates the value null with every pair of allowed row and column keys.
  public void eraseAll() {
    for (V[] row : ) {
      Arrays.fill(rownull);
    }
  }

  
Returns true if the provided keys are among the keys provided when the table was constructed.
  public boolean contains(@Nullable Object rowKey, @Nullable Object columnKey) {
    return containsRow(rowKey) && containsColumn(columnKey);
  }

  
Returns true if the provided column key is among the column keys provided when the table was constructed.
  public boolean containsColumn(@Nullable Object columnKey) {
    return .containsKey(columnKey);
  }

  
Returns true if the provided row key is among the row keys provided when the table was constructed.
  public boolean containsRow(@Nullable Object rowKey) {
    return .containsKey(rowKey);
  }
  public boolean containsValue(@Nullable Object value) {
    for (V[] row : ) {
      for (V element : row) {
        if (Objects.equal(valueelement)) {
          return true;
        }
      }
    }
    return false;
  }
  public V get(@Nullable Object rowKey, @Nullable Object columnKey) {
    Integer rowIndex = .get(rowKey);
    Integer columnIndex = .get(columnKey);
    return (rowIndex == null || columnIndex == null)
        ? null : [rowIndex][columnIndex];
  }

  
Always returns false.
  public boolean isEmpty() {
    return false;
  }

  

Throws:
IllegalArgumentException if rowKey is not in .rowKeySet() or columnKey is not in columnKeySet().
  public V put(R rowKey, C columnKey, @Nullable V value) {
    checkNotNull(rowKey);
    checkNotNull(columnKey);
    Integer rowIndex = .get(rowKey);
    checkArgument(rowIndex != null"Row %s not in %s"rowKey);
    Integer columnIndex = .get(columnKey);
    checkArgument(columnIndex != null,
        "Column %s not in %s"columnKey);
    return set(rowIndexcolumnIndexvalue);
  }
  /*
   * TODO(jlevy): Consider creating a merge() method, similar to putAll() but
   * copying non-null values only.
   */

  

If table is an ArrayTable, its null values will be stored in this table, possibly replacing values that were previously non-null.

Throws:
NullPointerException if table has a null key
IllegalArgumentException if any of the provided table's row keys or column keys is not in rowKeySet() or columnKeySet()
  public void putAll(Table<? extends R, ? extends C, ? extends V> table) {
    for (Cell<? extends R, ? extends C, ? extends V> cell : table.cellSet()) {
      put(cell.getRowKey(), cell.getColumnKey(), cell.getValue());
    }
  }

  
Not supported. Use erase instead.

Deprecated:
Use erase
Throws:
UnsupportedOperationException always
  @Deprecated public V remove(Object rowKeyObject columnKey) {
    throw new UnsupportedOperationException();
  }

  
Associates the value null with the specified keys, assuming both keys are valid. If either key is null or isn't among the keys provided during construction, this method has no effect.

This method is equivalent to put(rowKey, columnKey, null) when both provided keys are valid.

Parameters:
rowKey row key of mapping to be erased
columnKey column key of mapping to be erased
Returns:
the value previously associated with the keys, or null if no mapping existed for the keys
  public V erase(@Nullable Object rowKey, @Nullable Object columnKey) {
    Integer rowIndex = .get(rowKey);
    Integer columnIndex = .get(columnKey);
    if (rowIndex == null || columnIndex == null) {
      return null;
    }
    return set(rowIndexcolumnIndexnull);
  }
  // TODO(jlevy): Add eraseRow and eraseColumn methods?
  public int size() {
    return .size() * .size();
  }
  @Override public boolean equals(@Nullable Object obj) {
    if (obj instanceof Table) {
      Table<?, ?, ?> other = (Table<?, ?, ?>) obj;
      return cellSet().equals(other.cellSet());
    }
    return false;
  }
  @Override public int hashCode() {
    return cellSet().hashCode();
  }

  
Returns the string representation rowMap().toString().
  @Override public String toString() {
    return rowMap().toString();
  }
  private transient CellSet cellSet;

  
Returns an unmodifiable set of all row key / column key / value triplets. Changes to the table will update the returned set.

The returned set's iterator traverses the mappings with the first row key, the mappings with the second row key, and so on.

The value in the returned cells may change if the table subsequently changes.

Returns:
set of table cells consisting of row key / column key / value triplets
  public Set<Cell<R, C, V>> cellSet() {
    CellSet set = ;
    return (set == null) ?  = new CellSet() : set;
  }
  private class CellSet extends AbstractSet<Cell<R, C, V>> {
    @Override public Iterator<Cell<R, C, V>> iterator() {
      return new AbstractIndexedListIterator<Cell<R, C, V>>(size()) {
        @Override protected Cell<R, C, V> get(final int index) {
          return new Tables.AbstractCell<R, C, V>() {
            final int rowIndex = index / .size();
            final int columnIndex = index % .size();
            @Override
            public R getRowKey() {
              return .get();
            }
            @Override
            public C getColumnKey() {
              return .get();
            }
            @Override
            public V getValue() {
              return [][];
            }
          };
        }
      };
    }
    @Override public int size() {
      return ArrayTable.this.size();
    }
    @Override public boolean contains(Object obj) {
      if (obj instanceof Cell) {
        Cell<?, ?, ?> cell = (Cell<?, ?, ?>) obj;
        Integer rowIndex = .get(cell.getRowKey());
        Integer columnIndex = .get(cell.getColumnKey());
        return rowIndex != null
            && columnIndex != null
            && Objects.equal([rowIndex][columnIndex], cell.getValue());
      }
      return false;
    }
  }

  
Returns a view of all mappings that have the given column key. If the column key isn't in columnKeySet(), an empty immutable map is returned.

Otherwise, for each row key in rowKeySet(), the returned map associates the row key with the corresponding value in the table. Changes to the returned map will update the underlying table, and vice versa.

Parameters:
columnKey key of column to search for in the table
Returns:
the corresponding map from row keys to values
  public Map<R, V> column(C columnKey) {
    checkNotNull(columnKey);
    Integer columnIndex = .get(columnKey);
    return (columnIndex == null)
        ? ImmutableMap.<R, V>of() : new Column(columnIndex);
  }
  private class Column extends ArrayMap<R, V> {
    final int columnIndex;
    Column(int columnIndex) {
      super();
      this. = columnIndex;
    }
    @Override
    String getKeyRole() {
      return "Row";
    }
    @Override
    V getValue(int index) {
      return at(index);
    }
    @Override
    V setValue(int index, V newValue) {
      return set(indexnewValue);
    }
  }

  
Returns an immutable set of the valid column keys, including those that are associated with null values only.

Returns:
immutable set of column keys
  public ImmutableSet<C> columnKeySet() {
    return .keySet();
  }
  private transient ColumnMap columnMap;
  public Map<C, Map<R, V>> columnMap() {
    ColumnMap map = ;
    return (map == null) ?  = new ColumnMap() : map;
  }
  private class ColumnMap extends ArrayMap<C, Map<R, V>> {
    private ColumnMap() {
      super();
    }
    @Override
    String getKeyRole() {
      return "Column";
    }
    @Override
    Map<R, V> getValue(int index) {
      return new Column(index);
    }
    @Override
    Map<R, V> setValue(int indexMap<R, V> newValue) {
      throw new UnsupportedOperationException();
    }
    @Override
    public Map<R, V> put(C keyMap<R, V> value) {
      throw new UnsupportedOperationException();
    }
  }

  
Returns a view of all mappings that have the given row key. If the row key isn't in rowKeySet(), an empty immutable map is returned.

Otherwise, for each column key in columnKeySet(), the returned map associates the column key with the corresponding value in the table. Changes to the returned map will update the underlying table, and vice versa.

Parameters:
rowKey key of row to search for in the table
Returns:
the corresponding map from column keys to values
  public Map<C, V> row(R rowKey) {
    checkNotNull(rowKey);
    Integer rowIndex = .get(rowKey);
    return (rowIndex == null) ? ImmutableMap.<C, V>of() : new Row(rowIndex);
  }
  private class Row extends ArrayMap<C, V> {
    final int rowIndex;
    Row(int rowIndex) {
      super();
      this. = rowIndex;
    }
    @Override
    String getKeyRole() {
      return "Column";
    }
    @Override
    V getValue(int index) {
      return at(index);
    }
    @Override
    V setValue(int index, V newValue) {
      return set(indexnewValue);
    }
  }

  
Returns an immutable set of the valid row keys, including those that are associated with null values only.

Returns:
immutable set of row keys
  public ImmutableSet<R> rowKeySet() {
    return .keySet();
  }
  private transient RowMap rowMap;
  public Map<R, Map<C, V>> rowMap() {
    RowMap map = ;
    return (map == null) ?  = new RowMap() : map;
  }
  private class RowMap extends ArrayMap<R, Map<C, V>> {
    private RowMap() {
      super();
    }
    @Override
    String getKeyRole() {
      return "Row";
    }
    @Override
    Map<C, V> getValue(int index) {
      return new Row(index);
    }
    @Override
    Map<C, V> setValue(int indexMap<C, V> newValue) {
      throw new UnsupportedOperationException();
    }
    @Override
    public Map<C, V> put(R keyMap<C, V> value) {
      throw new UnsupportedOperationException();
    }
  }
  private transient Collection<V> values;

  
Returns an unmodifiable collection of all values, which may contain duplicates. Changes to the table will update the returned collection.

The returned collection's iterator traverses the values of the first row key, the values of the second row key, and so on.

Returns:
collection of values
  public Collection<V> values() {
    Collection<V> v = ;
    return (v == null) ?  = new Values() : v;
  }
  private class Values extends AbstractCollection<V> {
    @Override public Iterator<V> iterator() {
      return new TransformedIterator<Cell<R, C, V>, V>(cellSet().iterator()) {
        @Override
        V transform(Cell<R, C, V> cell) {
          return cell.getValue();
        }
      };
    }
    @Override public int size() {
      return ArrayTable.this.size();
    }
  }
  private static final long serialVersionUID = 0;
New to GrepCode? Check out our FAQ X