Java Notes

Collection Interface

The Collection interface is the parent of the List and Set interfaces, but not Map.

Assume the following declaration for identifiers in the table below:

Collection coll; boolean b; Object obj; int i; Iterator it;
ReturnsMethodAction
Adding objects to a collection
b = coll.add(obj) Adds obj to this collection. Returns true if the collection was changed because of the add (eg, it will always be true for adding to a List, but will be false when adding to a Set that already contains this object).
b = coll.addAll(coll) Adds all elements of obj to this collection. Returns true if the collection was changed because of the addition.
Removing objects from a collection
 coll.clear() Removes all elements from the collection.
b = coll.remove(obj) Removes one occurrence of obj from this collection. Returns true if the collection was changed because of this operation.
b = coll.removeAll(coll) Removes all elements of coll from this collection. Returns true if the collection was changed because of this operation.
b = coll.retainAll(coll) Removes all elements of which are not in coll from this collection. Returns true if the collection was changed because of this operation.
Testing for presence in a collection
b = coll.contains(obj) Returns true if obj is in this collection.
b = coll.containsAll(coll) Returns true if all the members of coll are in this collection.
b = coll.isEmpty() Returns true if there are no objects in this collection.
Other
it = coll.iterator() Returns an iterator for this collection. The order of elements is only specified if the underlying collection has an ordering (eg, List and TreeSet so, HashSet doesn't).
i = coll.size() Returns the number of objects in this collection.
Object[] = coll.toArray() Returns an array containing the elements of this collection.
Object[] = coll.toArray(Object[]) Returns an array containing the elements of this collection.