Collections Framework
Collection Interface
Analyze the root Collection interface contracts, including bulk, mutation, and stream operations.
Interview: Focuses on methods present in Collection, iterator factory contract, and bulk operations like retainAll/containsAll.
The java.util.Collection interface represents a group of objects known as its elements. It defines basic mutation operations (add, remove), queries (size, isEmpty, contains), and structural conversions (toArray, stream).
Basic Operations
Includes add(E), remove(Object), and contains(Object) which return booleans indicating state modification.
Bulk Operations
Performs algebraic set operations: addAll, removeAll, containsAll, and retainAll (intersection).
Iterable Contract
Extends Iterable<E>, forcing implementations to supply an iterator() for collection traversal.
Core Methods and Contracts
The Collection interface provides methods that operate on elements individually or collectively:
boolean add(E e):Inserts the element. Returns false if the collection does not allow duplicates and already contains it.boolean retainAll(Collection<?> c):Keeps only elements contained in target collectionc, modifying the host object.Object[] toArray():Safely copies elements into a new heap array.
Common Pitfalls
- Modifying collection during iteration: Directly calling
collection.remove()while iterating with a loop, causing aConcurrentModificationException. Use the iterator's own remove method instead. - Null pointer when calling retainAll: Passing a null collection to bulk operations, which raises a
NullPointerException.
Best Practices
- Use removeIf for filter-deletes: Use Java 8's
collection.removeIf(predicate)to safely remove items without manual iteration code. - Specify Array Type: Use
toArray(new T[0])rather thantoArray()to get a correctly typed array instead of an rawObject[].
Interview-Relevant Information
Q1: What does retainAll(Collection<?> c) do?
Answer: It retains only the elements in this collection that are contained in the specified collection c. It removes all other elements, acting as a set intersection operation.
Q2: Why does add(E e) return a boolean?
Answer: It returns true if the collection changed as a result of the call. For example, calling add on a Set will return false if the element was already present.
Quick Checklist
Can you list four query methods, explain what retainAll does, and state which parent interface provides the iterator method? If yes, you understand Collection interface.
Use Cases
Filtering collection models using predicates during runtime processing.
Creating type-safe collections from bulk data sources.
Common Mistakes
Calling toArray without passing a typed array, causing type casting exceptions.
Modifying a collection directly inside a standard for-each loop.