001/* 002 * Copyright (C) 2008 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; 020import static com.google.common.collect.CollectPreconditions.checkNonnegative; 021import static com.google.common.collect.ObjectArrays.checkElementsNotNull; 022 023import com.google.common.annotations.GwtCompatible; 024import com.google.errorprone.annotations.CanIgnoreReturnValue; 025import java.io.Serializable; 026import java.util.AbstractCollection; 027import java.util.ArrayList; 028import java.util.Arrays; 029import java.util.Collection; 030import java.util.Collections; 031import java.util.Iterator; 032import java.util.List; 033import javax.annotation.Nullable; 034 035/** 036 * A {@link Collection} whose contents will never change, and which offers a few additional 037 * guarantees detailed below. 038 * 039 * <p><b>Warning:</b> avoid <i>direct</i> usage of {@link ImmutableCollection} as a type (just as 040 * with {@link Collection} itself). Prefer subtypes such as {@link ImmutableSet} or {@link 041 * ImmutableList}, which have well-defined {@link #equals} semantics, thus avoiding a common source 042 * of bugs and confusion. 043 * 044 * <h3>About <i>all</i> {@code Immutable-} collections</h3> 045 * 046 * <p>The remainder of this documentation applies to every public {@code Immutable-} type in this 047 * package, whether it is a subtype of {@code ImmutableCollection} or not. 048 * 049 * <h4>Guarantees</h4> 050 * 051 * <p>Each makes the following guarantees: 052 * 053 * <ul> 054 * <li><b>Shallow immutability.</b> Elements can never be added, removed or replaced in this 055 * collection. This is a stronger guarantee than that of 056 * {@link Collections#unmodifiableCollection}, whose contents change whenever the wrapped 057 * collection is modified. 058 * <li><b>Null-hostility.</b> This collection will never contain a null element. 059 * <li><b>Deterministic iteration.</b> The iteration order is always well-defined, depending on how 060 * the collection was created (see the appropriate factory method for details). View collections 061 * such as {@link ImmutableMultiset#elementSet} iterate in the same order as the parent, except 062 * as noted. 063 * <li><b>Thread safety.</b> It is safe to access this collection concurrently from multiple 064 * threads. 065 * <li><b>Integrity.</b> This type cannot be subclassed outside this package (which would allow 066 * these guarantees to be violated). 067 * </ul> 068 * 069 * <h4>"Interfaces", not implementations</h4> 070 * 071 * <p>Each public class, such as {@link ImmutableSet}, is a <i>type</i> offering meaningful 072 * behavioral guarantees -- not merely a specific <i>implementation</i> as in the case of, say, 073 * {@link ArrayList}. You should treat them as interfaces in every important sense of the word. 074 * 075 * <p>For field types and method return types, you should generally use the immutable type (such as 076 * {@link ImmutableList}) instead of the general collection interface type (such as {@link List}). 077 * This communicates to your callers all of the semantic guarantees listed above, which is almost 078 * always very useful information. 079 * 080 * <p>On the other hand, a <i>parameter</i> type of {@link ImmutableList} is generally a nuisance to 081 * callers. Instead, accept {@link Iterable} and have your method or constructor body pass it to the 082 * appropriate {@code copyOf} method itself. 083 * 084 * <h4>Creation</h4> 085 * 086 * <p>Except for logically "abstract" types like {@code ImmutableCollection} itself, each {@code 087 * Immutable} type provides the static operations you need to obtain instances of that type. These 088 * usually include: 089 * 090 * <ul> 091 * <li>Static methods named {@code of}, accepting an explicit list of elements or entries. 092 * <li>Static methods named {@code copyOf} (or {@code copyOfSorted}), accepting an existing 093 * collection whose contents should be copied. 094 * <li>A static nested {@code Builder} class which can be used to populate a new immutable instance. 095 * </ul> 096 * 097 * <h4>Warnings</h4> 098 * 099 * <ul> 100 * <li><b>Warning:</b> as with any collection, it is almost always a bad idea to modify an element 101 * (in a way that affects its {@link Object#equals} behavior) while it is contained in a 102 * collection. Undefined behavior and bugs will result. It's generally best to avoid using 103 * mutable objects as elements at all, as many users may expect your "immutable" object to be 104 * <i>deeply</i> immutable. 105 * </ul> 106 * 107 * <h4>Performance notes</h4> 108 * 109 * <ul> 110 * <li>Implementations can be generally assumed to prioritize memory efficiency, then speed of 111 * access, and lastly speed of creation. 112 * <li>The {@code copyOf} methods will sometimes recognize that the actual copy operation is 113 * unnecessary; for example, {@code copyOf(copyOf(anArrayList))} should copy the data only once. 114 * This reduces the expense of habitually making defensive copies at API boundaries. However, 115 * the precise conditions for skipping the copy operation are undefined. 116 * <li><b>Warning:</b> a view collection such as {@link ImmutableMap#keySet} or {@link 117 * ImmutableList#subList} may retain a reference to the entire data set, preventing it from 118 * being garbage collected. If some of the data is no longer reachable through other means, this 119 * constitutes a memory leak. Pass the view collection to the appropriate {@code copyOf} method 120 * to obtain a correctly-sized copy. 121 * <li>The performance of using the associated {@code Builder} class can be assumed to be 122 * no worse, and possibly better, than creating a mutable collection and copying it. 123 * <li>Implementations generally do not cache hash codes. If your element or key type has a slow 124 * {@code hashCode} implementation, it should cache it itself. 125 * </ul> 126 * 127 * <h4>Example usage</h4> 128 * 129 * <pre> {@code 130 * 131 * class Foo { 132 * private static final ImmutableSet<String> RESERVED_CODES = 133 * ImmutableSet.of("AZ", "CQ", "ZX"); 134 * 135 * private final ImmutableSet<String> codes; 136 * 137 * public Foo(Iterable<String> codes) { 138 * this.codes = ImmutableSet.copyOf(codes); 139 * checkArgument(Collections.disjoint(this.codes, RESERVED_CODES)); 140 * } 141 * }}</pre> 142 * 143 * <h3>See also</h3> 144 * 145 * <p>See the Guava User Guide article on <a href= 146 * "https://github.com/google/guava/wiki/ImmutableCollectionsExplained"> 147 * immutable collections</a>. 148 * 149 * @since 2.0 150 */ 151@GwtCompatible(emulated = true) 152@SuppressWarnings("serial") // we're overriding default serialization 153// TODO(kevinb): I think we should push everything down to "BaseImmutableCollection" or something, 154// just to do everything we can to emphasize the "practically an interface" nature of this class. 155public abstract class ImmutableCollection<E> extends AbstractCollection<E> implements Serializable { 156 157 ImmutableCollection() {} 158 159 /** 160 * Returns an unmodifiable iterator across the elements in this collection. 161 */ 162 @Override 163 public abstract UnmodifiableIterator<E> iterator(); 164 165 private static final Object[] EMPTY_ARRAY = {}; 166 167 @Override 168 public final Object[] toArray() { 169 int size = size(); 170 if (size == 0) { 171 return EMPTY_ARRAY; 172 } 173 Object[] result = new Object[size]; 174 copyIntoArray(result, 0); 175 return result; 176 } 177 178 @CanIgnoreReturnValue 179 @Override 180 public final <T> T[] toArray(T[] other) { 181 checkNotNull(other); 182 int size = size(); 183 if (other.length < size) { 184 other = ObjectArrays.newArray(other, size); 185 } else if (other.length > size) { 186 other[size] = null; 187 } 188 copyIntoArray(other, 0); 189 return other; 190 } 191 192 @Override 193 public abstract boolean contains(@Nullable Object object); 194 195 /** 196 * Guaranteed to throw an exception and leave the collection unmodified. 197 * 198 * @throws UnsupportedOperationException always 199 * @deprecated Unsupported operation. 200 */ 201 @CanIgnoreReturnValue 202 @Deprecated 203 @Override 204 public final boolean add(E e) { 205 throw new UnsupportedOperationException(); 206 } 207 208 /** 209 * Guaranteed to throw an exception and leave the collection unmodified. 210 * 211 * @throws UnsupportedOperationException always 212 * @deprecated Unsupported operation. 213 */ 214 @CanIgnoreReturnValue 215 @Deprecated 216 @Override 217 public final boolean remove(Object object) { 218 throw new UnsupportedOperationException(); 219 } 220 221 /** 222 * Guaranteed to throw an exception and leave the collection unmodified. 223 * 224 * @throws UnsupportedOperationException always 225 * @deprecated Unsupported operation. 226 */ 227 @CanIgnoreReturnValue 228 @Deprecated 229 @Override 230 public final boolean addAll(Collection<? extends E> newElements) { 231 throw new UnsupportedOperationException(); 232 } 233 234 /** 235 * Guaranteed to throw an exception and leave the collection unmodified. 236 * 237 * @throws UnsupportedOperationException always 238 * @deprecated Unsupported operation. 239 */ 240 @CanIgnoreReturnValue 241 @Deprecated 242 @Override 243 public final boolean removeAll(Collection<?> oldElements) { 244 throw new UnsupportedOperationException(); 245 } 246 247 /** 248 * Guaranteed to throw an exception and leave the collection unmodified. 249 * 250 * @throws UnsupportedOperationException always 251 * @deprecated Unsupported operation. 252 */ 253 @CanIgnoreReturnValue 254 @Deprecated 255 @Override 256 public final boolean retainAll(Collection<?> elementsToKeep) { 257 throw new UnsupportedOperationException(); 258 } 259 260 /** 261 * Guaranteed to throw an exception and leave the collection unmodified. 262 * 263 * @throws UnsupportedOperationException always 264 * @deprecated Unsupported operation. 265 */ 266 @Deprecated 267 @Override 268 public final void clear() { 269 throw new UnsupportedOperationException(); 270 } 271 272 /** 273 * Returns an {@code ImmutableList} containing the same elements, in the same order, as this 274 * collection. 275 * 276 * <p><b>Performance note:</b> in most cases this method can return quickly without actually 277 * copying anything. The exact circumstances under which the copy is performed are undefined and 278 * subject to change. 279 * 280 * @since 2.0 281 */ 282 public ImmutableList<E> asList() { 283 return isEmpty() ? ImmutableList.<E>of() : ImmutableList.<E>asImmutableList(toArray()); 284 } 285 286 /** 287 * Returns {@code true} if this immutable collection's implementation contains references to 288 * user-created objects that aren't accessible via this collection's methods. This is generally 289 * used to determine whether {@code copyOf} implementations should make an explicit copy to avoid 290 * memory leaks. 291 */ 292 abstract boolean isPartialView(); 293 294 /** 295 * Copies the contents of this immutable collection into the specified array at the specified 296 * offset. Returns {@code offset + size()}. 297 */ 298 @CanIgnoreReturnValue 299 int copyIntoArray(Object[] dst, int offset) { 300 for (E e : this) { 301 dst[offset++] = e; 302 } 303 return offset; 304 } 305 306 Object writeReplace() { 307 // We serialize by default to ImmutableList, the simplest thing that works. 308 return new ImmutableList.SerializedForm(toArray()); 309 } 310 311 /** 312 * Abstract base class for builders of {@link ImmutableCollection} types. 313 * 314 * @since 10.0 315 */ 316 public abstract static class Builder<E> { 317 static final int DEFAULT_INITIAL_CAPACITY = 4; 318 319 static int expandedCapacity(int oldCapacity, int minCapacity) { 320 if (minCapacity < 0) { 321 throw new AssertionError("cannot store more than MAX_VALUE elements"); 322 } 323 // careful of overflow! 324 int newCapacity = oldCapacity + (oldCapacity >> 1) + 1; 325 if (newCapacity < minCapacity) { 326 newCapacity = Integer.highestOneBit(minCapacity - 1) << 1; 327 } 328 if (newCapacity < 0) { 329 newCapacity = Integer.MAX_VALUE; 330 // guaranteed to be >= newCapacity 331 } 332 return newCapacity; 333 } 334 335 Builder() {} 336 337 /** 338 * Adds {@code element} to the {@code ImmutableCollection} being built. 339 * 340 * <p>Note that each builder class covariantly returns its own type from 341 * this method. 342 * 343 * @param element the element to add 344 * @return this {@code Builder} instance 345 * @throws NullPointerException if {@code element} is null 346 */ 347 @CanIgnoreReturnValue 348 public abstract Builder<E> add(E element); 349 350 /** 351 * Adds each element of {@code elements} to the {@code ImmutableCollection} 352 * being built. 353 * 354 * <p>Note that each builder class overrides this method in order to 355 * covariantly return its own type. 356 * 357 * @param elements the elements to add 358 * @return this {@code Builder} instance 359 * @throws NullPointerException if {@code elements} is null or contains a 360 * null element 361 */ 362 @CanIgnoreReturnValue 363 public Builder<E> add(E... elements) { 364 for (E element : elements) { 365 add(element); 366 } 367 return this; 368 } 369 370 /** 371 * Adds each element of {@code elements} to the {@code ImmutableCollection} 372 * being built. 373 * 374 * <p>Note that each builder class overrides this method in order to 375 * covariantly return its own type. 376 * 377 * @param elements the elements to add 378 * @return this {@code Builder} instance 379 * @throws NullPointerException if {@code elements} is null or contains a 380 * null element 381 */ 382 @CanIgnoreReturnValue 383 public Builder<E> addAll(Iterable<? extends E> elements) { 384 for (E element : elements) { 385 add(element); 386 } 387 return this; 388 } 389 390 /** 391 * Adds each element of {@code elements} to the {@code ImmutableCollection} 392 * being built. 393 * 394 * <p>Note that each builder class overrides this method in order to 395 * covariantly return its own type. 396 * 397 * @param elements the elements to add 398 * @return this {@code Builder} instance 399 * @throws NullPointerException if {@code elements} is null or contains a 400 * null element 401 */ 402 @CanIgnoreReturnValue 403 public Builder<E> addAll(Iterator<? extends E> elements) { 404 while (elements.hasNext()) { 405 add(elements.next()); 406 } 407 return this; 408 } 409 410 /** 411 * Returns a newly-created {@code ImmutableCollection} of the appropriate 412 * type, containing the elements provided to this builder. 413 * 414 * <p>Note that each builder class covariantly returns the appropriate type 415 * of {@code ImmutableCollection} from this method. 416 */ 417 public abstract ImmutableCollection<E> build(); 418 } 419 420 abstract static class ArrayBasedBuilder<E> extends ImmutableCollection.Builder<E> { 421 Object[] contents; 422 int size; 423 boolean forceCopy; 424 425 ArrayBasedBuilder(int initialCapacity) { 426 checkNonnegative(initialCapacity, "initialCapacity"); 427 this.contents = new Object[initialCapacity]; 428 this.size = 0; 429 } 430 431 /* 432 * Expand the absolute capacity of the builder so it can accept at least the specified number of 433 * elements without being resized. Also, if we've already built a collection backed by the 434 * current array, create a new array. 435 */ 436 private void getReadyToExpandTo(int minCapacity) { 437 if (contents.length < minCapacity) { 438 this.contents = 439 Arrays.copyOf( 440 this.contents, expandedCapacity(contents.length, minCapacity)); 441 forceCopy = false; 442 } else if (forceCopy) { 443 this.contents = contents.clone(); 444 forceCopy = false; 445 } 446 } 447 448 @CanIgnoreReturnValue 449 @Override 450 public ArrayBasedBuilder<E> add(E element) { 451 checkNotNull(element); 452 getReadyToExpandTo(size + 1); 453 contents[size++] = element; 454 return this; 455 } 456 457 @CanIgnoreReturnValue 458 @Override 459 public Builder<E> add(E... elements) { 460 checkElementsNotNull(elements); 461 getReadyToExpandTo(size + elements.length); 462 System.arraycopy(elements, 0, contents, size, elements.length); 463 size += elements.length; 464 return this; 465 } 466 467 @CanIgnoreReturnValue 468 @Override 469 public Builder<E> addAll(Iterable<? extends E> elements) { 470 if (elements instanceof Collection) { 471 Collection<?> collection = (Collection<?>) elements; 472 getReadyToExpandTo(size + collection.size()); 473 } 474 super.addAll(elements); 475 return this; 476 } 477 } 478}