The Collection interface is at the root of the hierarchy and defines the most basic operations supported by all collections. It doesn’t directly support indexing but provides methods like add, remove, contains, isEmpty, and size. Implementations of Collection include Set and List, each with its unique characteristics.
Core Methods of Collection Interface
- Basic Operations:
- int size(): Returns the number of elements in the collection.
- boolean isEmpty(): Returns true if the collection contains no elements, false otherwise.
- boolean contains(Object o): Returns true if the collection contains the specified element o.
- Adding and Removing Elements:
- boolean add(E e): Adds the specified element e to the collection if not already present.
- boolean remove(Object o): Removes a single instance of the specified element o from the collection, if present.
- boolean addAll(Collection<? extends E> c): Adds all elements from collection c to this collection, if not already present.
- boolean removeAll(Collection<?> c): Removes all elements from this collection that are also contained in the specified collection c.
- boolean retainAll(Collection<?> c): Retains only the elements in this collection that are contained in the specified collection c.
- void clear(): Removes all elements from the collection.
- Checking Contents and Converting:
- boolean containsAll(Collection<?> c): Returns true if the collection contains all elements in the specified collection c.
- Object[] toArray(): Returns an array containing all of the elements in this collection.
- <T> T[] toArray(T[] a): Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array a.
- Iteration and Stream Operations:
- Iterator<E> iterator(): Returns an iterator over the elements in this collection.
- default Stream<E> stream(): Returns a sequential Stream with this collection as its source.
- default Stream<E> parallelStream(): Returns a possibly parallel Stream with this collection as its source.