Class ImmutableCollection<E>
- java.lang.Object
-
- java.util.AbstractCollection<E>
-
- com.google.common.collect.ImmutableCollection<E>
-
- All Implemented Interfaces:
Serializable
,Iterable<E>
,Collection<E>
- Direct Known Subclasses:
ImmutableList
,ImmutableMultiset
,ImmutableSet
@DoNotMock("Use ImmutableList.of or another implementation") @GwtCompatible(emulated=true) public abstract class ImmutableCollection<E> extends AbstractCollection<E> implements Serializable
ACollection
whose contents will never change, and which offers a few additional guarantees detailed below.Warning: avoid direct usage of
ImmutableCollection
as a type (just as withCollection
itself). Prefer subtypes such asImmutableSet
orImmutableList
, which have well-definedObject.equals(java.lang.Object)
semantics, thus avoiding a common source of bugs and confusion.About all
Immutable-
collectionsThe remainder of this documentation applies to every public
Immutable-
type in this package, whether it is a subtype ofImmutableCollection
or not.Guarantees
Each makes the following guarantees:
- Shallow immutability. Elements can never be added, removed or replaced in this
collection. This is a stronger guarantee than that of
Collections.unmodifiableCollection(java.util.Collection<? extends T>)
, whose contents change whenever the wrapped collection is modified. - Null-hostility. This collection will never contain a null element.
- Deterministic iteration. The iteration order is always well-defined, depending on
how the collection was created. Typically this is insertion order unless an explicit
ordering is otherwise specified (e.g.
ImmutableSortedSet.naturalOrder()
). See the appropriate factory method for details. View collections such asImmutableMultiset.elementSet()
iterate in the same order as the parent, except as noted. - Thread safety. It is safe to access this collection concurrently from multiple threads.
- Integrity. This type cannot be subclassed outside this package (which would allow these guarantees to be violated).
"Interfaces", not implementations
These are classes instead of interfaces to prevent external subtyping, but should be thought of as interfaces in every important sense. Each public class such as
ImmutableSet
is a type offering meaningful behavioral guarantees. This is substantially different from the case of (say)HashSet
, which is an implementation, with semantics that were largely defined by its supertype.For field types and method return types, you should generally use the immutable type (such as
ImmutableList
) instead of the general collection interface type (such asList
). This communicates to your callers all of the semantic guarantees listed above, which is almost always very useful information.On the other hand, a parameter type of
ImmutableList
is generally a nuisance to callers. Instead, acceptIterable
and have your method or constructor body pass it to the appropriatecopyOf
method itself.Expressing the immutability guarantee directly in the type that user code references is a powerful advantage. Although Java offers certain immutable collection factory methods, such as
Collections.singleton(Object)
andSet.of
, we recommend using these classes instead for this reason (as well as for consistency).Creation
Except for logically "abstract" types like
ImmutableCollection
itself, eachImmutable
type provides the static operations you need to obtain instances of that type. These usually include:- Static methods named
of
, accepting an explicit list of elements or entries. - Static methods named
copyOf
(orcopyOfSorted
), accepting an existing collection whose contents should be copied. - A static nested
Builder
class which can be used to populate a new immutable instance.
Warnings
- Warning: as with any collection, it is almost always a bad idea to modify an element
(in a way that affects its
Object.equals(java.lang.Object)
behavior) while it is contained in a collection. Undefined behavior and bugs will result. It's generally best to avoid using mutable objects as elements at all, as many users may expect your "immutable" object to be deeply immutable.
Performance notes
- Implementations can be generally assumed to prioritize memory efficiency, then speed of access, and lastly speed of creation.
- The
copyOf
methods will sometimes recognize that the actual copy operation is unnecessary; for example,copyOf(copyOf(anArrayList))
should copy the data only once. This reduces the expense of habitually making defensive copies at API boundaries. However, the precise conditions for skipping the copy operation are undefined. - Warning: a view collection such as
ImmutableMap.keySet
orImmutableList.subList(int, int)
may retain a reference to the entire data set, preventing it from being garbage collected. If some of the data is no longer reachable through other means, this constitutes a memory leak. Pass the view collection to the appropriatecopyOf
method to obtain a correctly-sized copy. - The performance of using the associated
Builder
class can be assumed to be no worse, and possibly better, than creating a mutable collection and copying it. - Implementations generally do not cache hash codes. If your element or key type has a slow
hashCode
implementation, it should cache it itself.
Example usage
class Foo { private static final ImmutableSet<String> RESERVED_CODES = ImmutableSet.of("AZ", "CQ", "ZX"); private final ImmutableSet<String> codes; public Foo(Iterable<String> codes) { this.codes = ImmutableSet.copyOf(codes); checkArgument(Collections.disjoint(this.codes, RESERVED_CODES)); } }
See also
See the Guava User Guide article on immutable collections.
- Since:
- 2.0
- See Also:
- Serialized Form
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static class
ImmutableCollection.Builder<E>
Abstract base class for builders ofImmutableCollection
types.
-
Method Summary
All Methods Instance Methods Abstract Methods Concrete Methods Deprecated Methods Modifier and Type Method Description boolean
add(E e)
Deprecated.Unsupported operation.boolean
addAll(Collection<? extends E> newElements)
Deprecated.Unsupported operation.ImmutableList<E>
asList()
Returns anImmutableList
containing the same elements, in the same order, as this collection.void
clear()
Deprecated.Unsupported operation.abstract boolean
contains(Object object)
Returnstrue
if this collection contains the specified element.abstract UnmodifiableIterator<E>
iterator()
Returns an unmodifiable iterator across the elements in this collection.boolean
remove(Object object)
Deprecated.Unsupported operation.boolean
removeAll(Collection<?> oldElements)
Deprecated.Unsupported operation.boolean
removeIf(Predicate<? super E> filter)
Deprecated.Unsupported operation.boolean
retainAll(Collection<?> elementsToKeep)
Deprecated.Unsupported operation.Spliterator<E>
spliterator()
Creates aSpliterator
over the elements in this collection.Object[]
toArray()
Returns an array containing all of the elements in this collection.<T extends @Nullable Object>
T[]toArray(T[] other)
Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array.-
Methods inherited from class java.util.AbstractCollection
containsAll, isEmpty, size, toString
-
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
-
Methods inherited from interface java.util.Collection
equals, hashCode, parallelStream, stream, toArray
-
-
-
-
Method Detail
-
iterator
public abstract UnmodifiableIterator<E> iterator()
Returns an unmodifiable iterator across the elements in this collection.- Specified by:
iterator
in interfaceCollection<E>
- Specified by:
iterator
in interfaceIterable<E>
- Specified by:
iterator
in classAbstractCollection<E>
- Returns:
- an iterator over the elements contained in this collection
-
spliterator
public Spliterator<E> spliterator()
Description copied from interface:java.util.Collection
Creates aSpliterator
over the elements in this collection. Implementations should document characteristic values reported by the spliterator. Such characteristic values are not required to be reported if the spliterator reportsSpliterator.SIZED
and this collection contains no elements.The default implementation should be overridden by subclasses that can return a more efficient spliterator. In order to preserve expected laziness behavior for the
Collection.stream()
andCollection.parallelStream()
methods, spliterators should either have the characteristic ofIMMUTABLE
orCONCURRENT
, or be late-binding. If none of these is practical, the overriding class should describe the spliterator's documented policy of binding and structural interference, and should override theCollection.stream()
andCollection.parallelStream()
methods to create streams using aSupplier
of the spliterator, as in:Stream<E> s = StreamSupport.stream(() -> spliterator(), spliteratorCharacteristics)
These requirements ensure that streams produced by the
Collection.stream()
andCollection.parallelStream()
methods will reflect the contents of the collection as of initiation of the terminal stream operation.- Specified by:
spliterator
in interfaceCollection<E>
- Specified by:
spliterator
in interfaceIterable<E>
- Returns:
- a
Spliterator
over the elements in this collection
-
toArray
public final Object[] toArray()
Description copied from class:java.util.AbstractCollection
Returns an array containing all of the elements in this collection. If this collection makes any guarantees as to what order its elements are returned by its iterator, this method must return the elements in the same order. The returned array's runtime component type isObject
.The returned array will be "safe" in that no references to it are maintained by this collection. (In other words, this method must allocate a new array even if this collection is backed by an array). The caller is thus free to modify the returned array.
- Specified by:
toArray
in interfaceCollection<E>
- Overrides:
toArray
in classAbstractCollection<E>
- Returns:
- an array, whose runtime component
type is
Object
, containing all of the elements in this collection
-
toArray
@CanIgnoreReturnValue public final <T extends @Nullable Object> T[] toArray(T[] other)
Description copied from class:java.util.AbstractCollection
Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array. If the collection fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this collection.If this collection fits in the specified array with room to spare (i.e., the array has more elements than this collection), the element in the array immediately following the end of the collection is set to
null
. (This is useful in determining the length of this collection only if the caller knows that this collection does not contain anynull
elements.)If this collection makes any guarantees as to what order its elements are returned by its iterator, this method must return the elements in the same order.
- Specified by:
toArray
in interfaceCollection<E>
- Overrides:
toArray
in classAbstractCollection<E>
- Type Parameters:
T
- the component type of the array to contain the collection- Parameters:
other
- the array into which the elements of this collection are to be stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose.- Returns:
- an array containing all of the elements in this collection
-
contains
public abstract boolean contains(@CheckForNull Object object)
Description copied from class:java.util.AbstractCollection
Returnstrue
if this collection contains the specified element. More formally, returnstrue
if and only if this collection contains at least one elemente
such thatObjects.equals(o, e)
.- Specified by:
contains
in interfaceCollection<E>
- Overrides:
contains
in classAbstractCollection<E>
- Parameters:
object
- element whose presence in this collection is to be tested- Returns:
true
if this collection contains the specified element
-
add
@CanIgnoreReturnValue @Deprecated public final boolean add(E e)
Deprecated.Unsupported operation.Guaranteed to throw an exception and leave the collection unmodified.- Specified by:
add
in interfaceCollection<E>
- Overrides:
add
in classAbstractCollection<E>
- Parameters:
e
- element whose presence in this collection is to be ensured- Returns:
true
if this collection changed as a result of the call- Throws:
UnsupportedOperationException
- always
-
remove
@CanIgnoreReturnValue @Deprecated public final boolean remove(@CheckForNull Object object)
Deprecated.Unsupported operation.Guaranteed to throw an exception and leave the collection unmodified.- Specified by:
remove
in interfaceCollection<E>
- Overrides:
remove
in classAbstractCollection<E>
- Parameters:
object
- element to be removed from this collection, if present- Returns:
true
if an element was removed as a result of this call- Throws:
UnsupportedOperationException
- always
-
addAll
@CanIgnoreReturnValue @Deprecated public final boolean addAll(Collection<? extends E> newElements)
Deprecated.Unsupported operation.Guaranteed to throw an exception and leave the collection unmodified.- Specified by:
addAll
in interfaceCollection<E>
- Overrides:
addAll
in classAbstractCollection<E>
- Parameters:
newElements
- collection containing elements to be added to this collection- Returns:
true
if this collection changed as a result of the call- Throws:
UnsupportedOperationException
- always- See Also:
AbstractCollection.add(Object)
-
removeAll
@CanIgnoreReturnValue @Deprecated public final boolean removeAll(Collection<?> oldElements)
Deprecated.Unsupported operation.Guaranteed to throw an exception and leave the collection unmodified.- Specified by:
removeAll
in interfaceCollection<E>
- Overrides:
removeAll
in classAbstractCollection<E>
- Parameters:
oldElements
- collection containing elements to be removed from this collection- Returns:
true
if this collection changed as a result of the call- Throws:
UnsupportedOperationException
- always- See Also:
AbstractCollection.remove(Object)
,AbstractCollection.contains(Object)
-
removeIf
@CanIgnoreReturnValue @Deprecated public final boolean removeIf(Predicate<? super E> filter)
Deprecated.Unsupported operation.Guaranteed to throw an exception and leave the collection unmodified.- Specified by:
removeIf
in interfaceCollection<E>
- Parameters:
filter
- a predicate which returnstrue
for elements to be removed- Returns:
true
if any elements were removed- Throws:
UnsupportedOperationException
- always
-
retainAll
@Deprecated public final boolean retainAll(Collection<?> elementsToKeep)
Deprecated.Unsupported operation.Guaranteed to throw an exception and leave the collection unmodified.- Specified by:
retainAll
in interfaceCollection<E>
- Overrides:
retainAll
in classAbstractCollection<E>
- Parameters:
elementsToKeep
- collection containing elements to be retained in this collection- Returns:
true
if this collection changed as a result of the call- Throws:
UnsupportedOperationException
- always- See Also:
AbstractCollection.remove(Object)
,AbstractCollection.contains(Object)
-
clear
@Deprecated public final void clear()
Deprecated.Unsupported operation.Guaranteed to throw an exception and leave the collection unmodified.- Specified by:
clear
in interfaceCollection<E>
- Overrides:
clear
in classAbstractCollection<E>
- Throws:
UnsupportedOperationException
- always
-
asList
public ImmutableList<E> asList()
Returns anImmutableList
containing the same elements, in the same order, as this collection.Performance note: in most cases this method can return quickly without actually copying anything. The exact circumstances under which the copy is performed are undefined and subject to change.
- Since:
- 2.0
-
-