@GwtCompatible(emulated=true) public abstract class ImmutableCollection<E> extends AbstractCollection<E> implements Serializable
Collection
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
with Collection
itself). Prefer subtypes such as ImmutableSet
or ImmutableList
, which have well-defined Object.equals(java.lang.Object)
semantics, thus avoiding a common source
of bugs and confusion.
Immutable-
collectionsThe remainder of this documentation applies to every public Immutable-
type in this
package, whether it is a subtype of ImmutableCollection
or not.
Each makes the following guarantees:
Collections.unmodifiableCollection(java.util.Collection<? extends T>)
, whose contents change whenever the wrapped
collection is modified.
ImmutableSortedSet.naturalOrder()
). See the appropriate
factory method for details. View collections such as ImmutableMultiset.elementSet()
iterate in the same order as the parent, except as noted.
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 as List
).
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, accept Iterable
and have your method or constructor body pass it to the
appropriate copyOf
method itself.
Expressing the immutability guarantee directly in the type that user code references is a
powerful advantage. Although Java 9 offers certain immutable collection factory methods, like
Set.of
,
we recommend continuing to use these immutable collection classes for this reason.
Except for logically "abstract" types like ImmutableCollection
itself, each Immutable
type provides the static operations you need to obtain instances of that type. These
usually include:
of
, accepting an explicit list of elements or entries.
copyOf
(or copyOfSorted
), accepting an existing
collection whose contents should be copied.
Builder
class which can be used to populate a new immutable instance.
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.
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.
ImmutableMap.keySet
or ImmutableList.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 appropriate copyOf
method
to obtain a correctly-sized copy.
Builder
class can be assumed to be
no worse, and possibly better, than creating a mutable collection and copying it.
hashCode
implementation, it should cache it itself.
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 the Guava User Guide article on immutable collections.
Modifier and Type | Class and Description |
---|---|
static class |
ImmutableCollection.Builder<E>
Abstract base class for builders of
ImmutableCollection types. |
Modifier and Type | Method and Description |
---|---|
boolean |
add(E e)
Deprecated.
Unsupported operation.
|
boolean |
addAll(Collection<? extends E> newElements)
Deprecated.
Unsupported operation.
|
ImmutableList<E> |
asList()
Returns an
ImmutableList containing the same elements, in the same order, as this
collection. |
void |
clear()
Deprecated.
Unsupported operation.
|
abstract boolean |
contains(Object object)
Returns true 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 |
retainAll(Collection<?> elementsToKeep)
Deprecated.
Unsupported operation.
|
Object[] |
toArray()
Returns an array containing all of the elements in this collection.
|
<T> 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.
|
containsAll, isEmpty, size, toString
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
equals, hashCode, parallelStream, removeIf, spliterator, stream
public abstract UnmodifiableIterator<E> iterator()
iterator
in interface Iterable<E>
iterator
in interface Collection<E>
iterator
in class AbstractCollection<E>
public final Object[] toArray()
java.util.AbstractCollection
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.
This method acts as bridge between array-based and collection-based APIs.
This implementation returns an array containing all the elements
returned by this collection's iterator, in the same order, stored in
consecutive elements of the array, starting with index 0
.
The length of the returned array is equal to the number of elements
returned by the iterator, even if the size of this collection changes
during iteration, as might happen if the collection permits
concurrent modification during iteration. The size
method is
called only as an optimization hint; the correct result is returned
even if the iterator returns a different number of elements.
This method is equivalent to:
List<E> list = new ArrayList<E>(size());
for (E e : this)
list.add(e);
return list.toArray();
toArray
in interface Collection<E>
toArray
in class AbstractCollection<E>
public final <T> T[] toArray(T[] other)
java.util.AbstractCollection
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 any null 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.
Like the Collection.toArray()
method, this method acts as bridge between
array-based and collection-based APIs. Further, this method allows
precise control over the runtime type of the output array, and may,
under certain circumstances, be used to save allocation costs.
Suppose x is a collection known to contain only strings. The following code can be used to dump the collection into a newly allocated array of String:
String[] y = x.toArray(new String[0]);Note that toArray(new Object[0]) is identical in function to toArray().
This implementation returns an array containing all the elements
returned by this collection's iterator in the same order, stored in
consecutive elements of the array, starting with index 0
.
If the number of elements returned by the iterator is too large to
fit into the specified array, then the elements are returned in a
newly allocated array with length equal to the number of elements
returned by the iterator, even if the size of this collection
changes during iteration, as might happen if the collection permits
concurrent modification during iteration. The size
method is
called only as an optimization hint; the correct result is returned
even if the iterator returns a different number of elements.
This method is equivalent to:
List<E> list = new ArrayList<E>(size());
for (E e : this)
list.add(e);
return list.toArray(a);
toArray
in interface Collection<E>
toArray
in class AbstractCollection<E>
T
- the runtime type of the array to contain the collectionother
- 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.public abstract boolean contains(@Nullable Object object)
java.util.AbstractCollection
This implementation iterates over the elements in the collection, checking each element in turn for equality with the specified element.
contains
in interface Collection<E>
contains
in class AbstractCollection<E>
object
- element whose presence in this collection is to be tested@Deprecated public final boolean add(E e)
add
in interface Collection<E>
add
in class AbstractCollection<E>
e
- element whose presence in this collection is to be ensuredUnsupportedOperationException
- always@Deprecated public final boolean remove(Object object)
remove
in interface Collection<E>
remove
in class AbstractCollection<E>
object
- element to be removed from this collection, if presentUnsupportedOperationException
- always@Deprecated public final boolean addAll(Collection<? extends E> newElements)
addAll
in interface Collection<E>
addAll
in class AbstractCollection<E>
newElements
- collection containing elements to be added to this collectionUnsupportedOperationException
- alwaysAbstractCollection.add(Object)
@Deprecated public final boolean removeAll(Collection<?> oldElements)
removeAll
in interface Collection<E>
removeAll
in class AbstractCollection<E>
oldElements
- collection containing elements to be removed from this collectionUnsupportedOperationException
- alwaysAbstractCollection.remove(Object)
,
AbstractCollection.contains(Object)
@Deprecated public final boolean retainAll(Collection<?> elementsToKeep)
retainAll
in interface Collection<E>
retainAll
in class AbstractCollection<E>
elementsToKeep
- collection containing elements to be retained in this collectionUnsupportedOperationException
- alwaysAbstractCollection.remove(Object)
,
AbstractCollection.contains(Object)
@Deprecated public final void clear()
clear
in interface Collection<E>
clear
in class AbstractCollection<E>
UnsupportedOperationException
- alwayspublic ImmutableList<E> asList()
ImmutableList
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.
Copyright © 2010–2017. All rights reserved.