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