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.checkNotNull; 020 021import com.google.common.annotations.GwtCompatible; 022import com.google.common.base.MoreObjects; 023import com.google.errorprone.annotations.CanIgnoreReturnValue; 024import com.google.errorprone.annotations.DoNotMock; 025import java.io.Serializable; 026import java.util.Comparator; 027import java.util.Iterator; 028import java.util.List; 029import java.util.Map; 030import org.checkerframework.checker.nullness.compatqual.MonotonicNonNullDecl; 031import org.checkerframework.checker.nullness.compatqual.NullableDecl; 032 033/** 034 * A {@link Table} whose contents will never change, with many other important properties detailed 035 * at {@link ImmutableCollection}. 036 * 037 * <p>See the Guava User Guide article on <a href= 038 * "https://github.com/google/guava/wiki/ImmutableCollectionsExplained"> immutable collections</a>. 039 * 040 * @author Gregory Kick 041 * @since 11.0 042 */ 043@GwtCompatible 044public abstract class ImmutableTable<R, C, V> extends AbstractTable<R, C, V> 045 implements Serializable { 046 /** Returns an empty immutable table. */ 047 @SuppressWarnings("unchecked") 048 public static <R, C, V> ImmutableTable<R, C, V> of() { 049 return (ImmutableTable<R, C, V>) SparseImmutableTable.EMPTY; 050 } 051 052 /** Returns an immutable table containing a single cell. */ 053 public static <R, C, V> ImmutableTable<R, C, V> of(R rowKey, C columnKey, V value) { 054 return new SingletonImmutableTable<>(rowKey, columnKey, value); 055 } 056 057 /** 058 * Returns an immutable copy of the provided table. 059 * 060 * <p>The {@link Table#cellSet()} iteration order of the provided table determines the iteration 061 * ordering of all views in the returned table. Note that some views of the original table and the 062 * copied table may have different iteration orders. For more control over the ordering, create a 063 * {@link Builder} and call {@link Builder#orderRowsBy}, {@link Builder#orderColumnsBy}, and 064 * {@link Builder#putAll} 065 * 066 * <p>Despite the method name, this method attempts to avoid actually copying the data when it is 067 * safe to do so. The exact circumstances under which a copy will or will not be performed are 068 * undocumented and subject to change. 069 */ 070 public static <R, C, V> ImmutableTable<R, C, V> copyOf( 071 Table<? extends R, ? extends C, ? extends V> table) { 072 if (table instanceof ImmutableTable) { 073 @SuppressWarnings("unchecked") 074 ImmutableTable<R, C, V> parameterizedTable = (ImmutableTable<R, C, V>) table; 075 return parameterizedTable; 076 } else { 077 return copyOf(table.cellSet()); 078 } 079 } 080 081 private static <R, C, V> ImmutableTable<R, C, V> copyOf( 082 Iterable<? extends Cell<? extends R, ? extends C, ? extends V>> cells) { 083 ImmutableTable.Builder<R, C, V> builder = ImmutableTable.builder(); 084 for (Cell<? extends R, ? extends C, ? extends V> cell : cells) { 085 builder.put(cell); 086 } 087 return builder.build(); 088 } 089 090 /** 091 * Returns a new builder. The generated builder is equivalent to the builder created by the {@link 092 * Builder#Builder() ImmutableTable.Builder()} constructor. 093 */ 094 public static <R, C, V> Builder<R, C, V> builder() { 095 return new Builder<>(); 096 } 097 098 /** 099 * Verifies that {@code rowKey}, {@code columnKey} and {@code value} are non-null, and returns a 100 * new entry with those values. 101 */ 102 static <R, C, V> Cell<R, C, V> cellOf(R rowKey, C columnKey, V value) { 103 return Tables.immutableCell( 104 checkNotNull(rowKey, "rowKey"), 105 checkNotNull(columnKey, "columnKey"), 106 checkNotNull(value, "value")); 107 } 108 109 /** 110 * A builder for creating immutable table instances, especially {@code public static final} tables 111 * ("constant tables"). Example: 112 * 113 * <pre>{@code 114 * static final ImmutableTable<Integer, Character, String> SPREADSHEET = 115 * new ImmutableTable.Builder<Integer, Character, String>() 116 * .put(1, 'A', "foo") 117 * .put(1, 'B', "bar") 118 * .put(2, 'A', "baz") 119 * .build(); 120 * }</pre> 121 * 122 * <p>By default, the order in which cells are added to the builder determines the iteration 123 * ordering of all views in the returned table, with {@link #putAll} following the {@link 124 * Table#cellSet()} iteration order. However, if {@link #orderRowsBy} or {@link #orderColumnsBy} 125 * is called, the views are sorted by the supplied comparators. 126 * 127 * <p>For empty or single-cell immutable tables, {@link #of()} and {@link #of(Object, Object, 128 * Object)} are even more convenient. 129 * 130 * <p>Builder instances can be reused - it is safe to call {@link #build} multiple times to build 131 * multiple tables in series. Each table is a superset of the tables created before it. 132 * 133 * @since 11.0 134 */ 135 @DoNotMock 136 public static final class Builder<R, C, V> { 137 private final List<Cell<R, C, V>> cells = Lists.newArrayList(); 138 @MonotonicNonNullDecl private Comparator<? super R> rowComparator; 139 @MonotonicNonNullDecl private Comparator<? super C> columnComparator; 140 141 /** 142 * Creates a new builder. The returned builder is equivalent to the builder generated by {@link 143 * ImmutableTable#builder}. 144 */ 145 public Builder() {} 146 147 /** Specifies the ordering of the generated table's rows. */ 148 @CanIgnoreReturnValue 149 public Builder<R, C, V> orderRowsBy(Comparator<? super R> rowComparator) { 150 this.rowComparator = checkNotNull(rowComparator, "rowComparator"); 151 return this; 152 } 153 154 /** Specifies the ordering of the generated table's columns. */ 155 @CanIgnoreReturnValue 156 public Builder<R, C, V> orderColumnsBy(Comparator<? super C> columnComparator) { 157 this.columnComparator = checkNotNull(columnComparator, "columnComparator"); 158 return this; 159 } 160 161 /** 162 * Associates the ({@code rowKey}, {@code columnKey}) pair with {@code value} in the built 163 * table. Duplicate key pairs are not allowed and will cause {@link #build} to fail. 164 */ 165 @CanIgnoreReturnValue 166 public Builder<R, C, V> put(R rowKey, C columnKey, V value) { 167 cells.add(cellOf(rowKey, columnKey, value)); 168 return this; 169 } 170 171 /** 172 * Adds the given {@code cell} to the table, making it immutable if necessary. Duplicate key 173 * pairs are not allowed and will cause {@link #build} to fail. 174 */ 175 @CanIgnoreReturnValue 176 public Builder<R, C, V> put(Cell<? extends R, ? extends C, ? extends V> cell) { 177 if (cell instanceof Tables.ImmutableCell) { 178 checkNotNull(cell.getRowKey(), "row"); 179 checkNotNull(cell.getColumnKey(), "column"); 180 checkNotNull(cell.getValue(), "value"); 181 @SuppressWarnings("unchecked") // all supported methods are covariant 182 Cell<R, C, V> immutableCell = (Cell<R, C, V>) cell; 183 cells.add(immutableCell); 184 } else { 185 put(cell.getRowKey(), cell.getColumnKey(), cell.getValue()); 186 } 187 return this; 188 } 189 190 /** 191 * Associates all of the given table's keys and values in the built table. Duplicate row key 192 * column key pairs are not allowed, and will cause {@link #build} to fail. 193 * 194 * @throws NullPointerException if any key or value in {@code table} is null 195 */ 196 @CanIgnoreReturnValue 197 public Builder<R, C, V> putAll(Table<? extends R, ? extends C, ? extends V> table) { 198 for (Cell<? extends R, ? extends C, ? extends V> cell : table.cellSet()) { 199 put(cell); 200 } 201 return this; 202 } 203 204 /** 205 * Returns a newly-created immutable table. 206 * 207 * @throws IllegalArgumentException if duplicate key pairs were added 208 */ 209 public ImmutableTable<R, C, V> build() { 210 int size = cells.size(); 211 switch (size) { 212 case 0: 213 return of(); 214 case 1: 215 return new SingletonImmutableTable<>(Iterables.getOnlyElement(cells)); 216 default: 217 return RegularImmutableTable.forCells(cells, rowComparator, columnComparator); 218 } 219 } 220 } 221 222 ImmutableTable() {} 223 224 @Override 225 public ImmutableSet<Cell<R, C, V>> cellSet() { 226 return (ImmutableSet<Cell<R, C, V>>) super.cellSet(); 227 } 228 229 @Override 230 abstract ImmutableSet<Cell<R, C, V>> createCellSet(); 231 232 @Override 233 final UnmodifiableIterator<Cell<R, C, V>> cellIterator() { 234 throw new AssertionError("should never be called"); 235 } 236 237 @Override 238 public ImmutableCollection<V> values() { 239 return (ImmutableCollection<V>) super.values(); 240 } 241 242 @Override 243 abstract ImmutableCollection<V> createValues(); 244 245 @Override 246 final Iterator<V> valuesIterator() { 247 throw new AssertionError("should never be called"); 248 } 249 250 /** 251 * {@inheritDoc} 252 * 253 * @throws NullPointerException if {@code columnKey} is {@code null} 254 */ 255 @Override 256 public ImmutableMap<R, V> column(C columnKey) { 257 checkNotNull(columnKey, "columnKey"); 258 return MoreObjects.firstNonNull( 259 (ImmutableMap<R, V>) columnMap().get(columnKey), ImmutableMap.<R, V>of()); 260 } 261 262 @Override 263 public ImmutableSet<C> columnKeySet() { 264 return columnMap().keySet(); 265 } 266 267 /** 268 * {@inheritDoc} 269 * 270 * <p>The value {@code Map<R, V>} instances in the returned map are {@link ImmutableMap} instances 271 * as well. 272 */ 273 @Override 274 public abstract ImmutableMap<C, Map<R, V>> columnMap(); 275 276 /** 277 * {@inheritDoc} 278 * 279 * @throws NullPointerException if {@code rowKey} is {@code null} 280 */ 281 @Override 282 public ImmutableMap<C, V> row(R rowKey) { 283 checkNotNull(rowKey, "rowKey"); 284 return MoreObjects.firstNonNull( 285 (ImmutableMap<C, V>) rowMap().get(rowKey), ImmutableMap.<C, V>of()); 286 } 287 288 @Override 289 public ImmutableSet<R> rowKeySet() { 290 return rowMap().keySet(); 291 } 292 293 /** 294 * {@inheritDoc} 295 * 296 * <p>The value {@code Map<C, V>} instances in the returned map are {@link ImmutableMap} instances 297 * as well. 298 */ 299 @Override 300 public abstract ImmutableMap<R, Map<C, V>> rowMap(); 301 302 @Override 303 public boolean contains(@NullableDecl Object rowKey, @NullableDecl Object columnKey) { 304 return get(rowKey, columnKey) != null; 305 } 306 307 @Override 308 public boolean containsValue(@NullableDecl Object value) { 309 return values().contains(value); 310 } 311 312 /** 313 * Guaranteed to throw an exception and leave the table unmodified. 314 * 315 * @throws UnsupportedOperationException always 316 * @deprecated Unsupported operation. 317 */ 318 @Deprecated 319 @Override 320 public final void clear() { 321 throw new UnsupportedOperationException(); 322 } 323 324 /** 325 * Guaranteed to throw an exception and leave the table unmodified. 326 * 327 * @throws UnsupportedOperationException always 328 * @deprecated Unsupported operation. 329 */ 330 @CanIgnoreReturnValue 331 @Deprecated 332 @Override 333 public final V put(R rowKey, C columnKey, V value) { 334 throw new UnsupportedOperationException(); 335 } 336 337 /** 338 * Guaranteed to throw an exception and leave the table unmodified. 339 * 340 * @throws UnsupportedOperationException always 341 * @deprecated Unsupported operation. 342 */ 343 @Deprecated 344 @Override 345 public final void putAll(Table<? extends R, ? extends C, ? extends V> table) { 346 throw new UnsupportedOperationException(); 347 } 348 349 /** 350 * Guaranteed to throw an exception and leave the table unmodified. 351 * 352 * @throws UnsupportedOperationException always 353 * @deprecated Unsupported operation. 354 */ 355 @CanIgnoreReturnValue 356 @Deprecated 357 @Override 358 public final V remove(Object rowKey, Object columnKey) { 359 throw new UnsupportedOperationException(); 360 } 361 362 /** Creates the common serialized form for this table. */ 363 abstract SerializedForm createSerializedForm(); 364 365 /** 366 * Serialized type for all ImmutableTable instances. It captures the logical contents and 367 * preserves iteration order of all views. 368 */ 369 static final class SerializedForm implements Serializable { 370 private final Object[] rowKeys; 371 private final Object[] columnKeys; 372 373 private final Object[] cellValues; 374 private final int[] cellRowIndices; 375 private final int[] cellColumnIndices; 376 377 private SerializedForm( 378 Object[] rowKeys, 379 Object[] columnKeys, 380 Object[] cellValues, 381 int[] cellRowIndices, 382 int[] cellColumnIndices) { 383 this.rowKeys = rowKeys; 384 this.columnKeys = columnKeys; 385 this.cellValues = cellValues; 386 this.cellRowIndices = cellRowIndices; 387 this.cellColumnIndices = cellColumnIndices; 388 } 389 390 static SerializedForm create( 391 ImmutableTable<?, ?, ?> table, int[] cellRowIndices, int[] cellColumnIndices) { 392 return new SerializedForm( 393 table.rowKeySet().toArray(), 394 table.columnKeySet().toArray(), 395 table.values().toArray(), 396 cellRowIndices, 397 cellColumnIndices); 398 } 399 400 Object readResolve() { 401 if (cellValues.length == 0) { 402 return of(); 403 } 404 if (cellValues.length == 1) { 405 return of(rowKeys[0], columnKeys[0], cellValues[0]); 406 } 407 ImmutableList.Builder<Cell<Object, Object, Object>> cellListBuilder = 408 new ImmutableList.Builder<>(cellValues.length); 409 for (int i = 0; i < cellValues.length; i++) { 410 cellListBuilder.add( 411 cellOf(rowKeys[cellRowIndices[i]], columnKeys[cellColumnIndices[i]], cellValues[i])); 412 } 413 return RegularImmutableTable.forOrderedComponents( 414 cellListBuilder.build(), ImmutableSet.copyOf(rowKeys), ImmutableSet.copyOf(columnKeys)); 415 } 416 417 private static final long serialVersionUID = 0; 418 } 419 420 final Object writeReplace() { 421 return createSerializedForm(); 422 } 423}